diff --git a/nodejs/__test__/embedding_openai.test.ts b/nodejs/__test__/embedding_openai.test.ts new file mode 100644 index 000000000..85a3eab09 --- /dev/null +++ b/nodejs/__test__/embedding_openai.test.ts @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const create = jest.fn(); + +jest.mock("openai", () => + jest.fn().mockImplementation(() => ({ embeddings: { create } })), +); + +import { OpenAIEmbeddingFunction } from "../lancedb/embedding/openai"; +import { getRegistry } from "../lancedb/embedding/registry"; + +describe("OpenAIEmbeddingFunction", () => { + beforeEach(() => { + create.mockReset(); + create.mockImplementation(async ({ input }: { input: string[] }) => { + if (input.length > 2048) { + throw new Error("400 max 2048 inputs per request"); + } + return { data: input.map((_, i) => ({ embedding: [i] })) }; + }); + }); + + it("splits source embeddings into batches of at most 2048 inputs", async () => { + const registry = getRegistry(); + registry.setVar("openai_api_key", "sk-test"); + const func = new OpenAIEmbeddingFunction({ + apiKey: "$var:openai_api_key", + model: "text-embedding-3-small", + }); + const data = Array.from({ length: 5000 }, (_, i) => `row ${i}`); + + const embeddings = await func.computeSourceEmbeddings(data); + + expect(embeddings).toHaveLength(5000); + expect(create.mock.calls.map(([args]) => args.input.length)).toEqual([ + 2048, 2048, 904, + ]); + }); +}); diff --git a/nodejs/lancedb/embedding/openai.ts b/nodejs/lancedb/embedding/openai.ts index 2218d44bc..94fea88b7 100644 --- a/nodejs/lancedb/embedding/openai.ts +++ b/nodejs/lancedb/embedding/openai.ts @@ -7,6 +7,9 @@ import { Float, Float32 } from "../arrow"; import { EmbeddingFunction } from "./embedding_function"; import { registerBuiltIn } from "./registry"; +// Maximum number of inputs the OpenAI embeddings API accepts per request. +const MAX_INPUTS_PER_REQUEST = 2048; + export type OpenAIOptions = { apiKey: string; model: EmbeddingCreateParams["model"]; @@ -75,14 +78,16 @@ export class OpenAIEmbeddingFunction extends EmbeddingFunction< } async computeSourceEmbeddings(data: string[]): Promise { - const response = await this.#openai.embeddings.create({ - model: this.#modelName, - input: data, - }); - const embeddings: number[][] = []; - for (let i = 0; i < response.data.length; i++) { - embeddings.push(response.data[i].embedding); + // The OpenAI embeddings endpoint accepts at most 2048 inputs per request. + for (let start = 0; start < data.length; start += MAX_INPUTS_PER_REQUEST) { + const response = await this.#openai.embeddings.create({ + model: this.#modelName, + input: data.slice(start, start + MAX_INPUTS_PER_REQUEST), + }); + for (let i = 0; i < response.data.length; i++) { + embeddings.push(response.data[i].embedding); + } } return embeddings; }