-
Notifications
You must be signed in to change notification settings - Fork 707
Include more request configuration options into the span attributes for the Google GenAI SDK instrumentation #3374
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 45 commits into
open-telemetry:main
from
michaelsafyan:google_genai_attribute_improvements
Apr 23, 2025
Merged
Changes from 28 commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
14ab0b4
Create a utility to simplify recording request attributes.
michaelsafyan cd5a36a
Merge branch 'open-telemetry:main' into google_genai_attribute_improv…
michaelsafyan 2fc0ad1
Update recording mechanism to record more request options.
michaelsafyan 969c003
Merge branch 'open-telemetry:main' into google_genai_attribute_improv…
michaelsafyan 88b7e45
Improve the recording of span request attributes.
michaelsafyan 744ef1c
Reformat with ruff.
michaelsafyan 76c84c3
Update TODOs to reflect change made here.
michaelsafyan 3953ea1
Update changelog now that PR has been created and can be referenced.
michaelsafyan d6f5f36
Merge branch 'open-telemetry:main' into google_genai_attribute_improv…
michaelsafyan 7354e6f
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan d3526fa
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan 80c8df1
Fix lint issues.
michaelsafyan 43987e4
Reformat with ruff.
michaelsafyan 6b8c599
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan aaaa017
Add more documentation comments requested in the pull request.
michaelsafyan 3d911b6
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan 5153080
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan 031369b
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan fa8fa60
Add tests and comments that provide some additional clarity regarding…
michaelsafyan 2a08ecd
Add tests and comments that provide some additional clarity regarding…
michaelsafyan 97dab62
Handle corner case where flatten function returns compound output.
michaelsafyan 3107e56
Update prefix to match currently proposed SemConv.
michaelsafyan cb4ca3b
Update to specify attributes from SemConv constants per PR feedback.
michaelsafyan 0b9c5bb
Use an allowlist for dynamic keys per PR feedback.
michaelsafyan ff73608
Reformat with ruff.
michaelsafyan d0f5444
Fix lint issues.
michaelsafyan ffb898b
Reformat with ruff.
michaelsafyan f583614
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan d6fe6a7
Handle flattening errors more gracefully.
michaelsafyan c4a7d12
Add support for more wildcards in the allowlist.
michaelsafyan f23216f
Add a clearer type for the flatten functions.
michaelsafyan d522ea0
Simplify 'exclude_keys' initialization per PR feedback.
michaelsafyan 0e441b2
Simplify AllowList constructor type annotation per PR feedback.
michaelsafyan 5902b35
Reformat with ruff.
michaelsafyan a609776
Resolve lint error concerning too many returns.
michaelsafyan f92758b
Reformat with ruff.
michaelsafyan 72bc998
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan c8f033a
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan 676c251
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan 3458eab
Merge branch 'main' into google_genai_attribute_improvements
michaelsafyan 49f7bd2
Update name to reflect requested changes in Semantic Conventions pull…
michaelsafyan 58eae49
Add test to verify correct handling of Unicode.
michaelsafyan 755e641
Merge branch 'open-telemetry:main' into google_genai_attribute_improv…
michaelsafyan 79b082e
Reformat with ruff.
michaelsafyan b2a6cd1
Remove deuplicated test.
michaelsafyan 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
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
62 changes: 62 additions & 0 deletions
62
...rumentation-google-genai/src/opentelemetry/instrumentation/google_genai/allowlist_util.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,62 @@ | ||
# 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. | ||
|
||
import os | ||
from typing import Callable, List, Optional, Set, Union | ||
|
||
ALLOWED = True | ||
DENIED = False | ||
|
||
|
||
def _parse_env_list(s: str) -> Set[str]: | ||
result = set() | ||
for entry in s.split(","): | ||
stripped_entry = entry.strip() | ||
if not stripped_entry: | ||
continue | ||
result.add(stripped_entry) | ||
return result | ||
|
||
|
||
class AllowList: | ||
def __init__( | ||
self, | ||
includes: Optional[Union[Set[str], List[str]]] = None, | ||
excludes: Optional[Union[Set[str], List[str]]] = None, | ||
if_none_match: Optional[Callable[str, bool]] = None, | ||
): | ||
self._includes = set(includes or []) | ||
self._excludes = set(excludes or []) | ||
self._include_all = "*" in self._includes | ||
self._exclude_all = "*" in self._excludes | ||
assert (not self._include_all) or ( | ||
not self._exclude_all | ||
), "Can't have '*' in both includes and excludes." | ||
|
||
def allowed(self, x: str): | ||
if self._exclude_all: | ||
return x in self._includes | ||
if self._include_all: | ||
return x not in self._excludes | ||
return (x in self._includes) and (x not in self._excludes) | ||
|
||
@staticmethod | ||
def from_env( | ||
includes_env_var: str, excludes_env_var: Optional[str] = None | ||
): | ||
includes = _parse_env_list(os.getenv(includes_env_var) or "") | ||
excludes = set() | ||
if excludes_env_var: | ||
excludes = _parse_env_list(os.getenv(excludes_env_var) or "") | ||
return AllowList(includes=includes, excludes=excludes) |
18 changes: 18 additions & 0 deletions
18
...rumentation-google-genai/src/opentelemetry/instrumentation/google_genai/custom_semconv.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,18 @@ | ||
# 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. | ||
|
||
|
||
# Prefix to use for LLM model request attributes that are unique GCP | ||
# (or that have not yet been formally defined in the GenAI/LLM SIG). | ||
CUSTOM_LLM_REQUEST_PREFIX = "gcp.gen_ai.request" |
257 changes: 257 additions & 0 deletions
257
...-instrumentation-google-genai/src/opentelemetry/instrumentation/google_genai/dict_util.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,257 @@ | ||
# 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. | ||
|
||
|
||
import json | ||
from typing import Any, Callable, Dict, Optional, Sequence, Set, Tuple, Union | ||
|
||
Primitive = Union[bool, str, int, float] | ||
BoolList = list[bool] | ||
StringList = list[str] | ||
IntList = list[int] | ||
FloatList = list[float] | ||
HomogenousPrimitiveList = Union[BoolList, StringList, IntList, FloatList] | ||
FlattenedValue = Union[Primitive, HomogenousPrimitiveList] | ||
FlattenedDict = Dict[str, FlattenedValue] | ||
|
||
|
||
def _concat_key(prefix: Optional[str], suffix: str): | ||
if not prefix: | ||
return suffix | ||
return f"{prefix}.{suffix}" | ||
|
||
|
||
def _is_primitive(v): | ||
for t in [str, bool, int, float]: | ||
if isinstance(v, t): | ||
return True | ||
return False | ||
|
||
|
||
def _is_homogenous_primitive_list(v): | ||
if not isinstance(v, list): | ||
return False | ||
if len(v) == 0: | ||
return True | ||
if not _is_primitive(v[0]): | ||
return False | ||
first_entry_value_type = type(v[0]) | ||
for entry in v[1:]: | ||
if not isinstance(entry, first_entry_value_type): | ||
return False | ||
return True | ||
|
||
|
||
def _get_flatten_func( | ||
flatten_functions: Dict[str, Callable], key_names: set[str] | ||
): | ||
for key in key_names: | ||
flatten_func = flatten_functions.get(key) | ||
if flatten_func is not None: | ||
return flatten_func | ||
return None | ||
|
||
|
||
def _flatten_with_flatten_func( | ||
key: str, | ||
value: Any, | ||
exclude_keys: Set[str], | ||
rename_keys: Dict[str, str], | ||
flatten_functions: Dict[str, Callable], | ||
key_names: Set[str], | ||
) -> Tuple[bool, Any]: | ||
flatten_func = _get_flatten_func(flatten_functions, key_names) | ||
if flatten_func is None: | ||
return False, value | ||
func_output = flatten_func( | ||
key, | ||
value, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) | ||
if func_output is None: | ||
return True, {} | ||
if _is_primitive(func_output) or _is_homogenous_primitive_list( | ||
func_output | ||
): | ||
return True, {key: func_output} | ||
return False, func_output | ||
|
||
|
||
def _flatten_compound_value( | ||
key: str, | ||
value: Any, | ||
exclude_keys: Set[str], | ||
rename_keys: Dict[str, str], | ||
flatten_functions: Dict[str, Callable], | ||
key_names: Set[str], | ||
_from_json=False, | ||
) -> FlattenedDict: | ||
fully_flattened_with_flatten_func, value = _flatten_with_flatten_func( | ||
key=key, | ||
value=value, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
key_names=key_names, | ||
) | ||
if fully_flattened_with_flatten_func: | ||
return value | ||
if isinstance(value, dict): | ||
return _flatten_dict( | ||
value, | ||
key_prefix=key, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) | ||
if isinstance(value, list): | ||
if _is_homogenous_primitive_list(value): | ||
return {key: value} | ||
return _flatten_list( | ||
value, | ||
key_prefix=key, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) | ||
if hasattr(value, "model_dump"): | ||
return _flatten_dict( | ||
value.model_dump(), | ||
key_prefix=key, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) | ||
if _from_json: | ||
raise ValueError( | ||
f"Cannot flatten value with key {key}; value: {value}" | ||
) | ||
michaelsafyan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
try: | ||
json_string = json.dumps(value) | ||
except TypeError as exc: | ||
raise ValueError( | ||
f"Cannot flatten value with key {key}; value: {value}. Not JSON serializable." | ||
) from exc | ||
json_value = json.loads(json_string) | ||
return _flatten_value( | ||
key, | ||
json_value, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
# Ensure that we don't recurse indefinitely if "json.loads()" somehow returns | ||
# a complex, compound object that does not get handled by the "primitive", "list", | ||
# or "dict" cases. Prevents falling back on the JSON serialization fallback path. | ||
_from_json=True, | ||
) | ||
|
||
|
||
def _flatten_value( | ||
key: str, | ||
value: Any, | ||
exclude_keys: Set[str], | ||
rename_keys: Dict[str, str], | ||
flatten_functions: Dict[str, Callable], | ||
_from_json=False, | ||
) -> FlattenedDict: | ||
if value is None: | ||
return {} | ||
key_names = set([key]) | ||
renamed_key = rename_keys.get(key) | ||
if renamed_key is not None: | ||
key_names.add(renamed_key) | ||
key = renamed_key | ||
if key_names & exclude_keys: | ||
return {} | ||
if _is_primitive(value): | ||
return {key: value} | ||
return _flatten_compound_value( | ||
key=key, | ||
value=value, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
key_names=key_names, | ||
_from_json=_from_json, | ||
) | ||
|
||
|
||
def _flatten_dict( | ||
d: Dict[str, Any], | ||
key_prefix: str, | ||
exclude_keys: Set[str], | ||
rename_keys: Dict[str, str], | ||
flatten_functions: Dict[str, Callable], | ||
) -> FlattenedDict: | ||
result = {} | ||
for key, value in d.items(): | ||
if key in exclude_keys: | ||
continue | ||
full_key = _concat_key(key_prefix, key) | ||
flattened = _flatten_value( | ||
full_key, | ||
value, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) | ||
result.update(flattened) | ||
return result | ||
|
||
|
||
def _flatten_list( | ||
lst: list[Any], | ||
key_prefix: str, | ||
exclude_keys: Set[str], | ||
rename_keys: Dict[str, str], | ||
flatten_functions: Dict[str, Callable], | ||
) -> FlattenedDict: | ||
result = {} | ||
result[_concat_key(key_prefix, "length")] = len(lst) | ||
for index, value in enumerate(lst): | ||
full_key = f"{key_prefix}[{index}]" | ||
michaelsafyan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
flattened = _flatten_value( | ||
full_key, | ||
value, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) | ||
result.update(flattened) | ||
return result | ||
|
||
|
||
def flatten_dict( | ||
d: Dict[str, Any], | ||
key_prefix: Optional[str] = None, | ||
exclude_keys: Optional[Sequence[str]] = None, | ||
rename_keys: Optional[Dict[str, str]] = None, | ||
flatten_functions: Optional[Dict[str, Callable]] = None, | ||
michaelsafyan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
): | ||
key_prefix = key_prefix or "" | ||
if exclude_keys is None: | ||
exclude_keys = set() | ||
elif isinstance(exclude_keys, list): | ||
exclude_keys = set(exclude_keys) | ||
michaelsafyan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
rename_keys = rename_keys or {} | ||
flatten_functions = flatten_functions or {} | ||
return _flatten_dict( | ||
d, | ||
key_prefix=key_prefix, | ||
exclude_keys=exclude_keys, | ||
rename_keys=rename_keys, | ||
flatten_functions=flatten_functions, | ||
) |
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.