Doubao API Developer Guide: Complete Volcengine Integration Tutorial (2026 Latest)
ByteDance Doubao Seed 2.1 API guide: Python SDK, TTS speech, image/video generation, and Agent mode with hands-on examples.
What This Tutorial Covers
You will learn:
- How to obtain a Doubao API Key on Volcengine
- How to call Doubao Seed 2.0 series models
- How to use the TTS speech synthesis API
- How to call AI image/video generation
- How to configure Thinking mode
🎯 Doubao is China’s most-used AI application (over 100M MAU (per public reports)) with the most comprehensive multimodal capabilities. This tutorial helps you integrate it into your projects.
Why Choose Doubao?
| Feature | Doubao Seed 2.0 | Other Models |
|---|---|---|
| Multimodal coverage | Text + Image + Video + Speech | Typically 1-2 modalities |
| User base | 157M MAU | — |
| Basic features | Free | Partially paid |
| Pro pricing | ~$4/month | — |
| Ecosystem integration | Douyin/TikTok ecosystem | — |
Doubao Model Family
| Model Series | Characteristics | Best Use |
|---|---|---|
| Seed 2.1 Pro | Flagship, deep reasoning | High-value complex tasks |
| Seed 2.1 Turbo | Balanced, high value | Chatbots, content generation |
| Seed 2.1 Mini | Lightweight, ultra-low latency | High concurrency scenarios |
| Seed 2.1 Code | Code-specific | Code generation, debugging, refactoring |
| Seedream 5 | AI image generation | Image creation, design |
| Seedance 2.5 | AI video generation | Video creation |
Step 1: Get an API Key
Doubao’s official API is provided through the Volcengine platform:
- Log in to the Volcengine Console
- Activate the desired Doubao models under “Service Activation”
- Create an API Key under “API Key Management”
- Create an inference endpoint (Endpoint ID)
export VOLCENGINE_API_KEY="your-api-key-here"
export VOLCENGINE_ENDPOINT_ID="your-endpoint-id"
Step 2: Install the SDK
pip install openai
pip install doubao-speech # Dedicated package for speech features
Step 3: Your First API Call
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("VOLCENGINE_API_KEY"),
base_url="https://ark.cn-beijing.volces.com/api/v3",
)
response = client.chat.completions.create(
model=os.environ.get("VOLCENGINE_ENDPOINT_ID"), # Your inference endpoint ID
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, please introduce yourself."}
],
temperature=0.7,
max_tokens=512,
)
print(response.choices[0].message.content)
ark.cn-beijing.volces.com/api/v3, which differs from the OpenAI-compatible endpoints used by DeepSeek/Kimi. The model name uses the inference endpoint ID you created (e.g., doubao-pro-32k).
Step 4: Thinking Mode
response = client.chat.completions.create(
model="your-endpoint-id",
messages=[
{"role": "user", "content": "Which is larger, 9.9 or 9.11?"}
],
extra_body={
"thinking": {"type": "enabled"} # Enable thinking mode
},
)
print(response.choices[0].message.content)
| thinking value | Behavior |
|---|---|
enabled | Force output of reasoning process |
disabled | Output final answer only |
auto | Model decides automatically |
Step 5: Speech Synthesis (TTS)
Install the dedicated Doubao speech package:
pip install doubao-speech
from doubao_speech import synthesize, transcribe
# Text-to-speech
synthesize("Hello, welcome to Doubao AI speech synthesis.", "output.mp3")
print("Speech file generated: output.mp3")
# Speech-to-text
text = transcribe("meeting.mp3")
print(f"Recognition result: {text}")
Configure Speech Credentials
export VOLCENGINE_APP_ID="your-app-id"
export VOLCENGINE_ACCESS_TOKEN="your-access-token"
Step 6: Multimodal Vision Understanding
response = client.chat.completions.create(
model="your-vision-endpoint-id",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image? Please describe in detail."},
{
"type": "image_url",
"image_url": {"url": "https://example.com/image.jpg"}
}
]
}],
)
print(response.choices[0].message.content)
Step 7: AI Video Generation (Seedance 2.0)
import time
# Create a video generation task
response = client.chat.completions.create(
model="doubao-seedance-2.5",
messages=[{
"role": "user",
"content": "An astronaut cat walking through neon-lit Tokyo streets at night, cinematic quality, 4K"
}],
)
task_id = response.task_id # Get the task ID
print(f"Task submitted, ID: {task_id}")
# Poll task status
while True:
status = client.tasks.retrieve(task_id)
if status.status == "succeeded":
print(f"Video generation complete! URL: {status.result.url}")
break
elif status.status == "failed":
print(f"Task failed: {status.error}")
break
print("Generating, please wait...")
time.sleep(5)
Doubao vs. Other Models
| Feature | Doubao Seed 2.0 | DeepSeek V4 | Qwen 3.7 |
|---|---|---|---|
| Coding | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Multimodal | ⭐⭐⭐⭐⭐ | ❌ | ⭐⭐⭐⭐ |
| AI Video | ✅ | ❌ | ❌ |
| AI Images | ✅ | ❌ | ⚠️ Limited |
| Voice TTS | ✅ | ❌ | ✅ |
| Free tier | ✅ Basic free | ✅ Web free | ✅ Basic free |
| Best for | Creators, general users | Developers, programmers | Enterprise users |
Step 8: Streaming Output
For chatbots and any user-facing interface, streaming makes the response feel instant instead of making the user stare at a spinner. Set stream=True and iterate over the chunks:
stream = client.chat.completions.create(
model=os.environ.get("VOLCENGINE_ENDPOINT_ID"),
messages=[
{"role": "user", "content": "Write a 200-word intro to ByteDance."}
],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)
print() # final newline
Step 9: Production-Grade Error Handling
The examples above assume every call succeeds. In production, network timeouts, rate limits, and invalid endpoints are routine. Wrap calls with typed error handling and retry with exponential backoff:
import time
from openai import OpenAI, APITimeoutError, RateLimitError, APIStatusError
def call_with_retry(client, messages, model, max_retries: int = 3):
"""Call the Doubao API with exponential-backoff retry on transient errors."""
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model=model,
messages=messages,
timeout=30, # seconds
)
except RateLimitError:
# 429: too many requests — back off and retry
wait = 2 ** attempt
print(f"Rate limited, retrying in {wait}s...")
time.sleep(wait)
except APITimeoutError:
# Request took too long — retry immediately once, then back off
print(f"Timeout on attempt {attempt + 1}, retrying...")
time.sleep(2 ** attempt)
except APIStatusError as e:
# 4xx/5xx with a response — non-retryable client errors should raise
if 400 <= e.status_code < 500 and e.status_code != 429:
raise # bad request, auth error, etc. — no point retrying
time.sleep(2 ** attempt)
raise RuntimeError(f"Failed after {max_retries} retries")
Common Errors and Fixes
| Error | Likely Cause | Fix |
|---|---|---|
AuthenticationError: invalid api key | Wrong key, or key not activated for this model | Re-check the key in API Key Management; confirm the model is activated under Service Activation |
model not found | Passed a model name instead of the endpoint ID | Doubao’s model field wants your inference endpoint ID, not doubao-pro-32k directly |
RateLimitError (429) | Exceeded QPS/TPM quota | Add backoff (see above); request a quota increase in the console |
region mismatch | Wrong base URL region | Match the endpoint region — cn-beijing vs other regions have different base URLs |
Empty content, only reasoning | Thinking mode returned reasoning but truncated the answer | Raise max_tokens; the reasoning trace consumes output budget too |
Estimating Your Costs
Doubao bills separately for input and output tokens, and multimodal generation (image/video) is billed per asset rather than per token. A rough monthly estimate for a text chatbot:
def estimate_monthly_cost(
requests_per_day: int,
avg_input_tokens: int,
avg_output_tokens: int,
input_price_per_1k: float, # check current Volcengine pricing
output_price_per_1k: float,
) -> float:
daily_input = requests_per_day * avg_input_tokens
daily_output = requests_per_day * avg_output_tokens
daily_cost = (
daily_input / 1000 * input_price_per_1k
+ daily_output / 1000 * output_price_per_1k
)
return daily_cost * 30
# Example: 10k requests/day, 500 in / 300 out tokens
monthly = estimate_monthly_cost(10_000, 500, 300, 0.0008, 0.002)
print(f"Estimated monthly text cost: ${monthly:.2f}")
FAQ
Q: Can the Doubao API be accessed from overseas?
A: Yes. Volcengine supports international access, but a Chinese phone number may be required for registration. Try international API gateways (e.g., CometAPI) first.
Q: Is the free tier sufficient?
A: Volcengine Ark provides approximately 500K tokens of trial credits per model, enough for development and testing. The basic Doubao edition is completely free (via web/app).
Q: Should I choose Doubao or DeepSeek?
A: Use DeepSeek for coding; use Doubao for multimodal creation (images/video/speech). They are not mutually exclusive — you can combine both.
Next Steps
- 2026 China AI Models Ultimate Comparison
- DeepSeek API Beginner Guide
- Volcengine Official Documentation
📝 Tutorial Version Notes: Based on Doubao Seed 2.1 API, tested and verified on June 20, 2026. Models and pricing may update — refer to official announcements.