Description
Issue Description:
When using @openai/[email protected]
in a Next.js (v15.2.4, React 19) application, a TypeError: Illegal invocation occurs. This error originates from within the SDK's internal tracing mechanisms when run(agent, ...) is called, specifically in what appears to be utils.mjs according to the stack trace. This happens even when setTracingDisabled(true) is called before any agent operations.
The application uses the standard @openai/agents
package (not @openai/agents-realtime
). The error seems to indicate that a trace-related function is being called with an incorrect this context in the browser environment.
SDK Version:
@openai/agents": "^0.0.1" (from package.json)
Environment:
Next.js v15.2.4
React v19.0.0
Browser (e.g., Chrome, latest)
Node.js (for build, likely v20+ as per SDK recommendations)
Steps to Reproduce:
- Set up a Next.js client component ("use client";).
- Import Agent, run, setDefaultOpenAIClient, setTracingDisabled from
@openai/agents
. - Import OpenAI from openai.
In the component/hook:
- Call setTracingDisabled(true) as early as possible.
- Initialize an OpenAI client instance.
- Call setDefaultOpenAIClient() with the created client instance.
- Define a simple Agent instance (e.g., new Agent({ name: 'TestAgent', instructions: 'You are a test agent.' })).
- Attempt to call await run(agentInstance, "Test input").
Observed Behavior:
A TypeError: Illegal invocation is thrown. The browser console also shows messages like:
BatchTraceProcessor is not supported in the browser. Traces will not be exported.
Stack Trace:
[Orchestrator] Error running WelcomeAgent: TypeError: Illegal invocation
at tX (utils.mjs:15:21) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:17358
at new tq (traces.mjs:12:43) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:18893
at new tY (traces.mjs:54:1) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:19447
at tV.createTrace (provider.mjs:52:1) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:19867
at tP (context.mjs:80:44) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:14263
at n9.run (run.mjs:484:16) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:65421
at n2 (run.mjs:505:1) // Mapped to https://in.ference.ai/_next/static/chunks/682-a6a0afe59dc77b8b.js:42:65545
at l (useOrchestrator.ts:219:43) // Application code: call to SDK's run()
at processAndSend (useOrchestrator.ts:337:9) // Application code
... (React internal calls) ...
Expected Behavior:
Either:
- setTracingDisabled(true) should completely prevent any trace-related code paths that are incompatible with the browser from running.
- The SDK's tracing mechanism should be browser-compatible or gracefully degrade without throwing an "Illegal invocation" error when setTracingDisabled(true) is active.
- The run() function should execute successfully without this internal error.
Code Snippet (Illustrative useOrchestrator.ts setup):
"use client";
import { Agent, run, setDefaultOpenAIClient, setTracingDisabled } from '@openai/agents';
import OpenAI from 'openai';
import { useMemo, useEffect, useState } from 'react';
// Early call to disable tracing
try {
setTracingDisabled(true);
console.log("[Orchestrator] Tracing explicitly disabled for Agent SDK.");
} catch (e) {
console.warn("[Orchestrator] Could not disable tracing for Agent SDK:", e);
}
export const useOrchestrator = () => {
const [message, setMessage] = useState("");
const openaiClient = useMemo(() => {
const apiKey = process.env.NEXT_PUBLIC_OPENAI_API_KEY;
if (!apiKey) {
console.warn("API key not set");
return null;
}
try {
return new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
} catch (e) {
console.error("Failed to create OpenAI client", e);
return null;
}
}, []);
// Set default client immediately if available
if (openaiClient) {
try {
setDefaultOpenAIClient(openaiClient);
console.log("[Orchestrator] Default OpenAI client attempted to be set synchronously.");
} catch (e) {
console.error("[Orchestrator] Failed to set default OpenAI client synchronously:", e);
}
} else {
console.warn("[Orchestrator] OpenAI client is null, cannot set default client.");
}
const testAgent = useMemo(() => {
if (!openaiClient) return null; // Ensure client is set before agent creation
return new Agent({
name: 'TestAgent',
instructions: 'You are a test agent.',
// model: 'gpt-3.5-turbo', // Or your desired model
});
}, [openaiClient]);
const handleRunTest = async () => {
if (!testAgent) {
setMessage("Agent not initialized.");
return;
}
console.log("Attempting to run TestAgent...");
try {
const result = await run(testAgent, "Hello, agent!");
setMessage(JSON.stringify(result.finalOutput) || "No output");
console.log("Agent run successful:", result.finalOutput);
} catch (error) {
const err = error as Error;
console.error("[Orchestrator] Error running TestAgent:", err);
console.error("[Orchestrator] Full error object:", err);
console.error("[Orchestrator] Stack trace:", err.stack);
setMessage(`Error: ${err.message} - Check console for stack trace.`);
}
};
return { message, handleRunTest };
};
(Note: The above snippet is a simplified version for reproduction and might need adjustments to exactly match the full setup, particularly around how llmConfig and llmPromptsConfig are used for model/temperature if those are essential for basic agent run.)
Additional Context:
The project successfully builds after changes to ensure setDefaultOpenAIClient is called synchronously (avoiding previous SSR ReferenceError). The "Illegal invocation" is a runtime error in the browser. The application also uses tools defined with arrow functions for their execute methods, which are unlikely to be the source of this specific this-context error.