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-15T00:00:00.000+00:00

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

How to do well in a technical interview

Over the past 7 years I've sat across virtual and physical tables from many software engineers, from bright-eyed juniors to battle-tested veterans with decades of experience under their belts. Today, I want to speak directly to you, the job seeker, and suggest how you can increase your chances of securing a technical role. Of course, this assessment is through my own lens and my advice may not help you in any situation, but as usual you should use your best judgement.

Integrating Auth0 User Invitations with auth0-react's withAuthenticationRequired HOC

Integrating Auth0 user invitations with React applications can be tricky, especially when using the `withAuthenticationRequired` Higher-Order Component (HOC) from `auth0-react`. This article bridges that gap by explaining how to process invitation callbacks seamlessly.

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!