Files
lancedb/nodejs/lancedb/embedding/openai.ts
T
Alex Castillo González fc13fd6e98 fix(nodejs): batch OpenAI embedding requests to 2048 inputs (#4833)
`OpenAIEmbeddingFunction.computeSourceEmbeddings` in the Node SDK sent
every row in a single `embeddings.create` call. `makeArrowTable` passes
the whole source column at once, and the OpenAI embeddings endpoint
accepts at most 2048 inputs per request, so `table.add` (or
`createTable`) with more than 2048 rows and an `openai` embedding
function fails with a 400.

This splits the input into chunks of at most 2048 and concatenates the
results in order. Inputs of 2048 rows or fewer still make one request,
as before.

Test: `nodejs/__test__/embedding_openai.test.ts` mocks `openai`
(rejecting requests with more than 2048 inputs) and checks that 5000
rows produce 5000 embeddings, in order, over three calls (2048, 2048,
904). It fails without the change and passes with it.

This change was prepared with AI assistance (Claude Code).
2026-11-30 19:14:00 +08:00

109 lines
2.9 KiB
TypeScript

// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import type OpenAI from "openai";
import type { EmbeddingCreateParams } from "openai/resources/index";
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"];
};
export class OpenAIEmbeddingFunction extends EmbeddingFunction<
string,
Partial<OpenAIOptions>
> {
#openai: OpenAI;
#modelName: OpenAIOptions["model"];
constructor(
optionsRaw: Partial<OpenAIOptions> = {
model: "text-embedding-ada-002",
},
) {
super();
const options = this.resolveVariables(optionsRaw);
const openAIKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
if (!openAIKey) {
throw new Error("OpenAI API key is required");
}
const modelName = options?.model ?? "text-embedding-ada-002";
/**
* @type {import("openai").default}
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
let Openai;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
Openai = require("openai");
} catch {
throw new Error("please install openai@^4.24.1 using npm install openai");
}
const configuration = {
apiKey: openAIKey,
};
this.#openai = new Openai(configuration);
this.#modelName = modelName;
}
protected getSensitiveKeys(): string[] {
return ["apiKey"];
}
ndims(): number {
switch (this.#modelName) {
case "text-embedding-ada-002":
return 1536;
case "text-embedding-3-large":
return 3072;
case "text-embedding-3-small":
return 1536;
default:
throw new Error(`Unknown model: ${this.#modelName}`);
}
}
embeddingDataType(): Float {
return new Float32();
}
async computeSourceEmbeddings(data: string[]): Promise<number[][]> {
const embeddings: number[][] = [];
// 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;
}
async computeQueryEmbeddings(data: string): Promise<number[]> {
if (typeof data !== "string") {
throw new Error("Data must be a string");
}
const response = await this.#openai.embeddings.create({
model: this.#modelName,
input: data,
});
return response.data[0].embedding;
}
}
registerBuiltIn("openai", OpenAIEmbeddingFunction);