10000 Prevent JSON parsing errors and preserve non-ascii characters in tele… · google/adk-python@d587270 · GitHub
[go: up one dir, main page]

Skip to content

Commit d587270

Browse files
selcukguncopybara-github
authored andcommitted
Prevent JSON parsing errors and preserve non-ascii characters in telemetry
PiperOrigin-RevId: 764801572
1 parent 1de5c34 commit d587270

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

src/google/adk/telemetry.py

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,25 @@
3838
tracer = trace.get_tracer('gcp.vertex.agent')
3939

4040

41+
def _safe_json_serialize(obj) -> str:
42+
"""Convert any Python object to a JSON-serializable type or string.
43+
44+
Args:
45+
obj: The object to serialize.
46+
47+
Returns:
48+
The JSON-serialized object string or <non-serializable> if the object cannot be serialized.
49+
"""
50+
51+
try:
52+
# Try direct JSON serialization first
53+
return json.dumps(
54+
obj, ensure_ascii=False, default=lambda o: '<not serializable>'
55+
)
56+
except (TypeError, OverflowError):
57+
return '<not serializable>'
58+
59+
4160
def trace_tool_call(
4261
tool: BaseTool,
4362
args: dict[str, Any],
@@ -69,11 +88,14 @@ def trace_tool_call(
6988

7089
if not isinstance(tool_response, dict):
7190
tool_response = {'result': tool_response}
72-
span.set_attribute('gcp.vertex.agent.tool_call_args', json.dumps(args))
91+
span.set_attribute(
92+
'gcp.vertex.agent.tool_call_args',
93+
_safe_json_serialize(args),
94+
)
7395
span.set_attribute('gcp.vertex.agent.event_id', function_response_event.id)
7496
span.set_attribute(
7597
'gcp.vertex.agent.tool_response',
76-
json.dumps(tool_response),
98+
_safe_json_serialize(tool_response),
7799
)
78100
# Setting empty llm request and response (as UI expect these) while not
79101
# applicable for tool_response.
@@ -159,10 +181,7 @@ def trace_call_llm(
159181
# Consider removing once GenAI SDK provides a way to record this info.
160182
span.set_attribute(
161183
'gcp.vertex.agent.llm_request',
162-
json.dumps(
163-
_build_llm_request_for_trace(llm_request),
164-
default=lambda o: '<not serializable>',
165-
),
184+
_safe_json_serialize(_build_llm_request_for_trace(llm_request)),
166185
)
167186
# Consider removing once GenAI SDK provides a way to record this info.
168187

@@ -201,7 +220,7 @@ def trace_send_data(
201220
# information still needs to be recorded by the Agent Development Kit.
202221
span.set_attribute(
203222
'gcp.vertex.agent.data',
204-
json.dumps([
223+
_safe_json_serialize([
205224
types.Content(role=content.role, parts=content.parts).model_dump(
206225
exclude_none=True
207226
)

0 commit comments

Comments
 (0)
0