Skip to content

A suggestion for #40518 - don't serialize args and simplify code #40597

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

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,8 @@
GEN_AI_THREAD_RUN_STATUS,
GEN_AI_USAGE_INPUT_TOKENS,
GEN_AI_USAGE_OUTPUT_TOKENS,
GEN_AI_RUNSTEP_START_TIMESTAMP,
GEN_AI_RUNSTEP_END_TIMESTAMP,
GEN_AI_RUNSTEP_CANCEL_TIMESTAMP,
GEN_AI_RUNSTEP_FAIL_TIMESTAMP,
GEN_AI_RUN_STEP_START_TIMESTAMP,
GEN_AI_RUN_STEP_END_TIMESTAMP,
GEN_AI_RUN_STEP_STATUS,
ERROR_MESSAGE,
OperationName,
Expand Down Expand Up @@ -292,31 +290,24 @@ def _create_event_attributes(

if created_at:
if isinstance(created_at, datetime):
attrs[GEN_AI_RUNSTEP_START_TIMESTAMP] = created_at.isoformat()
attrs[GEN_AI_RUN_STEP_START_TIMESTAMP] = created_at.isoformat()
else:
# fallback in case int or string gets passed
attrs[GEN_AI_RUNSTEP_START_TIMESTAMP] = str(created_at)
attrs[GEN_AI_RUN_STEP_START_TIMESTAMP] = str(created_at)

end_timestamp = None
if completed_at:
if isinstance(completed_at, datetime):
attrs[GEN_AI_RUNSTEP_END_TIMESTAMP] = completed_at.isoformat()
else:
# fallback in case int or string gets passed
attrs[GEN_AI_RUNSTEP_END_TIMESTAMP] = str(completed_at)

if cancelled_at:
if isinstance(cancelled_at, datetime):
attrs[GEN_AI_RUNSTEP_CANCEL_TIMESTAMP] = cancelled_at.isoformat()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we record status of step on line 289, no need to make it part of the attribute name

else:
# fallback in case int or string gets passed
attrs[GEN_AI_RUNSTEP_CANCEL_TIMESTAMP] = str(cancelled_at)

if failed_at:
if isinstance(failed_at, datetime):
attrs[GEN_AI_RUNSTEP_FAIL_TIMESTAMP] = failed_at.isoformat()
else:
# fallback in case int or string gets passed
attrs[GEN_AI_RUNSTEP_FAIL_TIMESTAMP] = failed_at.isoformat()
end_timestamp = completed_at
elif cancelled_at:
end_timestamp = cancelled_at
elif failed_at:
end_timestamp = failed_at

if isinstance(end_timestamp, datetime):
attrs[GEN_AI_RUN_STEP_END_TIMESTAMP] = end_timestamp.isoformat()
else:
# fallback in case int or string gets passed
attrs[GEN_AI_RUN_STEP_END_TIMESTAMP] = str(end_timestamp)

if run_step_last_error:
attrs[ERROR_MESSAGE] = run_step_last_error.message
Expand Down Expand Up @@ -356,32 +347,6 @@ def add_thread_message_event(
usage=usage,
)

def _get_tool_details(self, tool: Any) -> Dict[str, Any]:
"""
Extracts tool details from a tool object dynamically and ensures the result is JSON-serializable.

:param tool: The tool object (e.g., RunStepToolCallDetails).
:return: A dictionary containing the tool details.
"""
tool_details = {}

# Dynamically extract attributes from the tool object
for attr in dir(tool):
# Skip private or special attributes
if not attr.startswith("_") and not callable(getattr(tool, attr)):
try:
value = getattr(tool, attr)
# Ensure the value is JSON-serializable
if isinstance(value, (str, int, float, bool, list, dict, type(None))):
tool_details[attr] = value
else:
# Convert non-serializable objects to strings
tool_details[attr] = str(value)
except Exception as e:
logging.warning("Error extracting attribute '%s': %s", attr, str(e))

return tool_details

def _process_tool_calls(self, step: RunStep) -> List[Dict[str, Any]]:
"""
Helper method to process tool calls and return a list of tool call dictionaries.
Expand All @@ -408,41 +373,24 @@ def _process_tool_calls(self, step: RunStep) -> List[Dict[str, Any]]:
},
}
elif isinstance(t, RunStepCodeInterpreterToolCall):
try:
parsed_outputs = json.dumps(t.code_interpreter.outputs)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this results in a huge escaped string, there is no need to dump it.

except Exception as e:
logging.warning("Error parsing code interpreter outputs: '%s'", str(e))
parsed_outputs = {}

tool_call = {
"id": t.id,
"type": t.type,
"code_interpreter": {
"input": t.code_interpreter.input,
"output": parsed_outputs,
"outputs": [output.as_dict() for output in t.code_interpreter.outputs],
},
}
elif isinstance(t, RunStepBingGroundingToolCall):
bing_grounding = {}
try:
bing_grounding = json.dumps(t.bing_grounding)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, dumping results in a string rather than object

except Exception as e:
logging.warning("Error parsing Bing grounding: '%s'", str(e))
parsed_outputs = {}

tool_call = {
"id": t.id,
"type": t.type,
t.type: {
"bing_grounding": bing_grounding
"bing_grounding": t.bing_grounding
},
}
else:
try:
tool_details = json.dumps(self._get_tool_details(t))
except Exception as e:
logging.warning("Error parsing step details: '%s'", str(e))
tool_details = ""
tool_details = t.as_dict()[t.type]

tool_call = {
"id": t.id,
Expand Down Expand Up @@ -625,10 +573,10 @@ def _add_tool_event_from_thread_run(self, span, run: ThreadRun) -> None:
)

if _trace_agents_content:
attributes[GEN_AI_EVENT_CONTENT] = json.dumps({"tool_calls": tool_calls})
attributes[GEN_AI_EVENT_CONTENT] = json.dumps({"tool_calls": tool_calls}, ensure_ascii=False)
else:
tool_calls_non_recording = self._remove_function_call_names_and_arguments(tool_calls=tool_calls)
attributes[GEN_AI_EVENT_CONTENT] = json.dumps({"tool_calls": tool_calls_non_recording})
attributes[GEN_AI_EVENT_CONTENT] = json.dumps({"tool_calls": tool_calls_non_recording}, ensure_ascii=False)
span.span_instance.add_event(name="gen_ai.assistant.message", attributes=attributes)

def set_end_run(self, span: "AbstractSpan", run: Optional[ThreadRun]) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,8 @@
GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"
GEN_AI_EVENT_CONTENT = "gen_ai.event.content"
GEN_AI_RUNSTEP_START_TIMESTAMP = "gen_ai.run_step.start.timestamp"
GEN_AI_RUNSTEP_END_TIMESTAMP = "gen_ai.run_step.end.timestamp"
GEN_AI_RUNSTEP_CANCEL_TIMESTAMP = "gen_ai.run_step.cancel.timestamp"
GEN_AI_RUNSTEP_FAIL_TIMESTAMP = "gen_ai.run_step.fail.timestamp"
GEN_AI_RUN_STEP_START_TIMESTAMP = "gen_ai.run_step.start.timestamp"
GEN_AI_RUN_STEP_END_TIMESTAMP = "gen_ai.run_step.end.timestamp"
GEN_AI_RUN_STEP_STATUS = "gen_ai.run_step.status"
ERROR_TYPE = "error.type"
ERROR_MESSAGE = "error.message"
Expand Down