-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Error [ERR_REQUIRE_ESM] when using HuggingFace Transformers #2992
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
🤖 Hi, This error is due to the fact that you're trying to import an ECMAScript module into a CommonJS module. Node.js treats files with a A similar issue was addressed in the langchainjs repository here. The solution is to use dynamic imports, which are supported in both CommonJS and ECMAScript modules. Here's how you can modify your code: export const getExamples = async (query: string, apiKey: string) => {
const { MemoryVectorStore } = await import("langchain/vectorstores/memory");
const { OpenAIEmbeddings } = await import("langchain/embeddings/openai");
// Rest of your code
}; This approach uses the Also, ensure that you're using a version of Node.js that supports ECMAScript modules. The current version of Node.js that langchainjs supports is 20 and above, and you're currently using Node.js version 20 as indicated by the .nvmrc file. As for the version of Let me know if this helps or if you have any other questions. SourcesThis response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research. Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant. If you want to continue the conversation, start your reply with @dosu-bot. |
Unfortunately no - it's to do with the way the dependent package is set up. Could you open an issue on them? |
Can you please take a look @hwchase17 ? |
Hi, @Facuiguacel, I'm helping the langchainjs team manage our backlog and am marking this issue as stale. From what I understand, you encountered an [ERR_REQUIRE_ESM] error when using HuggingFace Transformers in a NestJs application. I provided a detailed response explaining the error and suggesting the use of dynamic imports, with a reference to a similar issue in another repository. jacoblee93 suggested opening an issue on the dependent package, and codenameakshay asked hwchase17 to take a look at the issue. Could you please confirm if this issue is still relevant to the latest version of the langchainjs repository? If it is, please let the langchainjs team know by commenting on the issue. Otherwise, feel free to close the issue yourself, or it will be automatically closed in 7 days. Thank you! |
For those people, who still need to use: You can make the following patch, while the current problem is resolved They just need to update line 82 of the Patch:
I hope it is useful to you 👍 |
you can differ the compilation as explain by the transformer.js guy in an obscure stackoverflow post const TransformersApi = Function('return import("@xenova/transformers")')();
const { pipeline } = await TransformersApi; only solution for a complete ESM ts support |
How is this still an open issue? 🤔 |
why not make a PR? 🙌 |
If anyone wanted the full modified file that worked for me: "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HuggingFaceTransformersEmbeddings = void 0;
const embeddings_1 = require("@langchain/core/embeddings");
const chunk_array_1 = require("@langchain/core/utils/chunk_array");
/**
* @example
* ```typescript
* const model = new HuggingFaceTransformersEmbeddings({
* modelName: "Xenova/all-MiniLM-L6-v2",
* });
*
* // Embed a single query
* const res = await model.embedQuery(
* "What would be a good company name for a company that makes colorful socks?"
* );
* console.log({ res });
*
* // Embed multiple documents
* const documentRes = await model.embedDocuments(["Hello world", "Bye bye"]);
* console.log({ documentRes });
* ```
*/
class HuggingFaceTransformersEmbeddings extends embeddings_1.Embeddings {
constructor(fields) {
super(fields ?? {});
Object.defineProperty(this, "modelName", {
enumerable: true,
configurable: true,
writable: true,
value: "Xenova/all-MiniLM-L6-v2"
});
Object.defineProperty(this, "batchSize", {
enumerable: true,
configurable: true,
writable: true,
value: 512
});
Object.defineProperty(this, "stripNewLines", {
enumerable: true,
configurable: true,
writable: true,
value: true
});
Object.defineProperty(this, "timeout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "pipelinePromise", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.modelName = fields?.modelName ?? this.modelName;
this.stripNewLines = fields?.stripNewLines ?? this.stripNewLines;
this.timeout = fields?.timeout;
}
async embedDocuments(texts) {
const batches = (0, chunk_array_1.chunkArray)(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize);
const batchRequests = batches.map((batch) => this.runEmbedding(batch));
const batchResponses = await Promise.all(batchRequests);
const embeddings = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batchResponse = batchResponses[i];
for (let j = 0; j < batchResponse.length; j += 1) {
embeddings.push(batchResponse[j]);
}
}
return embeddings;
}
async embedQuery(text) {
const data = await this.runEmbedding([
this.stripNewLines ? text.replace(/\n/g, " ") : text,
]);
return data[0];
}
async runEmbedding(texts) {
const pipe = await (this.pipelinePromise ??= (await import("@xenova/transformers")).pipeline("feature-extraction", this.modelName));
return this.caller.call(async () => {
const output = await pipe(texts, { pooling: "mean", normalize: true });
return output.tolist();
});
}
}
exports.HuggingFaceTransformersEmbeddings = HuggingFaceTransformersEmbeddings; |
Hi folks, Sorry for missing this issue for so long - have updated @JonaMX's PR to use @Candoyeya's fix, have added it to the CJS export tests, and will aim to get this out today! |
Live in community 0.2.11! |
Hi,
I'm getting this compilation error when trying to use HuggingFaceTransformersEmbeddings.
@xenova/transformers
is installed.Any way around it?
This is my code that's using the module in a NestJs application:
The text was updated successfully, but these errors were encountered: