-
Notifications
You must be signed in to change notification settings - Fork 260
fix(openai): preserve native v1 stream contract #1627
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
b818885
2dcc02b
514171b
b5a7071
95c933d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -830,6 +830,178 @@ | |
| ) | ||
|
|
||
|
|
||
| _openai_stream_iter_hook_installed = False | ||
|
|
||
|
|
||
| def _install_openai_stream_iteration_hooks() -> None: | ||
| global _openai_stream_iter_hook_installed | ||
|
|
||
| if not _is_openai_v1(): | ||
| return | ||
|
|
||
| if not _openai_stream_iter_hook_installed: | ||
| original_iter = openai.Stream.__iter__ | ||
|
|
||
| def traced_iter(self: Any) -> Any: | ||
| try: | ||
| yield from original_iter(self) | ||
| finally: | ||
| finalize_once = getattr(self, "_langfuse_finalize_once", None) | ||
| if finalize_once is not None: | ||
| finalize_once() | ||
|
|
||
| setattr(openai.Stream, "__iter__", traced_iter) | ||
| _openai_stream_iter_hook_installed = True | ||
|
|
||
|
|
||
| def _finalize_stream_response( | ||
| *, | ||
| resource: OpenAiDefinition, | ||
| items: list[Any], | ||
| generation: LangfuseGeneration, | ||
| completion_start_time: Optional[datetime], | ||
| ) -> None: | ||
| try: | ||
| model, completion, usage, metadata = ( | ||
| _extract_streamed_response_api_response(items) | ||
| if resource.object == "Responses" or resource.object == "AsyncResponses" | ||
| else _extract_streamed_openai_response(resource, items) | ||
| ) | ||
|
|
||
| _create_langfuse_update( | ||
| completion, | ||
| generation, | ||
| completion_start_time, | ||
| model=model, | ||
| usage=usage, | ||
| metadata=metadata, | ||
| ) | ||
| except Exception: | ||
| pass | ||
| finally: | ||
| generation.end() | ||
|
|
||
|
|
||
| def _instrument_openai_stream( | ||
| *, | ||
| resource: OpenAiDefinition, | ||
| response: Any, | ||
| generation: LangfuseGeneration, | ||
| ) -> Any: | ||
| if not hasattr(response, "_iterator"): | ||
| return LangfuseResponseGeneratorSync( | ||
| resource=resource, | ||
| response=response, | ||
| generation=generation, | ||
| ) | ||
|
|
||
| items: list[Any] = [] | ||
| raw_iterator = response._iterator | ||
| completion_start_time: Optional[datetime] = None | ||
| is_finalized = False | ||
| close = response.close | ||
|
|
||
| def finalize_once() -> None: | ||
| nonlocal is_finalized | ||
| if is_finalized: | ||
| return | ||
|
|
||
| is_finalized = True | ||
| _finalize_stream_response( | ||
| resource=resource, | ||
| items=items, | ||
| generation=generation, | ||
| completion_start_time=completion_start_time, | ||
| ) | ||
|
|
||
| response._langfuse_finalize_once = finalize_once # type: ignore[attr-defined] | ||
|
|
||
| def traced_iterator() -> Any: | ||
| nonlocal completion_start_time | ||
| try: | ||
| for item in raw_iterator: | ||
| items.append(item) | ||
|
|
||
| if completion_start_time is None: | ||
| completion_start_time = _get_timestamp() | ||
|
|
||
| yield item | ||
| finally: | ||
| finalize_once() | ||
|
|
||
| def traced_close() -> Any: | ||
| try: | ||
| return close() | ||
| finally: | ||
| finalize_once() | ||
|
|
||
| response._iterator = traced_iterator() | ||
| response.close = traced_close | ||
|
claude[bot] marked this conversation as resolved.
|
||
|
|
||
| return response | ||
|
|
||
|
|
||
| def _instrument_openai_async_stream( | ||
| *, | ||
| resource: OpenAiDefinition, | ||
| response: Any, | ||
| generation: LangfuseGeneration, | ||
| ) -> Any: | ||
| if not hasattr(response, "_iterator"): | ||
| return LangfuseResponseGeneratorAsync( | ||
| resource=resource, | ||
| response=response, | ||
| generation=generation, | ||
| ) | ||
|
|
||
| items: list[Any] = [] | ||
| raw_iterator = response._iterator | ||
| completion_start_time: Optional[datetime] = None | ||
| is_finalized = False | ||
| close = response.close | ||
|
|
||
| async def finalize_once() -> None: | ||
| nonlocal is_finalized | ||
| if is_finalized: | ||
| return | ||
|
|
||
| is_finalized = True | ||
| _finalize_stream_response( | ||
| resource=resource, | ||
| items=items, | ||
| generation=generation, | ||
| completion_start_time=completion_start_time, | ||
| ) | ||
|
|
||
| async def traced_iterator() -> Any: | ||
| nonlocal completion_start_time | ||
| try: | ||
| async for item in raw_iterator: | ||
| items.append(item) | ||
|
|
||
| if completion_start_time is None: | ||
| completion_start_time = _get_timestamp() | ||
|
|
||
| yield item | ||
| finally: | ||
| await finalize_once() | ||
|
|
||
| async def traced_close() -> Any: | ||
| try: | ||
| return await close() | ||
| finally: | ||
| await finalize_once() | ||
|
|
||
| async def traced_aclose() -> Any: | ||
| return await traced_close() | ||
|
|
||
| response._iterator = traced_iterator() | ||
| response.close = traced_close | ||
| response.aclose = traced_aclose | ||
|
Comment on lines
+998
to
+1000
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In Useful? React with 👍 / 👎. |
||
|
|
||
| return response | ||
|
|
||
|
|
||
| @_langfuse_wrapper | ||
| def _wrap( | ||
| open_ai_resource: OpenAiDefinition, wrapped: Any, args: Any, kwargs: Any | ||
|
|
@@ -863,7 +1035,13 @@ | |
| try: | ||
| openai_response = wrapped(**arg_extractor.get_openai_args()) | ||
|
|
||
| if _is_streaming_response(openai_response): | ||
| if _is_openai_v1() and isinstance(openai_response, openai.Stream): | ||
| return _instrument_openai_stream( | ||
| resource=open_ai_resource, | ||
| response=openai_response, | ||
| generation=generation, | ||
| ) | ||
| elif _is_streaming_response(openai_response): | ||
| return LangfuseResponseGeneratorSync( | ||
| resource=open_ai_resource, | ||
| response=openai_response, | ||
|
|
@@ -934,7 +1112,13 @@ | |
| try: | ||
| openai_response = await wrapped(**arg_extractor.get_openai_args()) | ||
|
|
||
| if _is_streaming_response(openai_response): | ||
| if _is_openai_v1() and isinstance(openai_response, openai.AsyncStream): | ||
| return _instrument_openai_async_stream( | ||
| resource=open_ai_resource, | ||
| response=openai_response, | ||
| generation=generation, | ||
| ) | ||
| elif _is_streaming_response(openai_response): | ||
| return LangfuseResponseGeneratorAsync( | ||
| resource=open_ai_resource, | ||
| response=openai_response, | ||
|
|
@@ -994,6 +1178,7 @@ | |
|
|
||
|
|
||
| register_tracing() | ||
| _install_openai_stream_iteration_hooks() | ||
|
|
||
|
|
||
| class LangfuseResponseGeneratorSync: | ||
|
|
@@ -1010,6 +1195,7 @@ | |
| self.response = response | ||
| self.generation = generation | ||
| self.completion_start_time: Optional[datetime] = None | ||
| self._is_finalized = False | ||
|
|
||
| def __iter__(self) -> Any: | ||
| try: | ||
|
|
@@ -1045,26 +1231,16 @@ | |
| pass | ||
|
|
||
| def _finalize(self) -> None: | ||
| try: | ||
| model, completion, usage, metadata = ( | ||
| _extract_streamed_response_api_response(self.items) | ||
| if self.resource.object == "Responses" | ||
| or self.resource.object == "AsyncResponses" | ||
| else _extract_streamed_openai_response(self.resource, self.items) | ||
| ) | ||
|
|
||
| _create_langfuse_update( | ||
| completion, | ||
| self.generation, | ||
| self.completion_start_time, | ||
| model=model, | ||
| usage=usage, | ||
| metadata=metadata, | ||
| ) | ||
| except Exception: | ||
| pass | ||
| finally: | ||
| self.generation.end() | ||
| if self._is_finalized: | ||
| return | ||
|
|
||
| self._is_finalized = True | ||
| _finalize_stream_response( | ||
| resource=self.resource, | ||
| items=self.items, | ||
| generation=self.generation, | ||
| completion_start_time=self.completion_start_time, | ||
| ) | ||
|
|
||
|
|
||
| class LangfuseResponseGeneratorAsync: | ||
|
claude[bot] marked this conversation as resolved.
|
||
|
|
@@ -1081,6 +1257,7 @@ | |
| self.response = response | ||
| self.generation = generation | ||
| self.completion_start_time: Optional[datetime] = None | ||
| self._is_finalized = False | ||
|
|
||
| async def __aiter__(self) -> Any: | ||
| try: | ||
|
|
@@ -1113,32 +1290,22 @@ | |
| return self.__aiter__() | ||
|
|
||
| async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: | ||
| pass | ||
|
|
||
| async def _finalize(self) -> None: | ||
| try: | ||
| model, completion, usage, metadata = ( | ||
| _extract_streamed_response_api_response(self.items) | ||
| if self.resource.object == "Responses" | ||
| or self.resource.object == "AsyncResponses" | ||
| else _extract_streamed_openai_response(self.resource, self.items) | ||
| ) | ||
|
|
||
| _create_langfuse_update( | ||
| completion, | ||
| self.generation, | ||
| self.completion_start_time, | ||
| model=model, | ||
| usage=usage, | ||
| metadata=metadata, | ||
| ) | ||
| except Exception: | ||
| pass | ||
| finally: | ||
| self.generation.end() | ||
| if self._is_finalized: | ||
| return | ||
|
|
||
| self._is_finalized = True | ||
| _finalize_stream_response( | ||
| resource=self.resource, | ||
| items=self.items, | ||
| generation=self.generation, | ||
| completion_start_time=self.completion_start_time, | ||
| ) | ||
|
|
||
| async def close(self) -> None: | ||
| """Close the response and release the connection. | ||
|
Check notice on line 1308 in langfuse/openai.py
|
||
|
Comment on lines
1293
to
1308
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 The fallback async wrapper's Extended reasoning...What the bug is and how it manifests
The specific code path that triggers it The only paths in Why existing code does not prevent it The PR added an What the impact would be Any code using the fallback path (non-OpenAI async generators fed through the instrumented API) that calls How to fix it Add Step-by-step proof
|
||
|
|
||
| Automatically called if the response body is read to completion. | ||
| """ | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 The sync early-break fix (commit 2dcc02b) has no async equivalent:
_install_openai_stream_iteration_hooksonly patchesopenai.Stream.__iter__and never installs a hook onopenai.AsyncStream.__aiter__, and_instrument_openai_async_streamnever setsresponse._langfuse_finalize_once. When a user doesasync for chunk in stream: break, Python closes the outer__aiter__generator but does not propagateaclose()toself._iterator(an attribute reference, not a frame-local), sotraced_iterator()'sfinallyblock never fires andgeneration.end()is never called. Fix by installing an analogous async hook onopenai.AsyncStream.__aiter__and storingfinalize_onceasresponse._langfuse_finalize_oncein_instrument_openai_async_stream.Extended reasoning...
What the bug is and how it manifests
The PR fixes sync stream early-break finalization via two coordinated changes: (1)
_install_openai_stream_iteration_hookspatchesopenai.Stream.__iter__with atraced_iterthat wraps the original withyield from original_iter(self)and callsself._langfuse_finalize_once()in afinallyblock, and (2)_instrument_openai_streamstoresresponse._langfuse_finalize_once = finalize_onceso the hook can reach the per-instance callback. Neither of these two steps was applied to the async path._install_openai_stream_iteration_hooksnever patchesopenai.AsyncStream.__aiter__, and_instrument_openai_async_streamnever setsresponse._langfuse_finalize_once.The specific code path that triggers it
openai.AsyncStream.__aiter__(confirmed from OpenAI SDK_streaming.py) is an async generator:async for item in self._iterator: yield item. When a user doesasync for chunk in stream: break, Python creates an outer async generator G from__aiter__. G iteratesself._iterator— which istraced_iterator()(call it TI) installed by_instrument_openai_async_stream. After yielding the first chunk,breakcauses Python to callawait G.aclose(), throwingGeneratorExitinto G at theyield itempoint.Why existing code does not prevent it
G terminates on
GeneratorExit, butself._iterator(TI) is stored on the response object as an attribute — it is not a local variable in G's frame. Python only automatically propagatesaclose()to generators stored as frame-local variables (viayield from/async foron a local). Here, TI's refcount does not drop to zero synchronously, soTI.aclose()is never called. TI'sfinally: await finalize_once()never executes.traced_aclose/traced_closeare only invoked by explicitstream.aclose()/stream.close()calls — they are not triggered by earlybreak.What the impact would be
generation.end()is never called immediately. The Langfuse generation leaks until either the user explicitly callsawait stream.aclose()or the stream object is garbage-collected (non-deterministic). Users who read only the first N chunks from an async stream without remembering to callaclose()will silently lose Langfuse traces. This is an observability correctness regression: the previousLangfuseResponseGeneratorAsync.__aiter__had atry/finallydirectly in the generator the caller iterates, guaranteeing deterministic finalization on any exit path includingbreak.How to fix it
Two symmetric changes are needed: (1) in
_install_openai_stream_iteration_hooks, after patchingopenai.Stream.__iter__, also install an analogous async hook onopenai.AsyncStream.__aiter__:(2) in
_instrument_openai_async_stream, addresponse._langfuse_finalize_once = finalize_onceimmediately after definingfinalize_once, mirroring the sync path (line 917 in the new code). A corresponding testtest_openai_async_stream_break_still_finalizes_generationshould also be added.Step-by-step proof
await openai.chat.completions.create(..., stream=True)→ returns nativeopenai.AsyncStream swiths._iterator = traced_iterator()(TI).async for chunk in s: breaks.__aiter__()→ outer async generator G. G executesasync for item in self._iterator: yield item, readings._iterator = TI.breakcauses Python to callawait G.aclose().GeneratorExitis thrown into G at theyield itempoint. G has notry/finally, so it terminates immediately.s._iteratorstill holds a strong reference.TI.aclose()is NOT called. TI'sfinallydoes NOT run.finalize_once()is never called;generation.end()is never called.sis GC-collected (at which points._iteratoris released and TI eventually finalized — non-deterministic).test_openai_stream_break_still_finalizes_generationfor the sync case but no equivalent async test, confirming the async path was overlooked.