@n8n/n8n-nodes-langchain
Version:
217 lines • 10.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryLakebaseChat = exports.LakebaseChatMessageHistory = void 0;
const memory_1 = require("@langchain/classic/memory");
const chat_history_1 = require("@langchain/core/chat_history");
const messages_1 = require("@langchain/core/messages");
const ai_utilities_1 = require("@n8n/ai-utilities");
const helpers_1 = require("n8n-nodes-base/dist/nodes/Databricks/actions/lakebase/helpers");
const constants_1 = require("n8n-nodes-base/dist/nodes/Databricks/constants");
const listSearch_1 = require("n8n-nodes-base/dist/nodes/Databricks/methods/listSearch");
const parameters_1 = require("n8n-nodes-base/dist/nodes/Databricks/resources/lakebase/parameters");
const transport_1 = require("n8n-nodes-base/dist/nodes/Databricks/transport");
const n8n_workflow_1 = require("n8n-workflow");
const helpers_2 = require("../../../utils/helpers");
const sqlIdentifier_1 = require("../../../utils/sqlIdentifier");
const descriptions_1 = require("../descriptions");
const ROLE_PLACEHOLDER = 'replace "your-role" with the Postgres role of the OAuth2 identity (user email or service principal application ID), then retry.';
function grantStatements(schema, table) {
const qualified = `${(0, sqlIdentifier_1.escapeSqlIdentifier)(schema)}.${(0, sqlIdentifier_1.escapeSqlIdentifier)(table)}`;
const sequence = `${(0, sqlIdentifier_1.escapeSqlIdentifier)(schema)}.${(0, sqlIdentifier_1.escapeSqlIdentifier)(`${table}_id_seq`)}`;
return [
`GRANT USAGE ON SCHEMA ${(0, sqlIdentifier_1.escapeSqlIdentifier)(schema)} TO "your-role";`,
`GRANT SELECT, INSERT, DELETE ON ${qualified} TO "your-role";`,
`GRANT USAGE ON SEQUENCE ${sequence} TO "your-role";`,
];
}
function sqlHint(intro, statements) {
return [intro, ...statements.map((statement) => `\`${statement}\``)].join('<br>');
}
function missingTableHint(schema, table) {
const qualified = `${(0, sqlIdentifier_1.escapeSqlIdentifier)(schema)}.${(0, sqlIdentifier_1.escapeSqlIdentifier)(table)}`;
return sqlHint(`The Lakebase Data API cannot create tables. Run this in the Databricks SQL editor, ${ROLE_PLACEHOLDER}`, [
`CREATE TABLE ${qualified} (id SERIAL PRIMARY KEY, session_id VARCHAR(255) NOT NULL, message JSONB NOT NULL);`,
`CREATE INDEX ON ${qualified} (session_id, id);`,
...grantStatements(schema, table),
]);
}
function missingGrantHint(schema, table) {
return sqlHint(`The table exists but the OAuth2 identity has no rights on it. Run this in the Databricks SQL editor as the table owner, ${ROLE_PLACEHOLDER}`, grantStatements(schema, table));
}
class LakebaseChatMessageHistory extends chat_history_1.BaseListChatMessageHistory {
constructor(context, target) {
super();
this.context = context;
this.target = target;
this.lc_namespace = ['n8n', 'stores', 'message', 'lakebase'];
}
async request(options) {
try {
return await (0, transport_1.lakebaseApiRequest)(this.context, {
...options,
url: this.target.tableUrl,
json: true,
});
}
catch (error) {
const data = (0, transport_1.lakebaseErrorBody)(error) ?? {};
const { schema, table } = this.target;
if (data.code === 'PGRST205' || data.code === '42P01') {
throw new n8n_workflow_1.NodeOperationError(this.context.getNode(), `Table ${schema}.${table} does not exist`, { description: missingTableHint(schema, table) });
}
if (data.code === '42501' &&
typeof data.message === 'string' &&
/permission denied for (schema|table|sequence)/.test(data.message)) {
throw new n8n_workflow_1.NodeOperationError(this.context.getNode(), `The OAuth2 identity cannot use table ${schema}.${table}`, { description: missingGrantHint(schema, table) });
}
throw error;
}
}
async getMessages() {
const rows = [];
let readToTheEnd = false;
for (let page = 0; page < constants_1.LAKEBASE_MAX_PAGES; page++) {
const response = await this.request({
method: 'GET',
qs: {
session_id: `eq.${this.target.sessionId}`,
order: 'id.asc',
limit: constants_1.LAKEBASE_PAGE_SIZE,
offset: rows.length,
},
headers: { Accept: 'application/json', Prefer: 'count=exact' },
returnFullResponse: true,
});
const batch = Array.isArray(response.body) ? response.body : [];
rows.push(...batch);
const total = Number(/\/(\d+)$/.exec(String(response.headers?.['content-range']))?.[1]);
if (batch.length === 0 || rows.length >= total) {
readToTheEnd = true;
break;
}
}
if (!readToTheEnd) {
throw new n8n_workflow_1.NodeOperationError(this.context.getNode(), `The session holds more rows than one run can read (${constants_1.LAKEBASE_MAX_PAGES * constants_1.LAKEBASE_PAGE_SIZE})`, { description: 'Clear the session with the Memory Manager node or use a new Session ID.' });
}
return (0, messages_1.mapStoredMessagesToChatMessages)(rows.map(({ message: { type, ...data } }) => ({ type, data })));
}
async addMessage(message) {
await this.addMessages([message]);
}
async addMessages(messages) {
if (messages.length === 0)
return;
await this.request({
method: 'POST',
body: (0, messages_1.mapChatMessagesToStoredMessages)(messages).map(({ data, type }) => ({
session_id: this.target.sessionId,
message: { ...data, type },
})),
});
}
async clear() {
await this.request({
method: 'DELETE',
qs: { session_id: `eq.${this.target.sessionId}` },
});
}
}
exports.LakebaseChatMessageHistory = LakebaseChatMessageHistory;
class MemoryLakebaseChat {
constructor() {
this.description = {
displayName: 'Databricks Lakebase Chat Memory',
name: 'memoryLakebaseChat',
icon: {
light: 'file:../../shared/icons/databricks.svg',
dark: 'file:../../shared/icons/databricks.dark.svg',
},
group: ['transform'],
version: [1],
description: 'Stores the chat history in a Databricks Lakebase table.',
defaults: {
name: 'Databricks Lakebase Chat Memory',
},
credentials: [
{
name: 'databricksOAuth2Api',
required: true,
},
],
codex: {
categories: ['AI'],
subcategories: {
AI: ['Memory'],
Memory: ['Other memories'],
},
resources: {
primaryDocumentation: [
{
url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.memorylakebasechat/',
},
],
},
},
inputs: [],
outputs: [n8n_workflow_1.NodeConnectionTypes.AiMemory],
outputNames: ['Memory'],
properties: [
(0, ai_utilities_1.getConnectionHintNoticeField)([n8n_workflow_1.NodeConnectionTypes.AiAgent]),
{ displayName: 'Authentication', name: 'authentication', type: 'hidden', default: 'oAuth2' },
...parameters_1.lakebaseLocators.filter((p) => p.name !== 'lakebaseTable'),
{
displayName: 'Table Name',
name: 'lakebaseTable',
type: 'string',
default: 'n8n_chat_histories',
required: true,
description: 'The table in the schema that stores the chat history',
},
{
displayName: 'This node cannot create the table. Create it in the Lakebase SQL editor before the first run. A run against a missing table shows the SQL to copy.',
name: 'createTableNotice',
type: 'notice',
default: '',
},
descriptions_1.sessionIdOption,
(0, descriptions_1.expressionSessionKeyProperty)(1),
(0, descriptions_1.scopedSessionHint)(1),
descriptions_1.sessionKeyProperty,
descriptions_1.contextWindowLengthProperty,
],
};
this.methods = {
listSearch: {
getLakebaseProjects: listSearch_1.getLakebaseProjects,
getLakebaseBranches: listSearch_1.getLakebaseBranches,
getLakebaseDatabases: listSearch_1.getLakebaseDatabases,
getLakebaseSchemas: listSearch_1.getLakebaseSchemas,
},
};
}
async supplyData(itemIndex) {
const tableUrl = await (0, helpers_1.resolveLakebaseTableUrl)(this, itemIndex);
const schema = String(this.getNodeParameter('lakebaseSchema', itemIndex, '', { extractValue: true }));
const table = String(this.getNodeParameter('lakebaseTable', itemIndex, '', { extractValue: true }));
const sessionId = (0, helpers_2.getSessionId)(this, itemIndex);
const chatHistory = new LakebaseChatMessageHistory(this, {
tableUrl,
schema,
table,
sessionId,
});
const memory = new memory_1.BufferWindowMemory({
memoryKey: 'chat_history',
chatHistory,
returnMessages: true,
inputKey: 'input',
outputKey: 'output',
k: Number(this.getNodeParameter('contextWindowLength', itemIndex)),
});
return {
response: (0, ai_utilities_1.logWrapper)(memory, this),
};
}
}
exports.MemoryLakebaseChat = MemoryLakebaseChat;
//# sourceMappingURL=MemoryLakebaseChat.node.js.map