-
Notifications
You must be signed in to change notification settings - Fork 957
genai-util: refactor streams to a generic ABC wrapper. #4500
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
Merged
aabmass
merged 40 commits into
open-telemetry:main
from
eternalcuriouslearner:feat/move-stream-to-genai-util-as-abc
May 12, 2026
Merged
Changes from 10 commits
Commits
Show all changes
40 commits
Select commit
Hold shift + click to select a range
cb0156f
wip: move the streams to a generic ABC wrapper.
eternalcuriouslearner 11258d9
polish: add changelogs.
eternalcuriouslearner 6f4e510
wip: precommit.
eternalcuriouslearner 787ecbb
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 8a273c5
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 07b4a66
wip: fix the merge issues.
eternalcuriouslearner c496ecf
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
lzchen 250a7bf
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 04e067c
polish: pr feedback.
eternalcuriouslearner 2157d28
polish: fixing the precommit.
eternalcuriouslearner fc3bd4d
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 8a8b9c7
wip: renamed to stream.py and changed finish_reasons population style.
eternalcuriouslearner ae2663b
wip: implementing copilot suggestions.
eternalcuriouslearner a246ee1
wip: fixing the tox.
eternalcuriouslearner 26743fb
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 5689654
polish: copilot feedback.
eternalcuriouslearner c43b094
polish: copilot suggestions.
eternalcuriouslearner c06a7e7
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 57e2957
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 1cf0924
Update CLAUDE.md
eternalcuriouslearner 46540b3
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
lmolkova 3b31fc1
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
lzchen d60659a
wip: shifting the instructions to right agents.md file.
eternalcuriouslearner c4c3e0c
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner 7ce1427
wip: using objectproxy.
eternalcuriouslearner a133e8d
Merge branch 'feat/move-stream-to-genai-util-as-abc' of https://githu…
eternalcuriouslearner 17cd07c
fixing pypy errors.
eternalcuriouslearner a3faa51
wip: renaming functions based on events.
eternalcuriouslearner 8fb9c83
polish: making chat_buffers and chat_wrappers type safe.
eternalcuriouslearner 4759d81
polish: removed get_attr guard.
eternalcuriouslearner bca90da
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner d7b2bdd
polish: add types to chat_wrappers.py.
eternalcuriouslearner 53650d5
Merge branch 'feat/move-stream-to-genai-util-as-abc' of https://githu…
eternalcuriouslearner b7cb6db
wip: use get_attr for new fields to avoid failures.
eternalcuriouslearner 9782774
polish: fix lint and spdx headers.
eternalcuriouslearner ae0e6d2
polish:fixing pre-commit
eternalcuriouslearner b259a1e
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
aabmass 7f1d7bd
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
eternalcuriouslearner d8cb7cc
update oldest deps
lmolkova 6916805
Merge branch 'main' into feat/move-stream-to-genai-util-as-abc
lmolkova File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,8 @@ | ||
| @AGENTS.md | ||
|
|
||
| For GenAI streaming wrappers, use `SyncStreamWrapper` and | ||
| `AsyncStreamWrapper` from `opentelemetry.util.genai._stream` instead of | ||
| reimplementing iteration, close/context-manager, and finalization behavior in | ||
| provider packages. Keep provider-specific chunk parsing and telemetry | ||
| finalization in private hooks or a narrow mixin, and do not make async stream | ||
| wrappers inherit from sync stream wrappers. |
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
52 changes: 52 additions & 0 deletions
52
...try-instrumentation-openai-v2/src/opentelemetry/instrumentation/openai_v2/chat_buffers.py
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
|
|
||
| class ToolCallBuffer: | ||
| def __init__(self, index, tool_call_id, function_name): | ||
|
eternalcuriouslearner marked this conversation as resolved.
Outdated
|
||
| self.index = index | ||
| self.function_name = function_name | ||
| self.tool_call_id = tool_call_id | ||
| self.arguments = [] | ||
|
|
||
| def append_arguments(self, arguments): | ||
| if arguments is not None: | ||
|
aabmass marked this conversation as resolved.
|
||
| self.arguments.append(arguments) | ||
|
|
||
|
|
||
| class ChoiceBuffer: | ||
| def __init__(self, index): | ||
| self.index = index | ||
| self.finish_reason = None | ||
| self.text_content = [] | ||
| self.tool_calls_buffers = [] | ||
|
|
||
| def append_text_content(self, content): | ||
| self.text_content.append(content) | ||
|
|
||
| def append_tool_call(self, tool_call): | ||
| idx = tool_call.index | ||
| for _ in range(len(self.tool_calls_buffers), idx + 1): | ||
| self.tool_calls_buffers.append(None) | ||
|
|
||
| function = tool_call.function | ||
| if not self.tool_calls_buffers[idx]: | ||
| self.tool_calls_buffers[idx] = ToolCallBuffer( | ||
| idx, | ||
| tool_call.id, | ||
| function.name if function else None, | ||
| ) | ||
|
|
||
| if function: | ||
| self.tool_calls_buffers[idx].append_arguments(function.arguments) | ||
|
eternalcuriouslearner marked this conversation as resolved.
Outdated
|
||
216 changes: 216 additions & 0 deletions
216
...ry-instrumentation-openai-v2/src/opentelemetry/instrumentation/openai_v2/chat_wrappers.py
|
eternalcuriouslearner marked this conversation as resolved.
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,216 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from typing import Any, Optional | ||
|
|
||
| from openai import AsyncStream, Stream | ||
|
|
||
| from opentelemetry.semconv._incubating.attributes import ( | ||
| openai_attributes as OpenAIAttributes, | ||
| ) | ||
| from opentelemetry.util.genai._stream import ( | ||
| AsyncStreamWrapper, | ||
| SyncStreamWrapper, | ||
| ) | ||
|
eternalcuriouslearner marked this conversation as resolved.
Outdated
|
||
| from opentelemetry.util.genai.invocation import InferenceInvocation | ||
| from opentelemetry.util.genai.types import ( | ||
| OutputMessage, | ||
| Text, | ||
| ToolCallRequest, | ||
| ) | ||
|
|
||
| from .chat_buffers import ChoiceBuffer | ||
|
|
||
|
|
||
| class _ChatStreamMixin: | ||
| """Chat-specific hooks shared by sync and async stream wrappers.""" | ||
|
|
||
| invocation: InferenceInvocation | ||
| capture_content: bool | ||
| choice_buffers: list | ||
| response_id: Optional[str] = None | ||
| response_model: Optional[str] = None | ||
| service_tier: Optional[str] = None | ||
| finish_reasons: list = [] | ||
| prompt_tokens: Optional[int] = None | ||
| completion_tokens: Optional[int] = None | ||
|
eternalcuriouslearner marked this conversation as resolved.
Outdated
|
||
|
|
||
| def _set_response_model(self, chunk): | ||
| if self.response_model: | ||
| return | ||
|
|
||
| if getattr(chunk, "model", None): | ||
| self.response_model = chunk.model | ||
|
aabmass marked this conversation as resolved.
Outdated
|
||
|
|
||
| def _set_response_id(self, chunk): | ||
| if self.response_id: | ||
| return | ||
|
|
||
| if getattr(chunk, "id", None): | ||
| self.response_id = chunk.id | ||
|
|
||
| def _set_response_service_tier(self, chunk): | ||
| if self.service_tier: | ||
| return | ||
|
|
||
| if getattr(chunk, "service_tier", None): | ||
| self.service_tier = chunk.service_tier | ||
|
|
||
| def _build_streaming_response(self, chunk): | ||
| if getattr(chunk, "choices", None) is None: | ||
| return | ||
|
|
||
| choices = chunk.choices | ||
| for choice in choices: | ||
| if not choice.delta: | ||
| continue | ||
|
|
||
| for idx in range(len(self.choice_buffers), choice.index + 1): | ||
| self.choice_buffers.append(ChoiceBuffer(idx)) | ||
|
|
||
| if choice.finish_reason: | ||
| self.choice_buffers[ | ||
| choice.index | ||
| ].finish_reason = choice.finish_reason | ||
|
|
||
| if choice.delta.content is not None: | ||
| self.choice_buffers[choice.index].append_text_content( | ||
| choice.delta.content | ||
| ) | ||
|
|
||
| if choice.delta.tool_calls is not None: | ||
| for tool_call in choice.delta.tool_calls: | ||
| self.choice_buffers[choice.index].append_tool_call( | ||
| tool_call | ||
| ) | ||
|
|
||
| def _set_usage(self, chunk): | ||
| if getattr(chunk, "usage", None): | ||
| self.completion_tokens = chunk.usage.completion_tokens | ||
| self.prompt_tokens = chunk.usage.prompt_tokens | ||
|
|
||
| def _process_chunk(self, chunk): | ||
| self._set_response_id(chunk) | ||
| self._set_response_model(chunk) | ||
| self._set_response_service_tier(chunk) | ||
| self._build_streaming_response(chunk) | ||
| self._set_usage(chunk) | ||
|
|
||
| def _set_output_messages(self): | ||
| if not self.capture_content: # optimization | ||
| return | ||
| output_messages = [] | ||
| for choice in self.choice_buffers: | ||
| message = OutputMessage( | ||
| role="assistant", | ||
| finish_reason=choice.finish_reason or "error", | ||
| parts=[], | ||
| ) | ||
| if choice.text_content: | ||
| message.parts.append( | ||
| Text(content="".join(choice.text_content)) | ||
| ) | ||
| if choice.tool_calls_buffers: | ||
| tool_calls = [] | ||
| for tool_call in choice.tool_calls_buffers: | ||
| arguments = None | ||
| arguments_str = "".join(tool_call.arguments) | ||
| if arguments_str: | ||
| try: | ||
| arguments = json.loads(arguments_str) | ||
| except json.JSONDecodeError: | ||
| arguments = arguments_str | ||
|
lmolkova marked this conversation as resolved.
|
||
| tool_call_part = ToolCallRequest( | ||
| name=tool_call.function_name, | ||
| id=tool_call.tool_call_id, | ||
| arguments=arguments, | ||
| ) | ||
| tool_calls.append(tool_call_part) | ||
| message.parts.extend(tool_calls) | ||
| output_messages.append(message) | ||
|
|
||
| self.invocation.output_messages = output_messages | ||
|
|
||
| def _stop_stream(self) -> None: | ||
| self._cleanup() | ||
|
|
||
| def _fail_stream(self, error: BaseException) -> None: | ||
| self._cleanup(error) | ||
|
|
||
| def parse(self): | ||
| """Called when using with_raw_response with stream=True.""" | ||
| return self | ||
|
|
||
| def _cleanup(self, error: Optional[BaseException] = None) -> None: | ||
| self.invocation.response_model_name = self.response_model | ||
| self.invocation.response_id = self.response_id | ||
| self.invocation.input_tokens = self.prompt_tokens | ||
| self.invocation.output_tokens = self.completion_tokens | ||
| # TODO: Derive finish_reasons from choice_buffers so streaming | ||
| # invocations match non-streaming response finalization. | ||
| self.invocation.finish_reasons = self.finish_reasons | ||
| if self.service_tier: | ||
|
eternalcuriouslearner marked this conversation as resolved.
Outdated
|
||
| self.invocation.attributes.update( | ||
| { | ||
| OpenAIAttributes.OPENAI_RESPONSE_SERVICE_TIER: self.service_tier | ||
| }, | ||
| ) | ||
|
|
||
| self._set_output_messages() | ||
|
|
||
| if error: | ||
| self.invocation.fail(error) | ||
| else: | ||
| self.invocation.stop() | ||
|
|
||
|
|
||
| class ChatStreamWrapper( | ||
| _ChatStreamMixin, | ||
| SyncStreamWrapper[Any], | ||
| ): | ||
| def __init__( | ||
| self, | ||
| stream: Stream, | ||
| invocation: InferenceInvocation, | ||
| capture_content: bool, | ||
| ): | ||
| super().__init__(stream) | ||
| self.invocation = invocation | ||
| self.choice_buffers = [] | ||
| self.capture_content = capture_content | ||
|
|
||
|
|
||
| class AsyncChatStreamWrapper( | ||
| _ChatStreamMixin, | ||
| AsyncStreamWrapper[Any], | ||
| ): | ||
| def __init__( | ||
| self, | ||
| stream: AsyncStream, | ||
| invocation: InferenceInvocation, | ||
| capture_content: bool, | ||
| ): | ||
| super().__init__(stream) | ||
| self.invocation = invocation | ||
| self.choice_buffers = [] | ||
| self.capture_content = capture_content | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "AsyncChatStreamWrapper", | ||
| "ChatStreamWrapper", | ||
| ] | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.