-
Notifications
You must be signed in to change notification settings - Fork 36
util-genai | Add RetrievalInvocation and lifecycle API #36
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
lmolkova
merged 12 commits into
open-telemetry:main
from
keith-decker:add-retrieval-invocation
Jun 1, 2026
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
35c949c
retrieval invocation
keith-decker 12d733c
copilot feedback
keith-decker 06689a9
addressing copilot feedback
keith-decker 2029e37
lint update
keith-decker a810ae2
towncrier fix
keith-decker 39c8e7f
clean up old changelog and docstring
keith-decker db685d0
use float for top_k per semconvs https://github.com/open-telemetry/se…
keith-decker 789c36c
Merge branch 'main' into add-retrieval-invocation
lmolkova bf52d3b
migrate away from using Any on attributes
keith-decker 3cdcf95
Merge branch 'main' into add-retrieval-invocation
keith-decker e407487
Merge branch 'main' into add-retrieval-invocation
keith-decker 85fd86f
Merge branch 'main' into add-retrieval-invocation
keith-decker 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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add `RetrievalInvocation` type with `start_retrieval` / `retrieval` span lifecycle, supporting `gen_ai.operation.name=retrieval` spans per the GenAI semantic conventions. |
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
142 changes: 142 additions & 0 deletions
142
util/opentelemetry-util-genai/src/opentelemetry/util/genai/_retrieval_invocation.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,142 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Mapping, Sequence | ||
| from typing import Any, cast | ||
|
|
||
| from opentelemetry._logs import Logger | ||
| from opentelemetry.semconv._incubating.attributes import ( | ||
| gen_ai_attributes as GenAI, | ||
| ) | ||
| from opentelemetry.semconv.attributes import server_attributes | ||
| from opentelemetry.trace import SpanKind, Tracer | ||
| from opentelemetry.util.genai._invocation import Error, GenAIInvocation | ||
| from opentelemetry.util.genai.completion_hook import CompletionHook | ||
| from opentelemetry.util.genai.metrics import InvocationMetricsRecorder | ||
| from opentelemetry.util.genai.utils import ( | ||
| ContentCapturingMode, | ||
| gen_ai_json_dumps, | ||
| get_content_capturing_mode, | ||
| is_experimental_mode, | ||
| ) | ||
| from opentelemetry.util.types import AttributeValue | ||
|
|
||
|
|
||
| class RetrievalInvocation(GenAIInvocation): | ||
| """Represents a single retrieval invocation (retrieval span). | ||
|
|
||
| Use handler.retrieval() rather than constructing this directly. | ||
|
|
||
| Reference: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-spans.md#retrievals | ||
|
|
||
| Semantic convention attributes for retrieval spans: | ||
| - gen_ai.operation.name: "retrieval" (Required) | ||
| - error.type: Error type if operation failed (Conditionally Required) | ||
| - gen_ai.data_source.id: Data source identifier (Conditionally Required, when applicable) | ||
| - gen_ai.provider.name: Provider name (Conditionally Required, when applicable) | ||
| - gen_ai.request.model: Model name if applicable (Conditionally Required, if available) | ||
| - server.port: Server port (Conditionally Required, if server.address is set) | ||
| - gen_ai.request.top_k: Top-k sampling setting (Recommended) | ||
| - server.address: Server address (Recommended) | ||
| - gen_ai.retrieval.documents: Retrieved documents (Opt-In, may contain sensitive data) | ||
| - gen_ai.retrieval.query.text: Query text (Opt-In, may contain sensitive data) | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| tracer: Tracer, | ||
| metrics_recorder: InvocationMetricsRecorder, | ||
| logger: Logger, | ||
| completion_hook: CompletionHook, | ||
| *, | ||
| data_source_id: str | None = None, | ||
| provider: str | None = None, | ||
| request_model: str | None = None, | ||
| server_address: str | None = None, | ||
| server_port: int | None = None, | ||
| ) -> None: | ||
| """Use handler.retrieval() instead of calling this directly.""" | ||
| _operation_name = GenAI.GenAiOperationNameValues.RETRIEVAL.value | ||
| super().__init__( | ||
| tracer, | ||
| metrics_recorder, | ||
| logger, | ||
| completion_hook, | ||
| operation_name=_operation_name, | ||
| span_name=f"{_operation_name} {data_source_id}" | ||
| if data_source_id | ||
| else _operation_name, | ||
| span_kind=SpanKind.CLIENT, | ||
| ) | ||
| self.data_source_id = data_source_id | ||
| self.provider = provider | ||
| self.request_model = request_model | ||
| self.server_address = server_address | ||
| self.server_port = server_port | ||
| self.top_k: float | None = None | ||
| self.query_text: str | None = None | ||
| self.documents: Sequence[Mapping[str, Any]] | None = None | ||
| self._start(self._get_base_attributes()) | ||
|
|
||
| def _get_base_attributes(self) -> dict[str, AttributeValue]: | ||
| """Return sampling-relevant attributes available at span creation time.""" | ||
| optional_attrs: tuple[tuple[str, AttributeValue | None], ...] = ( | ||
| (GenAI.GEN_AI_DATA_SOURCE_ID, self.data_source_id), | ||
| (GenAI.GEN_AI_PROVIDER_NAME, self.provider), | ||
| (GenAI.GEN_AI_REQUEST_MODEL, self.request_model), | ||
| (server_attributes.SERVER_ADDRESS, self.server_address), | ||
| (server_attributes.SERVER_PORT, self.server_port), | ||
| ) | ||
| return { | ||
| GenAI.GEN_AI_OPERATION_NAME: self._operation_name, | ||
| **{k: v for k, v in optional_attrs if v is not None}, | ||
| } | ||
|
|
||
| def _get_metric_attributes(self) -> dict[str, AttributeValue]: | ||
| # data_source_id intentionally excluded — high cardinality | ||
| optional_attrs: tuple[tuple[str, AttributeValue | None], ...] = ( | ||
| (GenAI.GEN_AI_PROVIDER_NAME, self.provider), | ||
| (GenAI.GEN_AI_REQUEST_MODEL, self.request_model), | ||
| (server_attributes.SERVER_ADDRESS, self.server_address), | ||
| (server_attributes.SERVER_PORT, self.server_port), | ||
| ) | ||
| attrs: dict[str, AttributeValue] = { | ||
| GenAI.GEN_AI_OPERATION_NAME: self._operation_name, | ||
| **{k: v for k, v in optional_attrs if v is not None}, | ||
| } | ||
| # TODO: remove cast once base class metric_attributes is typed as dict[str, AttributeValue] | ||
| attrs.update(cast(dict[str, AttributeValue], self.metric_attributes)) | ||
| return attrs | ||
|
|
||
| def _get_content_attributes_for_span(self) -> dict[str, AttributeValue]: | ||
| if not self.span.is_recording(): | ||
| return {} | ||
| if not is_experimental_mode() or get_content_capturing_mode() not in ( | ||
| ContentCapturingMode.SPAN_ONLY, | ||
| ContentCapturingMode.SPAN_AND_EVENT, | ||
| ): | ||
| return {} | ||
| optional_attrs: tuple[tuple[str, AttributeValue | None], ...] = ( | ||
| (GenAI.GEN_AI_RETRIEVAL_QUERY_TEXT, self.query_text), | ||
| ( | ||
| GenAI.GEN_AI_RETRIEVAL_DOCUMENTS, | ||
| gen_ai_json_dumps(self.documents) | ||
| if self.documents is not None | ||
| else None, | ||
| ), | ||
| ) | ||
| return {k: v for k, v in optional_attrs if v is not None} | ||
|
|
||
| def _apply_finish(self, error: Error | None = None) -> None: | ||
| if error is not None: | ||
| self._apply_error_attributes(error) | ||
| attributes: dict[str, AttributeValue] = {} | ||
| if self.top_k is not None: | ||
| attributes[GenAI.GEN_AI_REQUEST_TOP_K] = self.top_k | ||
| attributes.update(self._get_content_attributes_for_span()) | ||
| # TODO: remove cast once base class self.attributes is typed as dict[str, AttributeValue] | ||
| attributes.update(cast(dict[str, AttributeValue], self.attributes)) | ||
| self.span.set_attributes(attributes) | ||
|
Member
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. from call: why isn't type checker complaining here about set_attributes not being |
||
| self._metrics_recorder.record(self) | ||
|
keith-decker 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
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
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.