Hi, I'm Radu

Fixing OpenAI and Anthropic initialization errors when using Newrelic Agent in ESM projects

Read time: 1 minute

Published on: 2024-11-20T14:55:24.000Z

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!

You might also like

Launching Yappa, a new productivity tool for freelancers and contractors

I am pleased to announce the launch of Yappa, a powerful productivity tool designed by a freelancer, for freelancers. Yappa helps streamline client management, simplify time tracking, and more - all in one place. In this article I share the story behind Yappa and give a technical sneak peek into how it was built.

How I built this website

Follow my journey of building my personal website from idea to launch, mistakes and all. Expect OpenAI-generated color palette, SvelteKit, Tailwind, a few bad decisions and a dash of overengineering.

Using Azure Deployment Stacks

Deployment stacks are a powerful feature of Azure that can bring sanity to complex deployments. In this short article I'll explain what they are by exploring a simple use case.

Who I am

I'm a seasoned software engineer on a mission to help startups take flight, because in today's world good tech is the difference between disruptor and... well, disrupted.


Want to build a winner? Let's chat!