Skip to content

[Feature] create_and_wait helpers for Flows generations and template runs - #889

Merged
brandonrule11 merged 11 commits into
mainfrom
brandonrule/flo-350-sdk-create_and_wait-helpers-for-flows-generations-and
Oct 15, 2026
Merged

brandonrule11 merged 11 commits into
mainfrom
brandonrule/flo-350-sdk-create_and_wait-helpers-for-flows-generations-and

Conversation

@brandonrule11

@brandonrule11 brandonrule11 commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

FLO-350: quickstarts should get a Flows result in one call, without a hand-written poll loop or webhook plumbing (like OpenAI's create_and_poll). _should_retry only covers 408/409/429/5xx, so an in-progress 200 returns straight away. JS counterpart: elevenlabs/elevenlabs-js#469.

Warning

Merge after xi#52056 is live, together with elevenlabs-js#469, then cut a release. Without xi#52056's Retry-After, the helper polls at its 3s minimum. xi#52081 and elevenlabs-dx#2806 can't merge until this is in a published release.

Usage

gen = client.flows.image.create_and_wait(request=ImageGenerationRequest_BytedanceSeedream5Lite(prompt="a corgi"))
run = client.flows.templates.runs.create_and_wait("template_id", inputs={}, wait_timeout_in_seconds=600)

Design

  • New src/elevenlabs/flows_custom.py, added to .fernignore. Subclasses of the generated flows, templates, runs, image, video and TTS clients, sync and async. client.py sets self._flows to the wrapper, the same pattern as music/STT/speech engine.
  • Create and every GET go through with_raw_response, so the create response's Retry-After (FLO-349 sets it on creates too) sets the first wait.
  • Delay: max(Retry-After or min, min) × (1 + 0–20%). A missing, unparseable or 0 header falls back to min_poll_interval_in_seconds (default 3s, the server's shortest Retry-After in FLO-349). Retry-After is read as whole seconds or an HTTP date. Transport retries still handle 429s.
  • Bad wait options raise ValueError before the create: min_poll_interval_in_seconds must be finite and at least 0.5; wait_timeout_in_seconds, if set, must be at least 0 (NaN is rejected, float("inf") means no timeout, and 0 times out right after the create). request_options applies to every request except additional_body_parameters, which only the create gets.
  • completed/failed are terminal. Generation helpers return TerminalMediaGenerationResponse (the Completed | Failed union); runs return TemplateRunResponse, which the API doesn't discriminate on status. A failed result is returned, not raised.
  • With wait_timeout_in_seconds, the last sleep is cut short at the deadline and one final GET runs. If the work still isn't finished, it raises FlowsWaitTimeoutError (id, template_id, wait_timeout_in_seconds, last_response). With no timeout set (or float("inf")), it waits indefinitely, like OpenAI. A template-run timeout message names the template and says runs.get needs both template_id and id. The names follow request_options["timeout_in_seconds"] and match JS (waitTimeoutInSeconds, minPollIntervalInSeconds); plain timeout would clash with the client's per-request timeout.
  • The docstrings point production users to webhooks.

Notes

  • FlowsWaitTimeoutError is a plain Exception, not ApiError, because no HTTP status applies. Import it from elevenlabs.flows_custom, since the package __init__ is generated.
  • Where the other wrappers set a pattern, this follows it: *_custom.py + .fernignore, subclass wiring in client.py, Autogenerated* aliases, OMIT, static docstrings duplicated for sync/async (as in music_custom.py), ValueError for bad input.
  • No precedent, chosen deliberately:
    • FlowsWaitTimeoutError is the first hand-written exception (webhooks_custom.py reuses the generated BadRequestError, but a wait timeout has no HTTP status).
    • Retry-After parsing and jitter live in flows_custom.py instead of importing core.http_client's private _parse_retry_after / _add_positive_jitter, which can change on regeneration. (Fern's retry-after-ms branch compares a str to 0 and silently never matches, so dropping it loses nothing.)
    • Tests drive real requests through httpx MockTransport instead of patch.object(Autogenerated..., "create"), because the helper reads response headers.
    • A parity test checks each create_and_wait against the generated create: same parameters, and each parameter's docs copied word for word, so a regeneration can't silently leave the wrapper behind.
    • TerminalMediaGenerationResponse is the only type alias a wrapper exports.
  • I didn't run ruff format on the test file: ruff rewrites it to parenthesized context managers, which aren't valid on Python 3.8 (python = "^3.8").
  • Generation docstrings don't name a webhook event. Only flows_template_run appears in the API definition.

Testing

  • tests/test_flows_create_and_wait.py: covers Retry-After pacing and jitter, the min fallback, failed generations returned rather than raised, timeout errors carrying the id (and template_id for runs, named in the message), the no-poll path when create returns a terminal status, the async image and run paths, the min_poll_interval_in_seconds floor and non-finite/negative wait options, an infinite timeout polling through, additional_body_parameters staying off the GETs, and signature and docstring parity with each generated create, and Retry-After HTTP dates (future sets the delay, past falls back to the min). Uses httpx MockTransport with sleeps patched.
  • pytest tests/test_flows_create_and_wait.py: 26/26 pass. mypy on the new and changed files is clean.
  • Not run against the live API. FLO-349 hasn't shipped, so until it does the helper polls at the minimum interval.

🤖 Generated with Claude Code

client.flows.{image,video,text_to_speech}.create_and_wait and
client.flows.templates.runs.create_and_wait (sync and async) start the
work, then poll the GET endpoint, waiting the server's Retry-After (with
a minimum interval and jitter) between checks, until the status is
completed or failed. An optional timeout raises FlowsWaitTimeoutError
carrying the id so callers can resume with get.

FLO-350

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cursor

cursor Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

PR Summary

Low Risk
Additive SDK wrapper around existing Flows APIs with isolated polling logic and broad unit tests; no changes to auth or core HTTP client behavior.

Overview
Adds create_and_wait on the Flows API so scripts can start image/video/TTS generations or template runs and get a terminal result in one call, without hand-rolling poll loops.

New flows_custom.py (Fern-ignored) subclasses the generated Flows clients and exposes client.flows on sync/async ElevenLabs. Each helper creates the job, then polls status GETs until completed or failed, honoring Retry-After (seconds or HTTP date), a 3s default minimum interval, and 0–20% jitter. Optional wait_timeout_in_seconds raises FlowsWaitTimeoutError with ids to resume via get; failed outcomes are returned, not raised. request_options apply to create and polls except additional_body_parameters on GETs.

Tests cover pacing, timeouts, async paths, validation, and signature/doc parity with generated create methods.

Reviewed by Cursor Bugbot for commit 7f7baee. Bugbot is set up for automated code reviews on this repo. Configure here.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit dd0db64. Configure here.

Comment thread src/elevenlabs/client.py Resolved
Comment thread src/elevenlabs/flows_custom.py Resolved
Comment thread src/elevenlabs/flows_custom.py Resolved
Comment thread src/elevenlabs/flows_custom.py Resolved
Comment thread src/elevenlabs/flows_custom.py Resolved
Comment thread src/elevenlabs/flows_custom.py Resolved
brandonrule11 and others added 6 commits October 13, 2026 21:53
- Narrow generation results to TerminalMediaGenerationResponse
- Reject min_poll_interval below 0.5s to rule out tight poll loops
- Keep additional_body_parameters off the status GETs
- Stop naming the Retry-After header in public docstrings
- Point run params at `create` and test signature parity with it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FLO-349's shortest Retry-After is 3s (image, audio, text), and the web app
and MCP view poll at 3s or slower. A 1s default would poll three times
faster than the server intends whenever the header is missing, which is
every response until FLO-349 ships.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The wrappers now copy the parameter docs (and, for generations, the
summary) from the generated `create` docstring at import time, so the
fuller descriptions of `inputs`, `version_id` and `webhook`, plus the
TTS billing note, carry over and track regenerations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Docstrings assigned at runtime don't show in IDE hovers, and the other
hand-written wrappers (music, speech-to-text) use plain docstrings. The
parameter docs are copied from the generated `create`, and the parity
test now fails if any copied entry no longer matches it verbatim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`_parse_retry_after` and `_add_positive_jitter` are private to the
generated core and can change on regeneration. Keep a small Retry-After
parser (seconds or HTTP date) and the 0-20% jitter in flows_custom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in_seconds

`timeout` clashed with the client's per-request `timeout`. The new names
follow `request_options["timeout_in_seconds"]` and match the JS SDK's
`waitTimeoutInSeconds` / `minPollIntervalInSeconds`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Non-finite polling intervals bypass validation and can cause sleep failures or indefinite waits.

1 open finding
What changed in this PR

Adds synchronous and asynchronous create_and_wait helpers for Flows media generations and template runs.

Changes:

  • Implements polling, Retry-After handling, jitter, and timeout errors.
  • Wires custom Flows clients into the SDK.
  • Adds comprehensive polling and parity tests.
File Description
.fernignore Protects the custom Flows wrapper from regeneration.
src/​elevenlabs/​client.py Exposes custom sync and async Flows clients.
src/​elevenlabs/​flows_custom.py Implements polling helpers and client wrappers.
tests/​test_flows_create_and_wait.py Tests polling, timeout, request, and API parity behavior.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/elevenlabs/flows_custom.py Resolved
brandonrule11 and others added 3 commits October 14, 2026 11:07
NaN slips past the min_poll_interval floor check and an infinite interval
never polls; a NaN wait_timeout_in_seconds silently disables the timeout.
All now raise ValueError before the create request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
wait_timeout_in_seconds must now be finite and >= 0, like waitTimeoutInSeconds
in elevenlabs-js. The template-run timeout message names the template and
says runs.get needs both template_id and id. Also test that an HTTP-date
Retry-After sets the poll delay, and a past date falls back to the minimum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Matches elevenlabs-js 3e8fb956: the timeout only has to be at least 0, so
inf waits indefinitely like None, while NaN and negatives still raise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@brandonrule11
brandonrule11 merged commit 7e97b4c into main Oct 15, 2026
4 checks passed
@brandonrule11
brandonrule11 deleted the brandonrule/flo-350-sdk-create_and_wait-helpers-for-flows-generations-and branch October 15, 2026 09:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants