Skip to content

Commit 97dab62

Browse files
committed
Handle corner case where flatten function returns compound output.
1 parent 2a08ecd commit 97dab62

File tree

2 files changed

+45
-3
lines changed
  • instrumentation-genai/opentelemetry-instrumentation-google-genai

2 files changed

+45
-3
lines changed

instrumentation-genai/opentelemetry-instrumentation-google-genai/src/opentelemetry/instrumentation/google_genai/dict_util.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,12 @@ def _flatten_compound_value(
8181
rename_keys=rename_keys,
8282
flatten_functions=flatten_functions,
8383
)
84-
if func_output is not None:
84+
if func_output is None:
85+
return {}
86+
elif _is_primitive(func_output) or _is_homogenous_primitive_list(func_output):
8587
return {key: func_output}
88+
else:
89+
value = func_output
8690
if isinstance(value, dict):
8791
return _flatten_dict(
8892
value,

instrumentation-genai/opentelemetry-instrumentation-google-genai/tests/utils/test_dict_util.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919

2020
class PydanticModel(BaseModel):
2121
"""Used to verify handling of pydantic models in the flattener."""
22-
str_value: str
23-
int_value: int
22+
str_value: str = ""
23+
int_value: int = 0
2424

2525

2626
class ModelDumpableNotPydantic:
@@ -275,3 +275,41 @@ def test_flatten_list_of_compound_types():
275275
"list_value[3][0]": "abc",
276276
"list_value[3][1]": 123,
277277
}
278+
279+
280+
def test_handles_simple_output_from_flatten_func():
281+
def f(*args, **kwargs):
282+
return "baz"
283+
284+
input_dict = {
285+
"foo": PydanticModel(),
286+
}
287+
288+
output = dict_util.flatten_dict(
289+
input_dict,
290+
flatten_functions={"foo": f})
291+
292+
assert output == {
293+
"foo": "baz",
294+
}
295+
296+
297+
def test_handles_compound_output_from_flatten_func():
298+
def f(*args, **kwargs):
299+
return {
300+
"baz": 123,
301+
"qux": 456
302+
}
303+
304+
input_dict = {
305+
"foo": PydanticModel(),
306+
}
307+
308+
output = dict_util.flatten_dict(
309+
input_dict,
310+
flatten_functions={"foo": f})
311+
312+
assert output == {
313+
"foo.baz": 123,
314+
"foo.qux": 456,
315+
}

0 commit comments

Comments
 (0)