Skip to content

Commit ac4bf0c

Browse files
chore: sync from ark-apis b8f03d31d2
Auto-generated SDK sync from ark-apis at b8f03d31d2190a20ba8efa0021a9b18dd29fcb67. Generated files are overwritten by the sync pipeline and should not be edited by hand. Sync-Source-Commit: 9652692db585ba558b0c37e4b331940ccc54b15d Ark-APIs-Commit: b8f03d31d2190a20ba8efa0021a9b18dd29fcb67 Release-Version: 0.23.0
1 parent 31b3c27 commit ac4bf0c

7 files changed

Lines changed: 539 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,48 @@ client.chat.completions.create(
290290
)
291291
```
292292

293+
## Audio generation
294+
295+
`client.audio_generation.create(...)` supports reference audio generation, audio
296+
separation, and video dubbing through `POST /api/v3/contents/generations`. It returns
297+
an `AudioGenerationResponse` with typed audio tracks, subtitle artifacts, and usage.
298+
This is a complete JSON response, not a task to poll or an SSE stream.
299+
300+
Use a model or endpoint enabled for this API. For example, with `ARK_API_KEY`,
301+
`ARK_AUDIO_MODEL`, and `AUDIO_URL` set in your environment:
302+
303+
```python
304+
import os
305+
from arkruntime import Ark
306+
from arkruntime.types.audio_generation import AudioRole
307+
308+
with Ark.volc(timeout=600.0) as client:
309+
result = client.audio_generation.create(
310+
model=os.environ["ARK_AUDIO_MODEL"],
311+
content=[
312+
{"type": "text", "text": "Read this sentence aloud."},
313+
{
314+
"type": "audio_url",
315+
"audio_url": {"url": os.environ["AUDIO_URL"]},
316+
"role": AudioRole.reference_audio,
317+
},
318+
],
319+
)
320+
print(result.content)
321+
```
322+
323+
For asynchronous Python calls, use `AsyncArk` and
324+
`await client.audio_generation.create(...)`; the endpoint still returns the same
325+
complete JSON response. Optional arguments are omitted by default; passing `None`
326+
sends JSON `null`. Explicit `False`, `0`, and empty lists are preserved. The server
327+
validates scene-specific combinations; in particular, omit reference-only audio
328+
rate controls for separation and dubbing.
329+
330+
The [audio generation example](./examples/volc/audio_generation.py) includes all
331+
three scenes and a `--async` option. It sends one real, potentially billable request
332+
only when run explicitly. Standard `extra_headers`, `extra_query`, `extra_body`,
333+
and per-request `timeout` options are supported.
334+
293335
## Batch inference
294336

295337
`client.batch.*` provides a synchronous high-throughput path with per-model concurrency control and automatic retry on `408`/`409`/`429`/`5xx`. See the [batch examples](./examples/batch) for thread-pool and async fan-out patterns.

‎examples/volc/audio_generation.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Run one audio generation request (may incur charges).
5+
6+
Set ARK_API_KEY and ARK_AUDIO_MODEL to your credentials and enabled model/endpoint.
7+
Set AUDIO_URL for reference/separation, or VIDEO_URL for dubbing.
8+
9+
python examples/volc/audio_generation.py --scene reference
10+
python examples/volc/audio_generation.py --scene separation
11+
python examples/volc/audio_generation.py --scene dubbing --async
12+
13+
URLs must be accessible to the service. No media is uploaded by this script.
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import argparse
19+
import asyncio
20+
import os
21+
22+
from arkruntime import Ark, AsyncArk
23+
from arkruntime.types.audio_generation import AudioRole, Include, OutputFormat, TargetLanguage, VideoRole
24+
from arkruntime.types.audio_generation.audio_generation_request_param import AudioGenerationRequestParam
25+
26+
27+
def build_request(scene: str) -> AudioGenerationRequestParam:
28+
model = os.environ["ARK_AUDIO_MODEL"]
29+
if scene == "dubbing":
30+
return {
31+
"model": model,
32+
"content": [
33+
{
34+
"type": "video_url",
35+
"video_url": {"url": os.environ["VIDEO_URL"]},
36+
"role": VideoRole.dubbing_video,
37+
}
38+
],
39+
"dubbing_config": {"target_language": TargetLanguage.en},
40+
"include": [Include.video_url, Include.subtitles_srt, Include.subtitles_source_srt],
41+
}
42+
43+
separation = scene == "separation"
44+
return {
45+
"model": model,
46+
"content": [
47+
{
48+
"type": "text",
49+
"text": "Separate speech and background music." if separation else "Read this sentence aloud.",
50+
},
51+
{
52+
"type": "audio_url",
53+
"audio_url": {"url": os.environ["AUDIO_URL"]},
54+
"role": AudioRole.separate_audio if separation else AudioRole.reference_audio,
55+
},
56+
],
57+
"output_format": OutputFormat.wav,
58+
}
59+
60+
61+
async def async_main(body: AudioGenerationRequestParam) -> None:
62+
async with AsyncArk.volc(api_key=os.environ["ARK_API_KEY"], timeout=600.0) as client:
63+
response = await client.audio_generation.create(**body)
64+
print(response.model_dump_json(indent=2, exclude_unset=True))
65+
66+
67+
def main() -> None:
68+
parser = argparse.ArgumentParser(description=__doc__)
69+
parser.add_argument("--scene", choices=["reference", "separation", "dubbing"], required=True)
70+
parser.add_argument("--async", dest="use_async", action="store_true")
71+
args = parser.parse_args()
72+
body = build_request(args.scene)
73+
if args.use_async:
74+
asyncio.run(async_main(body))
75+
else:
76+
with Ark.volc(api_key=os.environ["ARK_API_KEY"], timeout=600.0) as client:
77+
response = client.audio_generation.create(**body)
78+
print(response.model_dump_json(indent=2, exclude_unset=True))
79+
80+
81+
if __name__ == "__main__":
82+
main()

‎src/arkruntime/_client.py‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242

4343

4444
class Ark(SyncAPIClient):
45+
audio_generation: resources.AudioGeneration
4546
beta: beta.Beta
4647
chat: resources.Chat
4748
embeddings: resources.Embeddings
@@ -118,6 +119,7 @@ def __init__(
118119
self._certificate_manager: E2ECertificateManager | None = None
119120

120121
self.beta = beta.Beta(self)
122+
self.audio_generation = resources.AudioGeneration(self)
121123
self.chat = resources.Chat(self)
122124
self.embeddings = resources.Embeddings(self)
123125
self.tokenization = resources.Tokenization(self)
@@ -197,6 +199,7 @@ def get_resource_type_by_endpoint_id(self, endpoint_id: str) -> str:
197199

198200

199201
class AsyncArk(AsyncAPIClient):
202+
audio_generation: resources.AsyncAudioGeneration
200203
beta: beta.AsyncBeta
201204
chat: resources.AsyncChat
202205
embeddings: resources.AsyncEmbeddings
@@ -273,6 +276,7 @@ def __init__(
273276
self._certificate_manager: E2ECertificateManager | None = None
274277

275278
self.beta = beta.AsyncBeta(self)
279+
self.audio_generation = resources.AsyncAudioGeneration(self)
276280
self.chat = resources.AsyncChat(self)
277281
self.embeddings = resources.AsyncEmbeddings(self)
278282
self.tokenization = resources.AsyncTokenization(self)
@@ -304,12 +308,15 @@ def byteplus(cls, **kwargs) -> "AsyncArk":
304308
"""See :meth:`Ark.byteplus`."""
305309
return _from_cloud(cls, Cloud.BYTEPLUS, **kwargs)
306310

307-
def _get_endpoint_sts_token(self, endpoint_id: str):
311+
def _get_endpoint_sts_token(self, endpoint_id: str, project_name: str = None):
308312
if self._sts_token_manager is None:
309313
if self.ak is None or self.sk is None:
310314
raise ArkAPIError("must set ak and sk before get endpoint token.")
311315
self._sts_token_manager = StsTokenManager(self.ak, self.sk, self.region)
312-
return self._sts_token_manager.get(endpoint_id)
316+
resource_type: str = self.get_resource_type_by_endpoint_id(endpoint_id)
317+
if resource_type == _PRESETENDPOINT_RESOURCE_TYPE and (project_name is None or project_name.strip() == ""):
318+
raise ArkAPIError("must set project_name when get preset endpoint token.")
319+
return self._sts_token_manager.get(endpoint_id, resource_type=resource_type, project_name=project_name)
313320

314321
def _get_endpoint_certificate(self, endpoint_id: str) -> key_agreement_client:
315322
if self._certificate_manager is None:
@@ -333,6 +340,14 @@ async def get_model_breaker(self, model_name: str) -> ModelBreaker:
333340
async with self.model_breaker_lock:
334341
return self.model_breaker_map[model_name]
335342

343+
def get_resource_type_by_endpoint_id(self, endpoint_id: str) -> str:
344+
if endpoint_id.startswith("ep-m-"):
345+
return _PRESETENDPOINT_RESOURCE_TYPE
346+
if endpoint_id.startswith("ep-"):
347+
return _DEFAULT_RESOURCE_TYPE
348+
# for model id, default to preset endpoint
349+
return _PRESETENDPOINT_RESOURCE_TYPE
350+
336351

337352
def _from_cloud(cls, cloud: str, **kwargs):
338353
"""Resolve a cloud preset, fill in env-var defaults for the cloud's

‎src/arkruntime/resources/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# License text: https://github.com/volcengine/ark-runtime-python/blob/main/LICENSE
44

55
from .agents import Agents, AsyncAgents
6+
from .audio_generation import AsyncAudioGeneration, AudioGeneration
67
from .batch import AsyncBatch, Batch
78
from .chat import AsyncChat, Chat
89
from .checkpoints import AsyncCheckpoints, Checkpoints
@@ -32,6 +33,8 @@
3233
from .vaults import AsyncCredentials, AsyncVaults, Credentials, Vaults
3334

3435
__all__ = [
36+
"AudioGeneration",
37+
"AsyncAudioGeneration",
3538
"Checkpoints",
3639
"Chat",
3740
"AsyncCheckpoints",
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
from .audio_generation import AsyncAudioGeneration, AudioGeneration
5+
6+
__all__ = ["AudioGeneration", "AsyncAudioGeneration"]
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
from __future__ import annotations
5+
6+
from typing import List, Optional
7+
8+
import httpx
9+
10+
from ..._base_client import make_request_options
11+
from ..._resource import AsyncAPIResource, SyncAPIResource
12+
from ..._types import NOT_GIVEN, Body, Headers, NotGiven, Query
13+
from ..._utils import async_with_sts_token, with_sts_token
14+
from ...types.audio_generation.audio_config_param import AudioConfigParam
15+
from ...types.audio_generation.audio_generation_response import AudioGenerationResponse
16+
from ...types.audio_generation.content_param import ContentParam
17+
from ...types.audio_generation.dubbing_config_param import DubbingConfigParam
18+
from ...types.audio_generation.include import Include
19+
from ...types.audio_generation.output_format import OutputFormat
20+
21+
__all__ = ["AudioGeneration", "AsyncAudioGeneration"]
22+
23+
_PATH = "/contents/generations"
24+
25+
26+
class AudioGeneration(SyncAPIResource):
27+
@with_sts_token
28+
def create(
29+
self,
30+
*,
31+
model: str,
32+
content: List[ContentParam],
33+
dubbing_config: Optional[DubbingConfigParam] | NotGiven = NOT_GIVEN,
34+
output_format: Optional[OutputFormat] | NotGiven = NOT_GIVEN,
35+
audio_config: Optional[AudioConfigParam] | NotGiven = NOT_GIVEN,
36+
include: Optional[List[Include]] | NotGiven = NOT_GIVEN,
37+
watermark: Optional[bool] | NotGiven = NOT_GIVEN,
38+
extra_headers: Headers | None = None,
39+
extra_query: Query | None = None,
40+
extra_body: Body | None = None,
41+
timeout: float | httpx.Timeout | None = None,
42+
) -> AudioGenerationResponse:
43+
"""Generate reference audio, separate audio, or dub a video.
44+
45+
This endpoint returns a complete JSON response, not a task or SSE stream.
46+
Omitted optional arguments are not sent; explicit None is sent as null.
47+
Scene-specific parameter validation is performed by the server.
48+
"""
49+
return self._post(
50+
_PATH,
51+
# RequestOptions removes NOT_GIVEN while preserving explicit nulls,
52+
# including nested nulls. maybe_transform would discard those nulls.
53+
body={
54+
"model": model,
55+
"content": content,
56+
"dubbing_config": dubbing_config,
57+
"output_format": output_format,
58+
"audio_config": audio_config,
59+
"include": include,
60+
"watermark": watermark,
61+
},
62+
options=make_request_options(
63+
extra_headers=extra_headers,
64+
extra_query=extra_query,
65+
extra_body=extra_body,
66+
timeout=timeout,
67+
),
68+
cast_to=AudioGenerationResponse,
69+
)
70+
71+
72+
class AsyncAudioGeneration(AsyncAPIResource):
73+
@async_with_sts_token
74+
async def create(
75+
self,
76+
*,
77+
model: str,
78+
content: List[ContentParam],
79+
dubbing_config: Optional[DubbingConfigParam] | NotGiven = NOT_GIVEN,
80+
output_format: Optional[OutputFormat] | NotGiven = NOT_GIVEN,
81+
audio_config: Optional[AudioConfigParam] | NotGiven = NOT_GIVEN,
82+
include: Optional[List[Include]] | NotGiven = NOT_GIVEN,
83+
watermark: Optional[bool] | NotGiven = NOT_GIVEN,
84+
extra_headers: Headers | None = None,
85+
extra_query: Query | None = None,
86+
extra_body: Body | None = None,
87+
timeout: float | httpx.Timeout | None = None,
88+
) -> AudioGenerationResponse:
89+
"""Asynchronously call the non-streaming audio generation endpoint.
90+
91+
Omitted optional arguments are not sent; explicit None is sent as null.
92+
Scene-specific parameter validation is performed by the server.
93+
"""
94+
return await self._post(
95+
_PATH,
96+
body={
97+
"model": model,
98+
"content": content,
99+
"dubbing_config": dubbing_config,
100+
"output_format": output_format,
101+
"audio_config": audio_config,
102+
"include": include,
103+
"watermark": watermark,
104+
},
105+
options=make_request_options(
106+
extra_headers=extra_headers,
107+
extra_query=extra_query,
108+
extra_body=extra_body,
109+
timeout=timeout,
110+
),
111+
cast_to=AudioGenerationResponse,
112+
)

0 commit comments

Comments
 (0)