I'm going to keep this very short and sweet, as if you're here you've probably spent time figuring out why you get weird errors such as:
TypeError: getDefaultAgent is not a function
when using openai
or anthropic
packages.
Summary
Using Newrelic’s suggested approach to initialization on ESM projects can sometimes break packages like openai-node
and anthropic-ai
. This guide provides a simple workaround using a custom loader to exclude these packages from being intercepted, ensuring your application runs smoothly and Newrelic Agent bootstraps correctly.
Related issues
I also assume you probably went through these issues as you searched for a solution, without success. If not, it's worth going through them to understand the underlying issue, which I'm not going to explore here:
Quick Solution
Create loader.mjs in your project root:
// loader.mjs
import { register } from 'node:module';
register('import-in-the-middle/hook.mjs', import.meta.url, {
parentURL: import.meta.url,
data: { exclude: [/openai/] }, // Use [/anthropic/] if anthropic packages are affected
});
Start your service using:
node --import ./loader.mjs -r newrelic ./dist
Double check that you still see logs in Newrelic. I recommend setting up an alert if no logs are pushed to Newrelic for a while, for safety.
Are you a freelancer looking for the ultimate productivity tool for you? Look no further - check out Yappa!