Skip to content

Commit b551530

Browse files
committed
refactor: Simplify metadata serialization by removing redundant JSON conversion
- Remove _make_json_serializable method entirely - Refactor _convert_value_to_proto to handle dictionaries and lists recursively - Fix null value handling to use struct_pb2.NULL_VALUE - Improve code efficiency and maintainability - All tests passing
1 parent 49824b3 commit b551530

File tree

1 file changed

+14
-23
lines changed

1 file changed

+14
-23
lines changed

src/a2a/utils/proto_utils.py

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,7 @@ def metadata(
6060
def _convert_value_to_proto(cls, value: Any) -> struct_pb2.Value:
6161
"""Convert Python value to protobuf Value."""
6262
if value is None:
63-
proto_value = struct_pb2.Value()
64-
proto_value.null_value = 0
65-
return proto_value
63+
return struct_pb2.Value(null_value=struct_pb2.NULL_VALUE)
6664
if isinstance(value, bool):
6765
return struct_pb2.Value(bool_value=value)
6866
if isinstance(value, int):
@@ -74,29 +72,22 @@ def _convert_value_to_proto(cls, value: Any) -> struct_pb2.Value:
7472
if isinstance(value, str):
7573
return struct_pb2.Value(string_value=value)
7674
if isinstance(value, dict):
77-
serializable_dict = cls._make_json_serializable(value)
78-
json_data = json.dumps(serializable_dict, ensure_ascii=False)
79-
struct_value = struct_pb2.Struct()
80-
json_format.Parse(json_data, struct_value)
81-
return struct_pb2.Value(struct_value=struct_value)
75+
return struct_pb2.Value(
76+
struct_value=struct_pb2.Struct(
77+
fields={
78+
k: cls._convert_value_to_proto(v)
79+
for k, v in value.items()
80+
}
81+
)
82+
)
8283
if isinstance(value, list | tuple):
83-
list_value = struct_pb2.ListValue()
84-
for item in value:
85-
converted_item = cls._convert_value_to_proto(item)
86-
list_value.values.append(converted_item)
87-
return struct_pb2.Value(list_value=list_value)
84+
return struct_pb2.Value(
85+
list_value=struct_pb2.ListValue(
86+
values=[cls._convert_value_to_proto(item) for item in value]
87+
)
88+
)
8889
return struct_pb2.Value(string_value=str(value))
8990

90-
@classmethod
91-
def _make_json_serializable(cls, value: Any) -> Any:
92-
if value is None or isinstance(value, str | int | float | bool):
93-
return value
94-
if isinstance(value, dict):
95-
return {k: cls._make_json_serializable(v) for k, v in value.items()}
96-
if isinstance(value, list | tuple):
97-
return [cls._make_json_serializable(item) for item in value]
98-
return str(value)
99-
10091
@classmethod
10192
def part(cls, part: types.Part) -> a2a_pb2.Part:
10293
if isinstance(part.root, types.TextPart):

0 commit comments

Comments
 (0)