`Reflect.get called on non-object` error when using OpenAI library in NextJS

I'm having issues in getting OpenAI library to work in NextJS project on Cloudflare Pages. I got the following error in workers log stream when calling the API endpoint on NextJS app:
{
"message": [
"TypeError: Reflect.get called on non-object"
],
"level": "error",
"timestamp": 1695279765223
}
{
"message": [
"TypeError: Reflect.get called on non-object"
],
"level": "error",
"timestamp": 1695279765223
}
Below is the minimal code that reproduce the issue:
import { OpenAI } from "openai";

export async function POST(requestContext: Request) {
const gptClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const requestBody = await requestContext.json();
const gptRes = await gptClient.chat.completions.create({
model: "gpt-4",
messages: [{ role: "system", content: requestBody.systemPrompt }],
});

return new Response(JSON.stringify(gptRes), {
headers: { "Content-Type": "application/json" },
});
}

/// Route Segment Config
export const runtime = "edge";
import { OpenAI } from "openai";

export async function POST(requestContext: Request) {
const gptClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const requestBody = await requestContext.json();
const gptRes = await gptClient.chat.completions.create({
model: "gpt-4",
messages: [{ role: "system", content: requestBody.systemPrompt }],
});

return new Response(JSON.stringify(gptRes), {
headers: { "Content-Type": "application/json" },
});
}

/// Route Segment Config
export const runtime = "edge";
I tried searching around on the internet to see if anyone encounter the same issues and possible solution but I couldn't found any. Interestingly, the example from Cloudflare Docs Stream OpenAI API Responses seems to be working when I tried it.
Stream OpenAI API Responses · Cloudflare Workers docs
Documentation for Cloudflare Workers, a serverless execution environment that allows you to create entirely new applications or augment existing ones …
5 Replies
askprateek
askprateek14mo ago
We are facing the same issue. Can anyone help? @Cloudflare (Server Owner) ?
justjumper
justjumper14mo ago
Also facing the same issue!
no
no10mo ago
+1
James
James10mo ago
GitHub
🐛 Bug Report — Runtime APIs: The AsyncContext of AsynLocalStorages ...
If I define a custom thenable and try to access the store of an AsyncLocalStorage in the then method, the store seems to be undefined although it shouldn't be. Basically: import { AsyncLocalSto...
no
no10mo ago
I switched to directly calling the OpenAI API instead of using the npm package, and it worked.
Want results from more Discord servers?
Add your server