Adding content from API response to new image uploads

I’m trying to use the Astica API to get content for my new attachment uploads. While I have no problem using the API outside WordPress, I can’t seem to get it working inside WordPress.

Intend:

  1. Trigger function when a new attachment image is uploaded
  2. Send $image_url to the API
  3. Extract “caption > text” from the response
  4. Add the text to the post_content field.

Astica documentation

The function:

function cwpai_add_content_to_new_attachment( $attachment_id ) {
    // Get the attachment post object
    $attachment = get_post( $attachment_id );
    $image_url = wp_get_attachment_url( $attachment_id );
    
    // Make sure the attachment is an image
    if ( 'image' === substr( $attachment->post_mime_type, 0, 5 ) ) {
        // Get the current content of the attachment
        $content = $attachment->post_content;
        
        // Add image URL to the caption
        $new_content = $content ? "{$content}<br>{$image_url}" : $image_url;
        
        // Update the attachment post with the new content
       
        
        //Add Astica API script
        wp_enqueue_script( 'asticaAPI', 'https://www.astica.org/endpoint/ml/javascript/2023-04-10/astica.core.js' );
        
        //Add custom script
        wp_add_inline_script( 'asticaAPI', '
            function your_astica_CallBack(data) {   
                if(typeof data.error != "undefined") { alert(data.error); }         
                console.log(data); //view all data
                //Update the attachment post with the Astica response
                wp_update_post( array(
                    "ID" => '.$attachment_id.',
                    "post_content" => json_encode(data)
                ) );
            }
            asticaAPI_start("KEY");

            asticaVision(
                "2.0_full", //modelVersion: 1.0_full, 2.0_full
                "'.$image_url.'", //Input Image
                "description, tags,", //or "all"
                your_astica_CallBack, //Your Custom Callback function
            ); 
           
        ' );
    }
}
add_action( 'add_attachment', 'cwpai_add_content_to_new_attachment' )

Testing inside and outside WordPress, tried with rest API as-well without no luck. Also tried to load it with jQuery and no conflict. Can’t seem to figure it out.