@@ -1095,31 +1095,45 @@ def _get_output_attributes(template, send_pii, result):
10951095 attributes = {} # type: dict[str, Any]
10961096
10971097 if template in [SPANTEMPLATE .AI_AGENT , SPANTEMPLATE .AI_TOOL , SPANTEMPLATE .AI_CHAT ]:
1098- attributes .update (_get_usage_attributes (result ))
1098+ # Usage from result, result.usage, and result.metadata.usage
1099+ usage_candidates = [result ]
1100+ if isinstance (result , dict ):
1101+ usage_candidates .append (result .get ("usage" ))
1102+ meta = result .get ("metadata" )
1103+ else :
1104+ usage_candidates .append (getattr (result , "usage" , None ))
1105+ meta = getattr (result , "metadata" , None )
1106+
1107+ if isinstance (meta , dict ):
1108+ usage_candidates .append (meta .get ("usage" ))
1109+ elif meta is not None :
1110+ usage_candidates .append (getattr (meta , "usage" , None ))
10991111
1112+ for usage_candidate in usage_candidates :
1113+ if usage_candidate is not None :
1114+ attributes .update (_get_usage_attributes (usage_candidate ))
1115+
1116+ # Response model
1117+ model_name = None
11001118 if isinstance (result , dict ):
1101- if "usage" in result :
1102- attributes .update (_get_usage_attributes (result ["usage" ]))
1103- if (
1104- "metadata" in result
1105- and result ["metadata" ]
1106- and "usage" in result ["metadata" ]
1107- ):
1108- attributes .update (_get_usage_attributes (result ["metadata" ]["usage" ]))
1109- if "model" in result :
1110- attributes [SPANDATA .GEN_AI_RESPONSE_MODEL ] = result ["model" ]
1111- if "model_name" in result :
1112- attributes [SPANDATA .GEN_AI_RESPONSE_MODEL ] = result ["model_name" ]
1119+ val = result .get ("model" )
1120+ if isinstance (val , str ):
1121+ model_name = val
1122+ val = result .get ("model_name" )
1123+ if isinstance (val , str ):
1124+ model_name = val
11131125 else :
1114- if hasattr (result , "usage" ):
1115- attributes .update (_get_usage_attributes (result .usage ))
1116- if hasattr (result , "metadata" ) and hasattr (result .metadata , "usage" ):
1117- attributes .update (_get_usage_attributes (result .metadata .usage ))
1118- if hasattr (result , "model" ) and isinstance (result .model , str ):
1119- attributes [SPANDATA .GEN_AI_RESPONSE_MODEL ] = result .model
1120- if hasattr (result , "model_name" ) and isinstance (result .model_name , str ):
1121- attributes [SPANDATA .GEN_AI_RESPONSE_MODEL ] = result .model_name
1126+ val = getattr (result , "model" , None )
1127+ if isinstance (val , str ):
1128+ model_name = val
1129+ val = getattr (result , "model_name" , None )
1130+ if isinstance (val , str ):
1131+ model_name = val
1132+
1133+ if model_name is not None :
1134+ attributes [SPANDATA .GEN_AI_RESPONSE_MODEL ] = model_name
11221135
1136+ # Tool output
11231137 if template == SPANTEMPLATE .AI_TOOL and send_pii :
11241138 attributes [SPANDATA .GEN_AI_TOOL_OUTPUT ] = safe_repr (result )
11251139
0 commit comments