Repository navigation
fix(ai): keep the openai.Stream API on sync OpenAI streams - #1062
Open
mosafariuk wants to merge 1 commit into
Open
mosafariuk wants to merge 1 commit into
mosafariuk wants to merge 1 commit into
Conversation
Sync chat completions and Responses streams returned a bare generator, so `with`, `close()` and attributes such as `.response` were lost. Wrap them with _StreamWrapper, as PostHog#804 did for Anthropic and PostHog#645 did for async.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
💡 Motivation and Context
With
stream=True, the syncposthog.ai.openai.OpenAIwrapper returns a bare generator fromchat.completions.createandresponses.create, not something that behaves likeopenai.Stream. So the wrapper is no longer a drop-in replacement for streaming:with client.chat.completions.create(..., stream=True) as stream:raisesAttributeError: __enter__(LangChain'sChatOpenAIstreams this way)stream.response(HTTP status and headers) is gonestream.close()only closes the generator. The HTTP connection stays open until it's garbage-collectedThis was already fixed for async streams in #645 (
AsyncStreamWrapper) and for sync Anthropic in #804 (_StreamWrapper). Sync OpenAI chat completions and Responses were the remaining paths still returninggenerator(). This PR wraps them with the same_StreamWrapper, sowith,close()and attributes such as.responsereach the provider stream, and the PostHog event is still captured once.It also makes
_StreamWrapper.close()skip a provider stream that has noclose(), the same checkAsyncStreamWrapperalready does.openai.Streamalways has one, but without the check the existingtest_sync_stream_close_after_early_exit_captures_partial_statetest, which mocks the stream asiter([...]), would fail. With the check it passes unchanged.Sync Gemini is unchanged on purpose:
google-genai's owngenerate_content_stream()returns a plain generator, so returning a generator there already matches the provider API.💚 How did you test it?
posthog/test/ai/openai/test_openai.py, modelled on the fix(ai): supportasync withon async streaming responses (Fixes #393) #645 async tests, using a new syncRecordingStreamhelper next toRecordingAsyncStream:with, expose.response, close the provider stream on exit, and capture exactly one$ai_generationeventwithcloses the provider stream and still captures the eventclose()mid-stream outside awithblock closes the provider stream and still captures the eventmainand pass with this changeruff format --check,ruff check,mypy | mypy-baseline filterandmake public_api_checkare clean (no public API change, since_StreamWrapperis internal).openai.Stream: a script points the real OpenAI client at anhttpx.MockTransportthat serves SSE chunks. I compared plainopenai.OpenAIwith the PostHog wrapper and checked thatwithand.responsework, the HTTP responseis_closedafter a fullwithiteration and after an earlyclose(), and one event is captured in each case. I ran it onopenai2.54 (the repo's lockfile) and reproduced the original failure on 3.31.📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
close()check instead of changing the existing parity test, so current behaviour stays as it is.