Skip to content

Stream server-sent events from Python SDK methods that declare them - #62

Closed
JaviChulvi wants to merge 1 commit into
mainfrom
JaviChulvi/sdk-event-stream
Closed

JaviChulvi wants to merge 1 commit into
mainfrom
JaviChulvi/sdk-event-stream

Conversation

@JaviChulvi

@JaviChulvi JaviChulvi commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

An operation can answer with server-sent events, for example a stream=true request whose successful response lists text/event-stream next to application/json. Today the generated Python client buffers the whole body and returns one string such as "data: {...}\n\ndata: {...}\n\n", so a caller sees nothing until the stream ends and then has to parse it.

Operations whose successful responses declare text/event-stream now return a generator of events when the server actually streams. Each event's data is decoded as JSON when it is JSON, and as a string otherwise. When the same operation answers JSON, it behaves exactly as before.

for event in client.inference.detect(file=image, classes=["person"], stream=True):
    print(event)  # each box as it arrives, then the full result
  • Only declared operations change. Every other operation still calls httpx.Client.request(), so custom clients, hooks and retries behave as before. Stream-capable calls use send(..., stream=True) and read the body as before when the response is not an event stream (including 204 and errors).
  • The connection is released when the events are exhausted, on close()/aclose(), even before the first event, and on errors.
  • Parsing follows the event-stream format: UTF-8 with an optional byte order mark, CRLF, CR or LF line endings across chunks, multi-line data, comments and other fields ignored, an unterminated final event dropped.
  • Typing: the method returns Response | collections.abc.Generator[Any, None, None] (AsyncGenerator for the async client), and the docstring says to close the generator to stop early.

Known limit: an operation declaring JSON under one success status and an event stream under another is still rejected as mixed successful media, as it was before this change.

Check Before (main) After
stream=true against a live event-stream API One string after the stream ends 11 events; first at 0.74 s, final result at 0.87 s
Same call, async client One string after the stream ends Events via async for, first at 0.81 s
Same operation without stream Dict Dict (unchanged)
close() after the first event N/A Pooled connection released
401 and 400 with stream=true APIError with status and body Same
Unrelated operation Unchanged Unchanged
New test: second chunk withheld until the client has the first event N/A (would time out) Sync and async pass, with BOM, split CRLF, CR-only lines, comment and bare data

bun run typecheck, lint, knip and all 22 tests pass; Ruff and compileall pass on the generated package. Live checks ran against a Platform preview deployment; the SDK's own test suite passes on the regenerated output.

🛠️ PR Summary

Made with ❤️ by Ultralytics Actions

🌟 Summary

Generated Python SDK methods whose successful OpenAPI responses declare text/event-stream now yield events as they arrive, while retaining the existing response handling for non-stream replies.

📊 Key Changes

  • The Python generator marks event-stream operations and adds generator return types and docstrings for both synchronous and asynchronous clients.
  • The generated clients use streaming requests for those operations, parse event data as JSON when possible and strings otherwise, and close the response when the generator finishes or is closed.
  • Non-event-stream responses from these operations are read and handled through the existing response logic; other operations continue using regular requests.
  • Added a generator test that checks events can be read before the server sends the next chunk, for both sync and async clients.

🎯 Purpose & Impact

  • Callers can process declared server-sent events incrementally instead of waiting for the full response body; JSON replies from the same operation retain their existing behavior.

@UltralyticsAssistant UltralyticsAssistant added the enhancement New feature or request label Nov 26, 2026
@UltralyticsAssistant

Copy link
Copy Markdown
Member

👋 Hello @JaviChulvi, thank you for submitting a ultralytics/openapi 🚀 PR! This automated message confirms your contribution was received, and an Ultralytics engineer will assist with the review. To ensure a seamless integration of your work, please review the following checklist:

  • ✅ Define a Purpose: Clearly explain the purpose of your fix or feature in your PR description, and link to any relevant issues. Ensure your commit messages are clear, concise, and adhere to the project's conventions.
  • ✅ Synchronize with Source: Confirm your PR is synchronized with the ultralytics/openapi main branch. If it's behind, update it by clicking the 'Update branch' button or by running git pull and git merge main locally.
  • ✅ Ensure CI Checks Pass: Verify all Ultralytics Continuous Integration (CI) checks are passing. If any checks fail, please address the issues.
  • ✅ Update Documentation: Update the relevant documentation for any new or modified features.
  • ✅ Add Tests: If applicable, include or update tests to cover your changes, and confirm that all tests are passing.
  • ✅ Sign the CLA: Please ensure you have signed our Contributor License Agreement if this is your first Ultralytics PR; the CLA check will comment with signing instructions if needed.
  • ✅ Minimize Changes: Limit your changes to the minimum necessary for your bug fix or feature addition. "It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is." — Bruce Lee

For more guidance, please refer to our Contributing Guide. Don't hesitate to leave a comment if you have any questions. Thank you for contributing to Ultralytics! 🚀

@UltralyticsAssistant UltralyticsAssistant left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔍 PR Review

Made with ❤️ by Ultralytics Actions

Reviewed the Python generator, event-stream parsing and lifecycle, and OpenAPI media detection. I found no concrete regressions; LGTM.

@UltralyticsAssistant
UltralyticsAssistant dismissed their stale review November 26, 2026 23:30

Superseded by new review

@UltralyticsAssistant UltralyticsAssistant left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔍 PR Review 2

Made with ❤️ by Ultralytics Actions

Since review 1, there were no findings left open. I rechecked the Python streaming request path, event parsing and cleanup, and OpenAPI media detection; I found no new concrete regressions. LGTM.

@JaviChulvi

Copy link
Copy Markdown
Contributor Author

Closing this: we no longer need the streaming parameters. VLM 4B inference merged in ultralytics/portal#5465 through the shared model predict route (POST /api/models/ultralytics-yolo/vlm/vlm-4b/predict), which returns one JSON response and has no streaming option, so no SDK method declares server-sent events anymore.

@JaviChulvi JaviChulvi closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants