Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions js/oai.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,45 @@ describe("OAI", () => {
});
});

test("wraps client with dangerouslyAllowBrowser", async () => {
server.use(
http.post("https://api.openai.com/v1/chat/completions", () => {
return HttpResponse.json(MOCK_OPENAI_COMPLETION_RESPONSE);
}),
);

// Create a subclass that throws if dangerouslyAllowBrowser is not passed
// This simulates browser environment behavior
class BrowserOpenAI extends OpenAI {
constructor(opts: ConstructorParameters<typeof OpenAI>[0]) {
if (!opts?.dangerouslyAllowBrowser) {
throw new Error(
"dangerouslyAllowBrowser must be set in browser environment",
);
}
super(opts);
}
}

await withMockWrapper(async ({ createSpy }) => {
const client = new BrowserOpenAI({
apiKey: "test-api-key",
dangerouslyAllowBrowser: true,
});

// This would throw before the fix, because isWrapped() was not
// passing dangerouslyAllowBrowser when constructing the clean client
const builtClient = buildOpenAIClient({ client });

await builtClient.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
});

expect(createSpy).toHaveBeenCalledTimes(1);
});
});

test("init sets client", async () => {
server.use(
http.post("https://api.openai.com/v1/chat/completions", () => {
Expand Down
20 changes: 17 additions & 3 deletions js/oai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,15 @@ const resolveOpenAIClient = (options: OpenAIAuth): OpenAI => {
});
};

const isWrapped = (client: OpenAI): boolean => {
const isWrapped = (
client: OpenAI,
dangerouslyAllowBrowser?: boolean,
): boolean => {
const Constructor = Object.getPrototypeOf(client).constructor;
const clean = new Constructor({ apiKey: "dummy" });
const clean = new Constructor({
apiKey: "dummy",
dangerouslyAllowBrowser,
});
return (
String(client.chat.completions.create) !==
String(clean.chat.completions.create)
Expand All @@ -139,8 +145,16 @@ const isWrapped = (client: OpenAI): boolean => {
export function buildOpenAIClient(options: OpenAIAuth): OpenAI {
const client = resolveOpenAIClient(options);

// Extract from deprecated options or client instance
const dangerouslyAllowBrowser =
options.openAiDangerouslyAllowBrowser ??
(client as any)._options?.dangerouslyAllowBrowser;

// avoid re-wrapping if the client is already wrapped (proxied)
if (globalThis.__inherited_braintrust_wrap_openai && !isWrapped(client)) {
if (
globalThis.__inherited_braintrust_wrap_openai &&
!isWrapped(client, dangerouslyAllowBrowser)
) {
return globalThis.__inherited_braintrust_wrap_openai(client);
}

Expand Down