File size: 39,189 Bytes
9410704 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 | import asyncio
import email.utils
import math
import time
import typing
from random import random
from elevenlabs.core.http_response import AsyncHttpResponse, HttpResponse
from elevenlabs.core.request_options import RequestOptions
from elevenlabs.flows.client import AsyncFlowsClient as AutogeneratedAsyncFlowsClient
from elevenlabs.flows.client import FlowsClient as AutogeneratedFlowsClient
from elevenlabs.flows.image.client import AsyncImageClient as AutogeneratedAsyncImageClient
from elevenlabs.flows.image.client import ImageClient as AutogeneratedImageClient
from elevenlabs.flows.templates.client import AsyncTemplatesClient as AutogeneratedAsyncTemplatesClient
from elevenlabs.flows.templates.client import TemplatesClient as AutogeneratedTemplatesClient
from elevenlabs.flows.templates.runs.client import AsyncRunsClient as AutogeneratedAsyncRunsClient
from elevenlabs.flows.templates.runs.client import RunsClient as AutogeneratedRunsClient
from elevenlabs.flows.text_to_speech.client import AsyncTextToSpeechClient as AutogeneratedAsyncTextToSpeechClient
from elevenlabs.flows.text_to_speech.client import TextToSpeechClient as AutogeneratedTextToSpeechClient
from elevenlabs.flows.video.client import AsyncVideoClient as AutogeneratedAsyncVideoClient
from elevenlabs.flows.video.client import VideoClient as AutogeneratedVideoClient
from elevenlabs.types.image_generation_request import ImageGenerationRequest
from elevenlabs.types.media_generation_response import (
MediaGenerationResponse_Completed,
MediaGenerationResponse_Failed,
)
from elevenlabs.types.template_run_input import TemplateRunInput
from elevenlabs.types.template_run_response import TemplateRunResponse
from elevenlabs.types.text_to_speech_generation_request import TextToSpeechGenerationRequest
from elevenlabs.types.video_generation_request import VideoGenerationRequest
from elevenlabs.types.webhook_target import WebhookTarget
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)
# Matches the server's shortest `Retry-After` (3s for image, audio and text), so the SDK polls no faster
# than the server would pace it when the header is missing.
DEFAULT_MIN_POLL_INTERVAL_SECONDS = 3.0
# Below this, a missing server hint would turn the wait into a tight loop of status checks.
_SMALLEST_MIN_POLL_INTERVAL_SECONDS = 0.5
# Spreads out clients that started together so their status checks don't arrive in lockstep.
_POLL_JITTER = 0.2
_TERMINAL_STATUSES = frozenset({"completed", "failed"})
T = typing.TypeVar("T")
TerminalMediaGenerationResponse = typing.Union[MediaGenerationResponse_Completed, MediaGenerationResponse_Failed]
"""What `create_and_wait` returns for a generation: always `completed` or `failed`, never in progress."""
class FlowsWaitTimeoutError(Exception):
"""
Raised by `create_and_wait` when a generation or template run is still unfinished after `wait_timeout_in_seconds` seconds.
The work keeps running on the server. Resume waiting by calling `get` with `id`
(and `template_id` for a template run), or let a webhook deliver the result.
"""
def __init__(
self,
*,
id: str,
wait_timeout_in_seconds: float,
last_response: typing.Any,
template_id: typing.Optional[str] = None,
) -> None:
self.id = id
self.template_id = template_id
self.wait_timeout_in_seconds = wait_timeout_in_seconds
self.last_response = last_response
status = getattr(last_response, "status", None)
if template_id is not None:
message = (
f"Template run {id} of template {template_id} is still {status} after {wait_timeout_in_seconds}s; "
"call `runs.get` with `template_id` and `id` to keep waiting"
)
else:
message = f"Generation {id} is still {status} after {wait_timeout_in_seconds}s; call `get` with this id to keep waiting"
super().__init__(message)
def _check_wait_options(wait_timeout_in_seconds: typing.Optional[float], min_interval: float) -> None:
# NaN passes every `<` check, and an infinite interval would never poll, so both are rejected explicitly.
if not math.isfinite(min_interval) or min_interval < _SMALLEST_MIN_POLL_INTERVAL_SECONDS:
raise ValueError(
f"min_poll_interval_in_seconds must be a finite number of at least {_SMALLEST_MIN_POLL_INTERVAL_SECONDS}s, got {min_interval}"
)
# Written as `not >= 0` so NaN fails too: a NaN deadline never compares as passed, so the wait would
# silently ignore the timeout. 0 times out straight after the create; None or inf waits indefinitely.
if wait_timeout_in_seconds is not None and not wait_timeout_in_seconds >= 0:
raise ValueError(f"wait_timeout_in_seconds must be at least 0s, got {wait_timeout_in_seconds}")
def _poll_request_options(request_options: typing.Optional[RequestOptions]) -> typing.Optional[RequestOptions]:
"""The caller's options for the status GETs: everything except body parameters, which only the create takes."""
if request_options is None or "additional_body_parameters" not in request_options:
return request_options
return typing.cast(RequestOptions, {k: v for k, v in request_options.items() if k != "additional_body_parameters"})
def _parse_retry_after(headers: typing.Mapping[str, str]) -> typing.Optional[float]:
"""
Seconds from a `Retry-After` header, given as whole seconds or an HTTP date (RFC 9110), or None if absent
or unparseable. Kept here rather than imported from the generated `core.http_client`, whose private
helpers can change on any regeneration.
"""
value = next((v for k, v in headers.items() if k.lower() == "retry-after"), None)
if value is None:
return None
value = value.strip()
if value.isdigit():
return float(value)
try:
retry_date = email.utils.parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if retry_date is None: # Python < 3.10 returns None instead of raising
return None
return max(retry_date.timestamp() - time.time(), 0.0)
def _poll_delay(headers: typing.Mapping[str, str], min_interval: float) -> float:
"""Seconds to wait before the next GET: the server's `Retry-After`, never below `min_interval`, plus 0-20% jitter."""
retry_after = _parse_retry_after(headers)
delay = max(retry_after if retry_after is not None else min_interval, min_interval)
return delay * (1 + random() * _POLL_JITTER)
def _is_terminal(response: typing.Any) -> bool:
return getattr(response, "status", None) in _TERMINAL_STATUSES
def _wait(
*,
id: str,
first_response: typing.Any,
first_headers: typing.Mapping[str, str],
get: typing.Callable[[], HttpResponse[T]],
started_at: float,
wait_timeout_in_seconds: typing.Optional[float],
min_interval: float,
template_id: typing.Optional[str] = None,
) -> T:
response: typing.Any = first_response
headers = first_headers
while not _is_terminal(response):
delay = _poll_delay(headers, min_interval)
if wait_timeout_in_seconds is not None:
# The last sleep ends on the deadline; the GET after it takes time, so the next pass raises.
remaining = started_at + wait_timeout_in_seconds - time.monotonic()
if remaining <= 0:
raise FlowsWaitTimeoutError(
id=id,
wait_timeout_in_seconds=wait_timeout_in_seconds,
last_response=response,
template_id=template_id,
)
delay = min(delay, remaining)
time.sleep(delay)
raw = get()
response, headers = raw.data, raw.headers
return typing.cast(T, response)
async def _async_wait(
*,
id: str,
first_response: typing.Any,
first_headers: typing.Mapping[str, str],
get: typing.Callable[[], typing.Awaitable[AsyncHttpResponse[T]]],
started_at: float,
wait_timeout_in_seconds: typing.Optional[float],
min_interval: float,
template_id: typing.Optional[str] = None,
) -> T:
response: typing.Any = first_response
headers = first_headers
while not _is_terminal(response):
delay = _poll_delay(headers, min_interval)
if wait_timeout_in_seconds is not None:
# The last sleep ends on the deadline; the GET after it takes time, so the next pass raises.
remaining = started_at + wait_timeout_in_seconds - time.monotonic()
if remaining <= 0:
raise FlowsWaitTimeoutError(
id=id,
wait_timeout_in_seconds=wait_timeout_in_seconds,
last_response=response,
template_id=template_id,
)
delay = min(delay, remaining)
await asyncio.sleep(delay)
raw = await get()
response, headers = raw.data, raw.headers
return typing.cast(T, response)
class ImageClient(AutogeneratedImageClient):
def create_and_wait(
self,
*,
request: ImageGenerationRequest,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TerminalMediaGenerationResponse:
"""
Start an image generation and wait until it is `completed` or `failed`, then return the final generation.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, set `webhook` on the request passed to `create`
and handle the webhook event instead of holding a process open.
A `failed` generation is returned, not raised; check `status` on the result.
Parameters
----------
request : ImageGenerationRequest
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the generation `id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TerminalMediaGenerationResponse
The generation in its terminal state: `MediaGenerationResponse_Completed` or `MediaGenerationResponse_Failed`.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = self.with_raw_response.create(request=request, request_options=request_options)
generation_id = created.data.id
poll_options = _poll_request_options(request_options)
return typing.cast(
TerminalMediaGenerationResponse,
_wait(
id=generation_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(generation_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
),
)
class AsyncImageClient(AutogeneratedAsyncImageClient):
async def create_and_wait(
self,
*,
request: ImageGenerationRequest,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TerminalMediaGenerationResponse:
"""
Start an image generation and wait until it is `completed` or `failed`, then return the final generation.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, set `webhook` on the request passed to `create`
and handle the webhook event instead of holding a process open.
A `failed` generation is returned, not raised; check `status` on the result.
Parameters
----------
request : ImageGenerationRequest
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the generation `id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TerminalMediaGenerationResponse
The generation in its terminal state: `MediaGenerationResponse_Completed` or `MediaGenerationResponse_Failed`.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = await self.with_raw_response.create(request=request, request_options=request_options)
generation_id = created.data.id
poll_options = _poll_request_options(request_options)
return typing.cast(
TerminalMediaGenerationResponse,
await _async_wait(
id=generation_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(generation_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
),
)
class VideoClient(AutogeneratedVideoClient):
def create_and_wait(
self,
*,
request: VideoGenerationRequest,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TerminalMediaGenerationResponse:
"""
Start a video generation and wait until it is `completed` or `failed`, then return the final generation.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, set `webhook` on the request passed to `create`
and handle the webhook event instead of holding a process open.
A `failed` generation is returned, not raised; check `status` on the result.
Parameters
----------
request : VideoGenerationRequest
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the generation `id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TerminalMediaGenerationResponse
The generation in its terminal state: `MediaGenerationResponse_Completed` or `MediaGenerationResponse_Failed`.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = self.with_raw_response.create(request=request, request_options=request_options)
generation_id = created.data.id
poll_options = _poll_request_options(request_options)
return typing.cast(
TerminalMediaGenerationResponse,
_wait(
id=generation_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(generation_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
),
)
class AsyncVideoClient(AutogeneratedAsyncVideoClient):
async def create_and_wait(
self,
*,
request: VideoGenerationRequest,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TerminalMediaGenerationResponse:
"""
Start a video generation and wait until it is `completed` or `failed`, then return the final generation.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, set `webhook` on the request passed to `create`
and handle the webhook event instead of holding a process open.
A `failed` generation is returned, not raised; check `status` on the result.
Parameters
----------
request : VideoGenerationRequest
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the generation `id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TerminalMediaGenerationResponse
The generation in its terminal state: `MediaGenerationResponse_Completed` or `MediaGenerationResponse_Failed`.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = await self.with_raw_response.create(request=request, request_options=request_options)
generation_id = created.data.id
poll_options = _poll_request_options(request_options)
return typing.cast(
TerminalMediaGenerationResponse,
await _async_wait(
id=generation_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(generation_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
),
)
class TextToSpeechClient(AutogeneratedTextToSpeechClient):
def create_and_wait(
self,
*,
request: TextToSpeechGenerationRequest,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TerminalMediaGenerationResponse:
"""
Start a text-to-speech generation and wait until it is `completed` or `failed`, then return the final generation.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, set `webhook` on the request passed to `create`
and handle the webhook event instead of holding a process open.
A `failed` generation is returned, not raised; check `status` on the result.
Charged per character via text-to-speech billing. Use this over `/v1/text-to-speech` for the asynchronous generation lifecycle or for models not offered there; for direct, synchronous speech synthesis, prefer `/v1/text-to-speech`.
Parameters
----------
request : TextToSpeechGenerationRequest
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the generation `id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TerminalMediaGenerationResponse
The generation in its terminal state: `MediaGenerationResponse_Completed` or `MediaGenerationResponse_Failed`.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = self.with_raw_response.create(request=request, request_options=request_options)
generation_id = created.data.id
poll_options = _poll_request_options(request_options)
return typing.cast(
TerminalMediaGenerationResponse,
_wait(
id=generation_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(generation_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
),
)
class AsyncTextToSpeechClient(AutogeneratedAsyncTextToSpeechClient):
async def create_and_wait(
self,
*,
request: TextToSpeechGenerationRequest,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TerminalMediaGenerationResponse:
"""
Start a text-to-speech generation and wait until it is `completed` or `failed`, then return the final generation.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, set `webhook` on the request passed to `create`
and handle the webhook event instead of holding a process open.
A `failed` generation is returned, not raised; check `status` on the result.
Charged per character via text-to-speech billing. Use this over `/v1/text-to-speech` for the asynchronous generation lifecycle or for models not offered there; for direct, synchronous speech synthesis, prefer `/v1/text-to-speech`.
Parameters
----------
request : TextToSpeechGenerationRequest
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the generation `id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TerminalMediaGenerationResponse
The generation in its terminal state: `MediaGenerationResponse_Completed` or `MediaGenerationResponse_Failed`.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = await self.with_raw_response.create(request=request, request_options=request_options)
generation_id = created.data.id
poll_options = _poll_request_options(request_options)
return typing.cast(
TerminalMediaGenerationResponse,
await _async_wait(
id=generation_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(generation_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
),
)
class RunsClient(AutogeneratedRunsClient):
def create_and_wait(
self,
template_id: str,
*,
inputs: typing.Dict[str, TemplateRunInput],
version_id: typing.Optional[str] = OMIT,
webhook: typing.Optional[WebhookTarget] = OMIT,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TemplateRunResponse:
"""
Start a run of a flows template and wait until its `status` is `completed` or `failed`, then return the final run.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, pass `webhook` to `create` and handle the
`flows_template_run` webhook instead of holding a process open.
A `failed` run is returned, not raised; check `status` on the result and on each output.
Parameters
----------
template_id : str
The ID of the template, as shown in the ElevenLabs app or by `GET /v1/flows/templates`.
inputs : typing.Dict[str, TemplateRunInput]
Input values keyed by input port id. Every input port of the version being run must be given; a missing or unknown id is rejected. Pass `{}` for a template with no inputs.
version_id : typing.Optional[str]
The template snapshot to run. Pass a specific version id to pin that snapshot, or `latest` (the default when omitted) to run the template's most recently published version. Only published versions can be pinned, except by the template's owner, who may also pin an unpublished saved snapshot to try it out before publishing. The live draft is never run through this API.
webhook : typing.Optional[WebhookTarget]
Include to send the run's result to the workspace's configured flows webhooks once the run's `status` reaches `completed` or `failed`. One event for the whole run: the `flows_template_run` event's `data` matches the terminal response of `GET /v1/flows/templates/{template_id}/runs/{run_id}`.
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the run `id` and `template_id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TemplateRunResponse
The run in its terminal state.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = self.with_raw_response.create(
template_id, inputs=inputs, version_id=version_id, webhook=webhook, request_options=request_options
)
run_id = created.data.id
poll_options = _poll_request_options(request_options)
return _wait(
id=run_id,
template_id=template_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(template_id, run_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
)
class AsyncRunsClient(AutogeneratedAsyncRunsClient):
async def create_and_wait(
self,
template_id: str,
*,
inputs: typing.Dict[str, TemplateRunInput],
version_id: typing.Optional[str] = OMIT,
webhook: typing.Optional[WebhookTarget] = OMIT,
wait_timeout_in_seconds: typing.Optional[float] = None,
min_poll_interval_in_seconds: float = DEFAULT_MIN_POLL_INTERVAL_SECONDS,
request_options: typing.Optional[RequestOptions] = None,
) -> TemplateRunResponse:
"""
Start a run of a flows template and wait until its `status` is `completed` or `failed`, then return the final run.
Between status checks this waits as long as the server suggests, never less than `min_poll_interval_in_seconds`.
This is meant for scripts and quickstarts: in production, pass `webhook` to `create` and handle the
`flows_template_run` webhook instead of holding a process open.
A `failed` run is returned, not raised; check `status` on the result and on each output.
Parameters
----------
template_id : str
The ID of the template, as shown in the ElevenLabs app or by `GET /v1/flows/templates`.
inputs : typing.Dict[str, TemplateRunInput]
Input values keyed by input port id. Every input port of the version being run must be given; a missing or unknown id is rejected. Pass `{}` for a template with no inputs.
version_id : typing.Optional[str]
The template snapshot to run. Pass a specific version id to pin that snapshot, or `latest` (the default when omitted) to run the template's most recently published version. Only published versions can be pinned, except by the template's owner, who may also pin an unpublished saved snapshot to try it out before publishing. The live draft is never run through this API.
webhook : typing.Optional[WebhookTarget]
Include to send the run's result to the workspace's configured flows webhooks once the run's `status` reaches `completed` or `failed`. One event for the whole run: the `flows_template_run` event's `data` matches the terminal response of `GET /v1/flows/templates/{template_id}/runs/{run_id}`.
wait_timeout_in_seconds : typing.Optional[float]
Seconds to wait in total before raising `FlowsWaitTimeoutError`, which carries the run `id` and `template_id`
so you can resume with `get`. Waits indefinitely when omitted or `float("inf")`; must be at least 0
when set. Not to be confused with the client's `timeout` or `timeout_in_seconds` in
`request_options`, which limit each HTTP request.
min_poll_interval_in_seconds : float
The shortest wait between status checks, in seconds, and the wait used when the server suggests none.
Must be at least 0.5.
request_options : typing.Optional[RequestOptions]
Request-specific configuration, applied to the create call and to every status check, except
`additional_body_parameters`, which only the create call gets. `timeout_in_seconds` and
`max_retries` apply to each request on its own; `wait_timeout_in_seconds` bounds the whole wait.
Returns
-------
TemplateRunResponse
The run in its terminal state.
"""
_check_wait_options(wait_timeout_in_seconds, min_poll_interval_in_seconds)
started_at = time.monotonic()
created = await self.with_raw_response.create(
template_id, inputs=inputs, version_id=version_id, webhook=webhook, request_options=request_options
)
run_id = created.data.id
poll_options = _poll_request_options(request_options)
return await _async_wait(
id=run_id,
template_id=template_id,
first_response=created.data,
first_headers=created.headers,
get=lambda: self.with_raw_response.get(template_id, run_id, request_options=poll_options),
started_at=started_at,
wait_timeout_in_seconds=wait_timeout_in_seconds,
min_interval=min_poll_interval_in_seconds,
)
class TemplatesClient(AutogeneratedTemplatesClient):
@property
def runs(self) -> RunsClient:
if self._runs is None:
self._runs = RunsClient(client_wrapper=self._client_wrapper)
return typing.cast(RunsClient, self._runs)
class AsyncTemplatesClient(AutogeneratedAsyncTemplatesClient):
@property
def runs(self) -> AsyncRunsClient:
if self._runs is None:
self._runs = AsyncRunsClient(client_wrapper=self._client_wrapper)
return typing.cast(AsyncRunsClient, self._runs)
class FlowsClient(AutogeneratedFlowsClient):
"""
Extends the autogenerated flows client with `create_and_wait` helpers on
`image`, `video`, `text_to_speech` and `templates.runs`.
"""
@property
def video(self) -> VideoClient:
if self._video is None:
self._video = VideoClient(client_wrapper=self._client_wrapper)
return typing.cast(VideoClient, self._video)
@property
def image(self) -> ImageClient:
if self._image is None:
self._image = ImageClient(client_wrapper=self._client_wrapper)
return typing.cast(ImageClient, self._image)
@property
def text_to_speech(self) -> TextToSpeechClient:
if self._text_to_speech is None:
self._text_to_speech = TextToSpeechClient(client_wrapper=self._client_wrapper)
return typing.cast(TextToSpeechClient, self._text_to_speech)
@property
def templates(self) -> TemplatesClient:
if self._templates is None:
self._templates = TemplatesClient(client_wrapper=self._client_wrapper)
return typing.cast(TemplatesClient, self._templates)
class AsyncFlowsClient(AutogeneratedAsyncFlowsClient):
"""
Extends the autogenerated async flows client with `create_and_wait` helpers on
`image`, `video`, `text_to_speech` and `templates.runs`.
"""
@property
def video(self) -> AsyncVideoClient:
if self._video is None:
self._video = AsyncVideoClient(client_wrapper=self._client_wrapper)
return typing.cast(AsyncVideoClient, self._video)
@property
def image(self) -> AsyncImageClient:
if self._image is None:
self._image = AsyncImageClient(client_wrapper=self._client_wrapper)
return typing.cast(AsyncImageClient, self._image)
@property
def text_to_speech(self) -> AsyncTextToSpeechClient:
if self._text_to_speech is None:
self._text_to_speech = AsyncTextToSpeechClient(client_wrapper=self._client_wrapper)
return typing.cast(AsyncTextToSpeechClient, self._text_to_speech)
@property
def templates(self) -> AsyncTemplatesClient:
if self._templates is None:
self._templates = AsyncTemplatesClient(client_wrapper=self._client_wrapper)
return typing.cast(AsyncTemplatesClient, self._templates)
|