@n8n/n8n-nodes-langchain
Version:
65 lines • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BedrockInvokeModelEmbeddings = void 0;
const client_bedrock_runtime_1 = require("@aws-sdk/client-bedrock-runtime");
const embeddings_1 = require("@langchain/core/embeddings");
const n8n_workflow_1 = require("n8n-workflow");
function selectEmbeddingType(byType) {
if (byType === undefined) {
return undefined;
}
if (Array.isArray(byType.float)) {
return byType.float;
}
const keyed = Object.values(byType).filter((value) => Array.isArray(value));
return keyed.length === 1 ? keyed[0] : undefined;
}
class BedrockInvokeModelEmbeddings extends embeddings_1.Embeddings {
constructor({ client, model, additionalModelRequestFields }) {
super({ maxRetries: 0 });
this.client = client;
this.model = model;
this.additionalModelRequestFields = additionalModelRequestFields ?? {};
}
buildRequestBody(text, inputType) {
const cleanedText = text.replace(/\n/g, ' ');
if (this.model.includes('cohere.embed')) {
return { texts: [cleanedText], input_type: inputType, ...this.additionalModelRequestFields };
}
return { inputText: cleanedText, ...this.additionalModelRequestFields };
}
async embed(text, inputType) {
return await this.caller.call(async () => {
const response = await this.client.send(new client_bedrock_runtime_1.InvokeModelCommand({
modelId: this.model,
body: JSON.stringify(this.buildRequestBody(text, inputType)),
contentType: 'application/json',
accept: 'application/json',
}));
const body = (0, n8n_workflow_1.jsonParse)(new TextDecoder().decode(response.body));
if (Array.isArray(body.embedding)) {
return body.embedding;
}
const titanTyped = selectEmbeddingType(body.embeddingsByType);
if (titanTyped) {
return titanTyped;
}
const rows = Array.isArray(body.embeddings)
? body.embeddings
: selectEmbeddingType(body.embeddings);
const first = rows?.[0];
if (Array.isArray(first)) {
return first;
}
throw new n8n_workflow_1.OperationalError('Unexpected embedding response from Bedrock');
});
}
async embedDocuments(documents) {
return await Promise.all(documents.map(async (document) => await this.embed(document, 'search_document')));
}
async embedQuery(text) {
return await this.embed(text, 'search_query');
}
}
exports.BedrockInvokeModelEmbeddings = BedrockInvokeModelEmbeddings;
//# sourceMappingURL=BedrockInvokeModelEmbeddings.js.map