@langchain/neo4j 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -0
  3. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  4. package/dist/chains/graph_qa/cypher.cjs +117 -0
  5. package/dist/chains/graph_qa/cypher.cjs.map +1 -0
  6. package/dist/chains/graph_qa/cypher.d.cts +73 -0
  7. package/dist/chains/graph_qa/cypher.d.cts.map +1 -0
  8. package/dist/chains/graph_qa/cypher.d.ts +73 -0
  9. package/dist/chains/graph_qa/cypher.d.ts.map +1 -0
  10. package/dist/chains/graph_qa/cypher.js +115 -0
  11. package/dist/chains/graph_qa/cypher.js.map +1 -0
  12. package/dist/chains/graph_qa/index.cjs +2 -0
  13. package/dist/chains/graph_qa/index.d.ts +2 -0
  14. package/dist/chains/graph_qa/index.js +3 -0
  15. package/dist/chains/graph_qa/prompts.cjs +42 -0
  16. package/dist/chains/graph_qa/prompts.cjs.map +1 -0
  17. package/dist/chains/graph_qa/prompts.d.cts +14 -0
  18. package/dist/chains/graph_qa/prompts.d.cts.map +1 -0
  19. package/dist/chains/graph_qa/prompts.d.ts +14 -0
  20. package/dist/chains/graph_qa/prompts.d.ts.map +1 -0
  21. package/dist/chains/graph_qa/prompts.js +40 -0
  22. package/dist/chains/graph_qa/prompts.js.map +1 -0
  23. package/dist/graphs/document.cjs +63 -0
  24. package/dist/graphs/document.cjs.map +1 -0
  25. package/dist/graphs/document.d.cts +56 -0
  26. package/dist/graphs/document.d.cts.map +1 -0
  27. package/dist/graphs/document.d.ts +56 -0
  28. package/dist/graphs/document.d.ts.map +1 -0
  29. package/dist/graphs/document.js +60 -0
  30. package/dist/graphs/document.js.map +1 -0
  31. package/dist/graphs/index.cjs +3 -0
  32. package/dist/graphs/index.d.ts +3 -0
  33. package/dist/graphs/index.js +4 -0
  34. package/dist/graphs/memgraph_graph.cjs +74 -0
  35. package/dist/graphs/memgraph_graph.cjs.map +1 -0
  36. package/dist/graphs/memgraph_graph.d.cts +36 -0
  37. package/dist/graphs/memgraph_graph.d.cts.map +1 -0
  38. package/dist/graphs/memgraph_graph.d.ts +36 -0
  39. package/dist/graphs/memgraph_graph.d.ts.map +1 -0
  40. package/dist/graphs/memgraph_graph.js +74 -0
  41. package/dist/graphs/memgraph_graph.js.map +1 -0
  42. package/dist/graphs/neo4j_graph.cjs +429 -0
  43. package/dist/graphs/neo4j_graph.cjs.map +1 -0
  44. package/dist/graphs/neo4j_graph.d.cts +96 -0
  45. package/dist/graphs/neo4j_graph.d.cts.map +1 -0
  46. package/dist/graphs/neo4j_graph.d.ts +96 -0
  47. package/dist/graphs/neo4j_graph.d.ts.map +1 -0
  48. package/dist/graphs/neo4j_graph.js +425 -0
  49. package/dist/graphs/neo4j_graph.js.map +1 -0
  50. package/dist/index.cjs +28 -0
  51. package/dist/index.d.cts +8 -0
  52. package/dist/index.d.ts +8 -0
  53. package/dist/index.js +12 -0
  54. package/dist/stores/message/index.cjs +1 -0
  55. package/dist/stores/message/index.d.ts +1 -0
  56. package/dist/stores/message/index.js +2 -0
  57. package/dist/stores/message/neo4j.cjs +114 -0
  58. package/dist/stores/message/neo4j.cjs.map +1 -0
  59. package/dist/stores/message/neo4j.d.cts +40 -0
  60. package/dist/stores/message/neo4j.d.cts.map +1 -0
  61. package/dist/stores/message/neo4j.d.ts +40 -0
  62. package/dist/stores/message/neo4j.d.ts.map +1 -0
  63. package/dist/stores/message/neo4j.js +112 -0
  64. package/dist/stores/message/neo4j.js.map +1 -0
  65. package/dist/vectorstores/index.cjs +1 -0
  66. package/dist/vectorstores/index.d.ts +1 -0
  67. package/dist/vectorstores/index.js +2 -0
  68. package/dist/vectorstores/neo4j_vector.cjs +622 -0
  69. package/dist/vectorstores/neo4j_vector.cjs.map +1 -0
  70. package/dist/vectorstores/neo4j_vector.d.cts +96 -0
  71. package/dist/vectorstores/neo4j_vector.d.cts.map +1 -0
  72. package/dist/vectorstores/neo4j_vector.d.ts +96 -0
  73. package/dist/vectorstores/neo4j_vector.d.ts.map +1 -0
  74. package/dist/vectorstores/neo4j_vector.js +616 -0
  75. package/dist/vectorstores/neo4j_vector.js.map +1 -0
  76. package/package.json +98 -0
@@ -0,0 +1,425 @@
1
+ import neo4j from "neo4j-driver";
2
+ import { sha256 } from "@langchain/core/utils/hash";
3
+ //#region src/graphs/neo4j_graph.ts
4
+ const BASE_ENTITY_LABEL = "__Entity__";
5
+ const DISTINCT_VALUE_LIMIT = 10;
6
+ const LIST_LIMIT = 128;
7
+ const EXHAUSTIVE_SEARCH_LIMIT = 1e4;
8
+ const EXCLUDED_LABELS = ["Bloom_Perspective", "Bloom_Scene"];
9
+ const EXCLUDED_RELS = ["Bloom_HAS_SCENE"];
10
+ const INCLUDE_DOCS_QUERY = `
11
+ MERGE (d:Document {id:$document.metadata.id})
12
+ SET d.text = $document.pageContent
13
+ SET d += $document.metadata
14
+ WITH d
15
+ `;
16
+ const NODE_PROPERTIES_QUERY = `
17
+ CALL apoc.meta.data()
18
+ YIELD label, other, elementType, type, property
19
+ WHERE NOT type = "RELATIONSHIP" AND elementType = "node"
20
+ AND NOT label IN $EXCLUDED_LABELS
21
+ WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
22
+ RETURN {labels: nodeLabels, properties: properties} AS output
23
+ `;
24
+ const REL_PROPERTIES_QUERY = `
25
+ CALL apoc.meta.data()
26
+ YIELD label, other, elementType, type, property
27
+ WHERE NOT type = "RELATIONSHIP" AND elementType = "relationship"
28
+ AND NOT label in $EXCLUDED_LABELS
29
+ WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
30
+ RETURN {type: nodeLabels, properties: properties} AS output
31
+ `;
32
+ const REL_QUERY = `
33
+ CALL apoc.meta.data()
34
+ YIELD label, other, elementType, type, property
35
+ WHERE type = "RELATIONSHIP" AND elementType = "node"
36
+ UNWIND other AS other_node
37
+ WITH * WHERE NOT label IN $EXCLUDED_LABELS
38
+ AND NOT other_node IN $EXCLUDED_LABELS
39
+ RETURN {start: label, type: property, end: toString(other_node)} AS output
40
+ `;
41
+ function isDistinctMoreThanLimit(distinct_count = 11, limit = DISTINCT_VALUE_LIMIT) {
42
+ return distinct_count !== void 0 && distinct_count > limit;
43
+ }
44
+ function cleanStringValues(text) {
45
+ return text.replace(/\n/g, " ").replace(/\r/g, " ");
46
+ }
47
+ function formatSchema(schema, isEnhanced) {
48
+ let formattedNodeProps = [];
49
+ let formattedRelProps = [];
50
+ if (isEnhanced) {
51
+ for (const [nodeType, properties] of Object.entries(schema.nodeProps)) {
52
+ formattedNodeProps.push(`- **${nodeType}**`);
53
+ for (const prop of properties) {
54
+ let example = "";
55
+ if (prop.type === "STRING") {
56
+ if (prop.values.length > 0) if (isDistinctMoreThanLimit(prop.distinct_count)) example = `Example: ${cleanStringValues(prop.values[0])}`;
57
+ else example = `Available options: ${prop.values.map(cleanStringValues).join(", ")}`;
58
+ } else if ([
59
+ "INTEGER",
60
+ "FLOAT",
61
+ "DATE",
62
+ "DATE_TIME",
63
+ "LOCAL_DATE_TIME"
64
+ ].includes(prop.type)) {
65
+ if (prop.min !== void 0) example = `Min: ${prop.min}, Max: ${prop.max}`;
66
+ else if (prop.values.length > 0) example = `Example: ${prop.values[0]}`;
67
+ } else if (prop.type === "LIST") {
68
+ if (!prop.min_size || prop.min_size > LIST_LIMIT) continue;
69
+ example = `Min Size: ${prop.min_size}, Max Size: ${prop.max_size}`;
70
+ }
71
+ formattedNodeProps.push(` - \`${prop.property}\`: ${prop.type} ${example}`);
72
+ }
73
+ }
74
+ for (const [relType, properties] of Object.entries(schema.relProps)) {
75
+ formattedRelProps.push(`- **${relType}**`);
76
+ for (const prop of properties) {
77
+ let example = "";
78
+ if (prop.type === "STRING") {
79
+ if (prop.values.length > 0) if (isDistinctMoreThanLimit(prop.distinct_count)) example = `Example: ${cleanStringValues(prop.values[0])}`;
80
+ else example = `Available options: ${prop.values.map(cleanStringValues).join(", ")}`;
81
+ } else if ([
82
+ "INTEGER",
83
+ "FLOAT",
84
+ "DATE",
85
+ "DATE_TIME",
86
+ "LOCAL_DATE_TIME"
87
+ ].includes(prop.type)) {
88
+ if (prop.min) example = `Min: ${prop.min}, Max: ${prop.max}`;
89
+ else if (prop.values) example = `Example: ${prop.values[0]}`;
90
+ } else if (prop.type === "LIST") {
91
+ if (prop.min_size > LIST_LIMIT) continue;
92
+ example = `Min Size: ${prop.min_size}, Max Size: ${prop.max_size}`;
93
+ }
94
+ formattedRelProps.push(` - \`${prop.property}\`: ${prop.type} ${example}`);
95
+ }
96
+ }
97
+ } else {
98
+ formattedNodeProps = Object.entries(schema.nodeProps).map(([key, value]) => {
99
+ return `${key} {${value.map((prop) => `${prop.property}: ${prop.type}`).join(", ")}}`;
100
+ });
101
+ formattedRelProps = Object.entries(schema.relProps).map(([key, value]) => {
102
+ return `${key} {${value.map((prop) => `${prop.property}: ${prop.type} `).join(", ")} } `;
103
+ });
104
+ }
105
+ const formattedRels = schema.relationships.map((el) => `(: ${el.start}) - [: ${el.type}] -> (:${el.end})`);
106
+ return [
107
+ "Node properties are the following:",
108
+ formattedNodeProps?.join(", "),
109
+ "Relationship properties are the following:",
110
+ formattedRelProps?.join(", "),
111
+ "The relationships are the following:",
112
+ formattedRels?.join(", ")
113
+ ].join("\n");
114
+ }
115
+ /**
116
+ * @security *Security note*: Make sure that the database connection uses credentials
117
+ * that are narrowly-scoped to only include necessary permissions.
118
+ * Failure to do so may result in data corruption or loss, since the calling
119
+ * code may attempt commands that would result in deletion, mutation
120
+ * of data if appropriately prompted or reading sensitive data if such
121
+ * data is present in the database.
122
+ * The best way to guard against such negative outcomes is to (as appropriate)
123
+ * limit the permissions granted to the credentials used with this tool.
124
+ * For example, creating read only users for the database is a good way to
125
+ * ensure that the calling code cannot mutate or delete data.
126
+ *
127
+ * @link See https://js.langchain.com/docs/security for more information.
128
+ */
129
+ var Neo4jGraph = class Neo4jGraph {
130
+ driver;
131
+ database;
132
+ timeoutMs;
133
+ enhancedSchema;
134
+ schema = "";
135
+ structuredSchema = {
136
+ nodeProps: {},
137
+ relProps: {},
138
+ relationships: [],
139
+ metadata: {
140
+ constraint: {},
141
+ index: {}
142
+ }
143
+ };
144
+ constructor({ url, username, password, database = "neo4j", timeoutMs, enhancedSchema = false }) {
145
+ try {
146
+ this.driver = neo4j.driver(url, neo4j.auth.basic(username, password));
147
+ this.database = database;
148
+ this.timeoutMs = timeoutMs;
149
+ this.enhancedSchema = enhancedSchema;
150
+ } catch {
151
+ throw new Error("Could not create a Neo4j driver instance. Please check the connection details.");
152
+ }
153
+ }
154
+ static async initialize(config) {
155
+ const graph = new Neo4jGraph(config);
156
+ await graph.verifyConnectivity();
157
+ try {
158
+ await graph.refreshSchema();
159
+ } catch (error) {
160
+ if (error.code === "Neo.ClientError.Procedure.ProcedureNotFound") throw new Error("Could not use APOC procedures. Please ensure the APOC plugin is installed in Neo4j and that 'apoc.meta.data()' is allowed in Neo4j configuration.");
161
+ throw error;
162
+ } finally {
163
+ console.log("Schema refreshed successfully.");
164
+ }
165
+ return graph;
166
+ }
167
+ getSchema() {
168
+ return this.schema;
169
+ }
170
+ getStructuredSchema() {
171
+ return this.structuredSchema;
172
+ }
173
+ async query(query, params = {}, routing = neo4j.routing.WRITE) {
174
+ return toObjects((await this.driver.executeQuery(query, params, {
175
+ database: this.database,
176
+ routing,
177
+ transactionConfig: { timeout: this.timeoutMs }
178
+ })).records);
179
+ }
180
+ async verifyConnectivity() {
181
+ await this.driver.getServerInfo();
182
+ }
183
+ async refreshSchema() {
184
+ const nodeProperties = (await this.query(NODE_PROPERTIES_QUERY, { EXCLUDED_LABELS: EXCLUDED_LABELS.concat([BASE_ENTITY_LABEL]) }))?.map((el) => el.output);
185
+ const relationshipsProperties = (await this.query(REL_PROPERTIES_QUERY, { EXCLUDED_LABELS: EXCLUDED_RELS }))?.map((el) => el.output);
186
+ const relationships = (await this.query(REL_QUERY, { EXCLUDED_LABELS: EXCLUDED_LABELS.concat([BASE_ENTITY_LABEL]) }))?.map((el) => el.output);
187
+ const constraint = await this.query("SHOW CONSTRAINTS");
188
+ const index = await this.query("SHOW INDEXES YIELD *");
189
+ this.structuredSchema = {
190
+ nodeProps: Object.fromEntries(nodeProperties?.map((el) => [el.labels, el.properties]) || []),
191
+ relProps: Object.fromEntries(relationshipsProperties?.map((el) => [el.type, el.properties]) || []),
192
+ relationships: relationships || [],
193
+ metadata: {
194
+ constraint,
195
+ index
196
+ }
197
+ };
198
+ if (this.enhancedSchema) {
199
+ const schemaCounts = await this.query("CALL apoc.meta.graphSample() YIELD nodes, relationships RETURN nodes, [rel in relationships | {name: apoc.any.property(rel, 'type'), count: apoc.any.property(rel, 'count')}] AS relationships");
200
+ for (const node of schemaCounts[0].nodes) {
201
+ if (EXCLUDED_LABELS.includes(node.name)) continue;
202
+ const nodeProps = this.structuredSchema.nodeProps[node.name];
203
+ if (!nodeProps) continue;
204
+ const enhancedCypher = await this.enhancedSchemaCypher(node.name, nodeProps, node.count < EXHAUSTIVE_SEARCH_LIMIT);
205
+ const enhancedInfo = (await this.query(enhancedCypher))[0].output;
206
+ for (const prop of nodeProps) if (enhancedInfo[prop.property]) Object.assign(prop, enhancedInfo[prop.property]);
207
+ }
208
+ for (const rel of schemaCounts[0].relationships) {
209
+ if (EXCLUDED_RELS.includes(rel.name)) continue;
210
+ const relProps = this.structuredSchema.relProps[rel.name];
211
+ if (!relProps) continue;
212
+ const enhancedCypher = await this.enhancedSchemaCypher(rel.name, relProps, rel.count < EXHAUSTIVE_SEARCH_LIMIT, true);
213
+ const enhancedInfo = (await this.query(enhancedCypher))[0].output;
214
+ for (const prop of relProps) if (prop.property in enhancedInfo) Object.assign(prop, enhancedInfo[prop.property]);
215
+ }
216
+ }
217
+ this.schema = formatSchema(this.structuredSchema, this.enhancedSchema);
218
+ }
219
+ async enhancedSchemaCypher(labelOrType, properties, exhaustive, isRelationship = false) {
220
+ let matchClause = isRelationship ? `MATCH ()-[n:\`${labelOrType}\`]->()` : `MATCH (n:\`${labelOrType}\`)`;
221
+ const withClauses = [];
222
+ const returnClauses = [];
223
+ const outputDict = {};
224
+ if (exhaustive) for (const prop of properties) {
225
+ const propName = prop.property;
226
+ const propType = prop.type;
227
+ if (propType === "STRING") {
228
+ withClauses.push(`collect(distinct substring(n.\`${propName}\`, 0, 50)) AS \`${propName}_values\``);
229
+ returnClauses.push(`values: \`${propName}_values\`[..${DISTINCT_VALUE_LIMIT}], distinct_count: size(\`${propName}_values\`)`);
230
+ } else if ([
231
+ "INTEGER",
232
+ "FLOAT",
233
+ "DATE",
234
+ "DATE_TIME",
235
+ "LOCAL_DATE_TIME"
236
+ ].includes(propType)) {
237
+ withClauses.push(`min(n.\`${propName}\`) AS \`${propName}_min\``);
238
+ withClauses.push(`max(n.\`${propName}\`) AS \`${propName}_max\``);
239
+ withClauses.push(`count(distinct n.\`${propName}\`) AS \`${propName}_distinct\``);
240
+ returnClauses.push(`min: toString(\`${propName}_min\`), max: toString(\`${propName}_max\`), distinct_count: \`${propName}_distinct\``);
241
+ } else if (propType === "LIST") {
242
+ withClauses.push(`min(size(n.\`${propName}\`)) AS \`${propName}_size_min\`, max(size(n.\`${propName}\`)) AS \`${propName}_size_max\``);
243
+ returnClauses.push(`min_size: \`${propName}_size_min\`, max_size: \`${propName}_size_max\``);
244
+ } else if ([
245
+ "BOOLEAN",
246
+ "POINT",
247
+ "DURATION"
248
+ ].includes(propType)) continue;
249
+ outputDict[propName] = `{${returnClauses.pop()}}`;
250
+ }
251
+ else {
252
+ matchClause += ` WITH n LIMIT 5`;
253
+ for (const prop of properties) {
254
+ const propName = prop.property;
255
+ const propType = prop.type;
256
+ const propIndex = this.structuredSchema?.metadata?.index.filter((el) => el.label === labelOrType && el.properties[0] === propName && el.type === "RANGE");
257
+ if (propType === "STRING") if (propIndex.length > 0 && propIndex[0].size > 0 && propIndex[0].distinctValues <= DISTINCT_VALUE_LIMIT) {
258
+ const distinctValues = (await this.query(`CALL apoc.schema.properties.distinct('${labelOrType}', '${propName}') YIELD value`))[0].value;
259
+ returnClauses.push(`values: ${distinctValues}, distinct_count: ${distinctValues.length}`);
260
+ } else {
261
+ withClauses.push(`collect(distinct substring(n.\`${propName}\`, 0, 50)) AS \`${propName}_values\``);
262
+ returnClauses.push(`values: ${propName}_values`);
263
+ }
264
+ else if ([
265
+ "INTEGER",
266
+ "FLOAT",
267
+ "DATE",
268
+ "DATE_TIME",
269
+ "LOCAL_DATE_TIME"
270
+ ].includes(propType)) if (!propIndex) {
271
+ withClauses.push(`collect(distinct toString(n.\`${propName}\`)) AS \`${propName}_values\``);
272
+ returnClauses.push(`values: ${propName}_values`);
273
+ } else {
274
+ withClauses.push(`min(n.\`${propName}\`) AS \`${propName}_min\``);
275
+ withClauses.push(`max(n.\`${propName}\`) AS \`${propName}_max\``);
276
+ withClauses.push(`count(distinct n.\`${propName}\`) AS \`${propName}_distinct\``);
277
+ returnClauses.push(`min: toString(\`${propName}_min\`), max: toString(\`${propName}_max\`), distinct_count: \`${propName}_distinct\``);
278
+ }
279
+ else if (propType === "LIST") {
280
+ withClauses.push(`min(size(n.\`${propName}\`)) AS \`${propName}_size_min\`, max(size(n.\`${propName}\`)) AS \`${propName}_size_max\``);
281
+ returnClauses.push(`min_size: \`${propName}_size_min\`, max_size: \`${propName}_size_max\``);
282
+ } else if ([
283
+ "BOOLEAN",
284
+ "POINT",
285
+ "DURATION"
286
+ ].includes(propType)) continue;
287
+ outputDict[propName] = `{${returnClauses.pop()}}`;
288
+ }
289
+ }
290
+ const withClause = `WITH ${withClauses.join(", ")}`;
291
+ const returnClause = `RETURN {${Object.entries(outputDict).map(([k, v]) => `\`${k}\`: ${v}`).join(", ")}} AS output`;
292
+ return [
293
+ matchClause,
294
+ withClause,
295
+ returnClause
296
+ ].join("\n");
297
+ }
298
+ async addGraphDocuments(graphDocuments, config = {}) {
299
+ const { baseEntityLabel } = config;
300
+ if (baseEntityLabel) {
301
+ if (!(this.structuredSchema?.metadata?.constraint?.some((el) => JSON.stringify(el.labelsOrTypes) === JSON.stringify(["__Entity__"]) && JSON.stringify(el.properties) === JSON.stringify(["id"])) ?? false)) {
302
+ await this.query(`
303
+ CREATE CONSTRAINT IF NOT EXISTS FOR (b:${BASE_ENTITY_LABEL})
304
+ REQUIRE b.id IS UNIQUE;
305
+ `);
306
+ await this.refreshSchema();
307
+ }
308
+ }
309
+ const nodeImportQuery = getNodeImportQuery(config);
310
+ const relImportQuery = getRelImportQuery(config);
311
+ for (const document of graphDocuments) {
312
+ if (!document.source.metadata.id) document.source.metadata.id = sha256(document.source.pageContent);
313
+ await this.query(nodeImportQuery, {
314
+ data: document.nodes.map((el) => ({ ...el })),
315
+ document: { ...document.source }
316
+ });
317
+ await this.query(relImportQuery, { data: document.relationships.map((el) => ({
318
+ source: el.source.id,
319
+ source_label: el.source.type,
320
+ target: el.target.id,
321
+ target_label: el.target.type,
322
+ type: el.type.replace(/ /g, "_").toUpperCase(),
323
+ properties: el.properties
324
+ })) });
325
+ }
326
+ }
327
+ async close() {
328
+ await this.driver.close();
329
+ }
330
+ };
331
+ function getNodeImportQuery({ baseEntityLabel, includeSource }) {
332
+ if (baseEntityLabel) return `
333
+ ${includeSource ? INCLUDE_DOCS_QUERY : ""}
334
+ UNWIND $data AS row
335
+ MERGE(source: \`${BASE_ENTITY_LABEL}\` {id: row.id})
336
+ SET source += row.properties
337
+ ${includeSource ? "MERGE (d)-[:MENTIONS]->(source)" : ""}
338
+ WITH source, row
339
+ CALL apoc.create.addLabels(source, [row.type]) YIELD node
340
+ RETURN distinct 'done' AS result
341
+ `;
342
+ else return `
343
+ ${includeSource ? INCLUDE_DOCS_QUERY : ""}
344
+ UNWIND $data AS row
345
+ CALL apoc.merge.node([row.type], {id: row.id},
346
+ row.properties, {}) YIELD node
347
+ ${includeSource ? "MERGE (d)-[:MENTIONS]->(node)" : ""}
348
+ RETURN distinct 'done' AS result
349
+ `;
350
+ }
351
+ function getRelImportQuery({ baseEntityLabel }) {
352
+ if (baseEntityLabel) return `
353
+ UNWIND $data AS row
354
+ MERGE (source:\`${BASE_ENTITY_LABEL}\` {id: row.source})
355
+ MERGE (target:\`${BASE_ENTITY_LABEL}\` {id: row.target})
356
+ WITH source, target, row
357
+ CALL apoc.merge.relationship(source, row.type,
358
+ {}, row.properties, target) YIELD rel
359
+ RETURN distinct 'done'
360
+ `;
361
+ else return `
362
+ UNWIND $data AS row
363
+ CALL apoc.merge.node([row.source_label], {id: row.source},
364
+ {}, {}) YIELD node as source
365
+ CALL apoc.merge.node([row.target_label], {id: row.target},
366
+ {}, {}) YIELD node as target
367
+ CALL apoc.merge.relationship(source, row.type,
368
+ {}, row.properties, target) YIELD rel
369
+ RETURN distinct 'done'
370
+ `;
371
+ }
372
+ function toObjects(records) {
373
+ return records.map((record) => {
374
+ const rObj = record.toObject();
375
+ const out = {};
376
+ Object.keys(rObj).forEach((key) => {
377
+ out[key] = itemIntToString(rObj[key]);
378
+ });
379
+ return out;
380
+ });
381
+ }
382
+ function itemIntToString(item) {
383
+ if (neo4j.isInt(item)) return item.toString();
384
+ if (Array.isArray(item)) return item.map((ii) => itemIntToString(ii));
385
+ if ([
386
+ "number",
387
+ "string",
388
+ "boolean"
389
+ ].indexOf(typeof item) !== -1) return item;
390
+ if (item === null) return item;
391
+ if (typeof item === "object") return objIntToString(item);
392
+ }
393
+ function objIntToString(obj) {
394
+ const entry = extractFromNeoObjects(obj);
395
+ let newObj = null;
396
+ if (Array.isArray(entry)) newObj = entry.map((item) => itemIntToString(item));
397
+ else if (entry !== null && typeof entry === "object") {
398
+ newObj = {};
399
+ Object.keys(entry).forEach((key) => {
400
+ newObj[key] = itemIntToString(entry[key]);
401
+ });
402
+ }
403
+ return newObj;
404
+ }
405
+ function extractFromNeoObjects(obj) {
406
+ if (obj instanceof neo4j.types.Node || obj instanceof neo4j.types.Relationship) return obj.properties;
407
+ else if (obj instanceof neo4j.types.Path) return [].concat.apply([], extractPathForRows(obj));
408
+ return obj;
409
+ }
410
+ const extractPathForRows = (path) => {
411
+ let { segments } = path;
412
+ if (!Array.isArray(path.segments) || path.segments.length < 1) segments = [{
413
+ ...path,
414
+ end: null
415
+ }];
416
+ return segments.map((segment) => [
417
+ objIntToString(segment.start),
418
+ objIntToString(segment.relationship),
419
+ objIntToString(segment.end)
420
+ ].filter((part) => part !== null));
421
+ };
422
+ //#endregion
423
+ export { BASE_ENTITY_LABEL, Neo4jGraph, formatSchema };
424
+
425
+ //# sourceMappingURL=neo4j_graph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"neo4j_graph.js","names":[],"sources":["../../src/graphs/neo4j_graph.ts"],"sourcesContent":["import neo4j, {\n RoutingControl,\n type Driver as Neo4jDriver,\n type Record as Neo4jRecord,\n type Path as Neo4jPath,\n} from \"neo4j-driver\";\nimport { sha256 } from \"@langchain/core/utils/hash\";\nimport { GraphDocument } from \"./document.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Any = any;\n\nexport interface Neo4jGraphConfig {\n url: string;\n username: string;\n password: string;\n database?: string;\n timeoutMs?: number;\n enhancedSchema?: boolean;\n}\n\nexport interface StructuredSchema {\n nodeProps: { [key: NodeType[\"labels\"]]: NodeType[\"properties\"] };\n relProps: { [key: RelType[\"type\"]]: RelType[\"properties\"] };\n relationships: PathType[];\n metadata?: {\n constraint: Record<string, Any>;\n index: Record<string, Any>;\n };\n}\n\nexport interface AddGraphDocumentsConfig {\n baseEntityLabel?: boolean;\n includeSource?: boolean;\n}\n\nexport type NodeType = {\n labels: string;\n properties: { property: string; type: string }[];\n};\n\nexport type RelType = {\n type: string;\n properties: { property: string; type: string }[];\n};\n\nexport type PathType = { start: string; type: string; end: string };\n\nexport const BASE_ENTITY_LABEL = \"__Entity__\";\n\nconst DISTINCT_VALUE_LIMIT = 10;\nconst LIST_LIMIT = 128;\nconst EXHAUSTIVE_SEARCH_LIMIT = 10000;\nconst EXCLUDED_LABELS = [\"Bloom_Perspective\", \"Bloom_Scene\"];\nconst EXCLUDED_RELS = [\"Bloom_HAS_SCENE\"];\n\nconst INCLUDE_DOCS_QUERY = `\nMERGE (d:Document {id:$document.metadata.id})\nSET d.text = $document.pageContent\nSET d += $document.metadata\nWITH d\n`;\n\nconst NODE_PROPERTIES_QUERY = `\nCALL apoc.meta.data()\nYIELD label, other, elementType, type, property\nWHERE NOT type = \"RELATIONSHIP\" AND elementType = \"node\"\n AND NOT label IN $EXCLUDED_LABELS\nWITH label AS nodeLabels, collect({property:property, type:type}) AS properties\nRETURN {labels: nodeLabels, properties: properties} AS output\n`;\n\nconst REL_PROPERTIES_QUERY = `\nCALL apoc.meta.data()\nYIELD label, other, elementType, type, property\nWHERE NOT type = \"RELATIONSHIP\" AND elementType = \"relationship\"\n AND NOT label in $EXCLUDED_LABELS\nWITH label AS nodeLabels, collect({property:property, type:type}) AS properties\nRETURN {type: nodeLabels, properties: properties} AS output\n`;\n\nconst REL_QUERY = `\nCALL apoc.meta.data()\nYIELD label, other, elementType, type, property\nWHERE type = \"RELATIONSHIP\" AND elementType = \"node\"\nUNWIND other AS other_node\nWITH * WHERE NOT label IN $EXCLUDED_LABELS\n AND NOT other_node IN $EXCLUDED_LABELS\nRETURN {start: label, type: property, end: toString(other_node)} AS output\n`;\n\nfunction isDistinctMoreThanLimit(\n distinct_count = 11,\n limit = DISTINCT_VALUE_LIMIT\n): boolean {\n return distinct_count !== undefined && distinct_count > limit;\n}\n\nfunction cleanStringValues(text: string) {\n return text.replace(/\\n/g, \" \").replace(/\\r/g, \" \");\n}\n\nexport function formatSchema(\n schema: Record<string, Any>,\n isEnhanced: boolean\n): string {\n let formattedNodeProps: string[] = [];\n let formattedRelProps: string[] = [];\n\n if (isEnhanced) {\n for (const [nodeType, properties] of Object.entries(schema.nodeProps)) {\n formattedNodeProps.push(`- **${nodeType}**`);\n\n for (const prop of properties as Array<Record<string, Any>>) {\n let example = \"\";\n\n if (prop.type === \"STRING\") {\n if (prop.values.length > 0) {\n if (isDistinctMoreThanLimit(prop.distinct_count)) {\n example = `Example: ${cleanStringValues(prop.values[0])}`;\n } else {\n example = `Available options: ${prop.values\n .map(cleanStringValues)\n .join(\", \")}`;\n }\n }\n } else if (\n [\"INTEGER\", \"FLOAT\", \"DATE\", \"DATE_TIME\", \"LOCAL_DATE_TIME\"].includes(\n prop.type\n )\n ) {\n if (prop.min !== undefined) {\n example = `Min: ${prop.min}, Max: ${prop.max}`;\n } else {\n if (prop.values.length > 0) {\n example = `Example: ${prop.values[0]}`;\n }\n }\n } else if (prop.type === \"LIST\") {\n if (!prop.min_size || prop.min_size > LIST_LIMIT) {\n continue;\n }\n example = `Min Size: ${prop.min_size}, Max Size: ${prop.max_size}`;\n }\n\n formattedNodeProps.push(\n ` - \\`${prop.property}\\`: ${prop.type} ${example}`\n );\n }\n }\n\n for (const [relType, properties] of Object.entries(schema.relProps)) {\n formattedRelProps.push(`- **${relType}**`);\n\n for (const prop of properties as Array<Record<string, Any>>) {\n let example = \"\";\n\n if (prop.type === \"STRING\") {\n if (prop.values.length > 0) {\n if (isDistinctMoreThanLimit(prop.distinct_count)) {\n example = `Example: ${cleanStringValues(prop.values[0])}`;\n } else {\n example = `Available options: ${prop.values\n .map(cleanStringValues)\n .join(\", \")}`;\n }\n }\n } else if (\n [\"INTEGER\", \"FLOAT\", \"DATE\", \"DATE_TIME\", \"LOCAL_DATE_TIME\"].includes(\n prop.type\n )\n ) {\n if (prop.min) {\n example = `Min: ${prop.min}, Max: ${prop.max}`;\n } else {\n if (prop.values) {\n example = `Example: ${prop.values[0]}`;\n }\n }\n } else if (prop.type === \"LIST\") {\n if (prop.min_size > LIST_LIMIT) {\n continue;\n }\n example = `Min Size: ${prop.min_size}, Max Size: ${prop.max_size}`;\n }\n\n formattedRelProps.push(\n ` - \\`${prop.property}\\`: ${prop.type} ${example}`\n );\n }\n }\n } else {\n formattedNodeProps = Object.entries(schema.nodeProps).map(\n ([key, value]: [string, Any]) => {\n const propsStr = value\n .map((prop: Record<string, Any>) => `${prop.property}: ${prop.type}`)\n .join(\", \");\n return `${key} {${propsStr}}`;\n }\n );\n\n formattedRelProps = Object.entries(schema.relProps).map(\n ([key, value]: [string, Any]) => {\n const propsStr = value\n .map((prop: Record<string, Any>) => `${prop.property}: ${prop.type} `)\n .join(\", \");\n return `${key} {${propsStr} } `;\n }\n );\n }\n\n const formattedRels = schema.relationships.map(\n (el: Record<string, string>) =>\n `(: ${el.start}) - [: ${el.type}] -> (:${el.end})`\n );\n\n return [\n \"Node properties are the following:\",\n formattedNodeProps?.join(\", \"),\n \"Relationship properties are the following:\",\n formattedRelProps?.join(\", \"),\n \"The relationships are the following:\",\n formattedRels?.join(\", \"),\n ].join(\"\\n\");\n}\n\n/**\n * @security *Security note*: Make sure that the database connection uses credentials\n * that are narrowly-scoped to only include necessary permissions.\n * Failure to do so may result in data corruption or loss, since the calling\n * code may attempt commands that would result in deletion, mutation\n * of data if appropriately prompted or reading sensitive data if such\n * data is present in the database.\n * The best way to guard against such negative outcomes is to (as appropriate)\n * limit the permissions granted to the credentials used with this tool.\n * For example, creating read only users for the database is a good way to\n * ensure that the calling code cannot mutate or delete data.\n *\n * @link See https://js.langchain.com/docs/security for more information.\n */\nexport class Neo4jGraph {\n private driver: Neo4jDriver;\n\n private database: string;\n\n private timeoutMs: number | undefined;\n\n private enhancedSchema: boolean;\n\n protected schema = \"\";\n\n protected structuredSchema: StructuredSchema = {\n nodeProps: {},\n relProps: {},\n relationships: [],\n metadata: {\n constraint: {},\n index: {},\n },\n };\n\n constructor({\n url,\n username,\n password,\n database = \"neo4j\",\n timeoutMs,\n enhancedSchema = false,\n }: Neo4jGraphConfig) {\n try {\n this.driver = neo4j.driver(url, neo4j.auth.basic(username, password));\n this.database = database;\n this.timeoutMs = timeoutMs;\n this.enhancedSchema = enhancedSchema;\n } catch {\n throw new Error(\n \"Could not create a Neo4j driver instance. Please check the connection details.\"\n );\n }\n }\n\n static async initialize(config: Neo4jGraphConfig): Promise<Neo4jGraph> {\n const graph = new Neo4jGraph(config);\n\n await graph.verifyConnectivity();\n\n try {\n await graph.refreshSchema();\n } catch (error: Any) {\n if (error.code === \"Neo.ClientError.Procedure.ProcedureNotFound\") {\n throw new Error(\n \"Could not use APOC procedures. Please ensure the APOC plugin is installed in Neo4j and that 'apoc.meta.data()' is allowed in Neo4j configuration.\"\n );\n }\n\n throw error;\n } finally {\n console.log(\"Schema refreshed successfully.\");\n }\n\n return graph;\n }\n\n getSchema(): string {\n return this.schema;\n }\n\n getStructuredSchema() {\n return this.structuredSchema;\n }\n\n async query<RecordShape extends Record<string, Any> = Record<string, Any>>(\n query: string,\n params: Record<string, Any> = {},\n routing: RoutingControl = neo4j.routing.WRITE\n ): Promise<RecordShape[]> {\n const result = await this.driver.executeQuery<RecordShape>(query, params, {\n database: this.database,\n routing,\n transactionConfig: { timeout: this.timeoutMs },\n });\n return toObjects<RecordShape>(result.records);\n }\n\n async verifyConnectivity() {\n await this.driver.getServerInfo();\n }\n\n async refreshSchema() {\n const nodeProperties = (\n await this.query<{ output: NodeType }>(NODE_PROPERTIES_QUERY, {\n EXCLUDED_LABELS: EXCLUDED_LABELS.concat([BASE_ENTITY_LABEL]),\n })\n )?.map((el) => el.output);\n\n const relationshipsProperties = (\n await this.query<{ output: RelType }>(REL_PROPERTIES_QUERY, {\n EXCLUDED_LABELS: EXCLUDED_RELS,\n })\n )?.map((el) => el.output);\n\n const relationships: PathType[] = (\n await this.query<{ output: PathType }>(REL_QUERY, {\n EXCLUDED_LABELS: EXCLUDED_LABELS.concat([BASE_ENTITY_LABEL]),\n })\n )?.map((el) => el.output);\n\n const constraint = await this.query(\"SHOW CONSTRAINTS\");\n\n const index = await this.query(\"SHOW INDEXES YIELD *\");\n\n this.structuredSchema = {\n nodeProps: Object.fromEntries(\n nodeProperties?.map((el) => [el.labels, el.properties]) || []\n ),\n relProps: Object.fromEntries(\n relationshipsProperties?.map((el) => [el.type, el.properties]) || []\n ),\n relationships: relationships || [],\n metadata: {\n constraint,\n index,\n },\n };\n\n if (this.enhancedSchema) {\n const schemaCounts = await this.query(\n `CALL apoc.meta.graphSample() YIELD nodes, relationships ` +\n `RETURN nodes, [rel in relationships | {name: apoc.any.property(rel, 'type'), count: apoc.any.property(rel, 'count')}] AS relationships`\n );\n for (const node of schemaCounts[0].nodes) {\n if (EXCLUDED_LABELS.includes(node.name)) {\n continue;\n }\n\n const nodeProps = this.structuredSchema.nodeProps[node.name];\n\n if (!nodeProps) {\n continue;\n }\n\n const enhancedCypher = await this.enhancedSchemaCypher(\n node.name,\n nodeProps,\n node.count < EXHAUSTIVE_SEARCH_LIMIT\n );\n const enhancedInfoPromise = await this.query(enhancedCypher);\n const enhancedInfo = enhancedInfoPromise[0].output;\n\n for (const prop of nodeProps) {\n if (enhancedInfo[prop.property]) {\n Object.assign(prop, enhancedInfo[prop.property]);\n }\n }\n }\n\n for (const rel of schemaCounts[0].relationships) {\n if (EXCLUDED_RELS.includes(rel.name)) {\n continue;\n }\n const relProps = this.structuredSchema.relProps[rel.name];\n\n if (!relProps) {\n continue;\n }\n const enhancedCypher = await this.enhancedSchemaCypher(\n rel.name,\n relProps,\n rel.count < EXHAUSTIVE_SEARCH_LIMIT,\n true\n );\n\n const enhancedInfoPromise = await this.query(enhancedCypher);\n const enhancedInfo = enhancedInfoPromise[0].output;\n\n for (const prop of relProps) {\n if (prop.property in enhancedInfo) {\n Object.assign(prop, enhancedInfo[prop.property]);\n }\n }\n }\n }\n\n this.schema = formatSchema(this.structuredSchema, this.enhancedSchema);\n }\n\n async enhancedSchemaCypher(\n labelOrType: string,\n properties: { property: string; type: string }[],\n exhaustive: boolean,\n isRelationship = false\n ) {\n let matchClause = isRelationship\n ? `MATCH ()-[n:\\`${labelOrType}\\`]->()`\n : `MATCH (n:\\`${labelOrType}\\`)`;\n\n const withClauses: string[] = [];\n const returnClauses: string[] = [];\n const outputDict: { [key: string]: string } = {};\n\n if (exhaustive) {\n for (const prop of properties) {\n const propName = prop.property;\n const propType = prop.type;\n\n if (propType === \"STRING\") {\n withClauses.push(\n `collect(distinct substring(n.\\`${propName}\\`, 0, 50)) AS \\`${propName}_values\\``\n );\n returnClauses.push(\n `values: \\`${propName}_values\\`[..${DISTINCT_VALUE_LIMIT}], distinct_count: size(\\`${propName}_values\\`)`\n );\n } else if (\n [\"INTEGER\", \"FLOAT\", \"DATE\", \"DATE_TIME\", \"LOCAL_DATE_TIME\"].includes(\n propType\n )\n ) {\n withClauses.push(`min(n.\\`${propName}\\`) AS \\`${propName}_min\\``);\n withClauses.push(`max(n.\\`${propName}\\`) AS \\`${propName}_max\\``);\n withClauses.push(\n `count(distinct n.\\`${propName}\\`) AS \\`${propName}_distinct\\``\n );\n returnClauses.push(\n `min: toString(\\`${propName}_min\\`), max: toString(\\`${propName}_max\\`), distinct_count: \\`${propName}_distinct\\``\n );\n } else if (propType === \"LIST\") {\n withClauses.push(\n `min(size(n.\\`${propName}\\`)) AS \\`${propName}_size_min\\`, max(size(n.\\`${propName}\\`)) AS \\`${propName}_size_max\\``\n );\n returnClauses.push(\n `min_size: \\`${propName}_size_min\\`, max_size: \\`${propName}_size_max\\``\n );\n } else if ([\"BOOLEAN\", \"POINT\", \"DURATION\"].includes(propType)) {\n continue;\n }\n outputDict[propName] = `{${returnClauses.pop()}}`;\n }\n } else {\n matchClause += ` WITH n LIMIT 5`;\n\n for (const prop of properties) {\n const propName = prop.property;\n const propType = prop.type;\n\n const propIndex = this.structuredSchema?.metadata?.index.filter(\n (el: Any) =>\n el.label === labelOrType &&\n el.properties[0] === propName &&\n el.type === \"RANGE\"\n );\n\n if (propType === \"STRING\") {\n if (\n propIndex.length > 0 &&\n propIndex[0].size > 0 &&\n propIndex[0].distinctValues <= DISTINCT_VALUE_LIMIT\n ) {\n const distinctValuesPromise = await this.query(\n `CALL apoc.schema.properties.distinct('${labelOrType}', '${propName}') YIELD value`\n );\n const distinctValues = distinctValuesPromise[0].value;\n returnClauses.push(\n `values: ${distinctValues}, distinct_count: ${distinctValues.length}`\n );\n } else {\n withClauses.push(\n `collect(distinct substring(n.\\`${propName}\\`, 0, 50)) AS \\`${propName}_values\\``\n );\n returnClauses.push(`values: ${propName}_values`);\n }\n } else if (\n [\"INTEGER\", \"FLOAT\", \"DATE\", \"DATE_TIME\", \"LOCAL_DATE_TIME\"].includes(\n propType\n )\n ) {\n if (!propIndex) {\n withClauses.push(\n `collect(distinct toString(n.\\`${propName}\\`)) AS \\`${propName}_values\\``\n );\n returnClauses.push(`values: ${propName}_values`);\n } else {\n withClauses.push(`min(n.\\`${propName}\\`) AS \\`${propName}_min\\``);\n withClauses.push(`max(n.\\`${propName}\\`) AS \\`${propName}_max\\``);\n withClauses.push(\n `count(distinct n.\\`${propName}\\`) AS \\`${propName}_distinct\\``\n );\n returnClauses.push(\n `min: toString(\\`${propName}_min\\`), max: toString(\\`${propName}_max\\`), distinct_count: \\`${propName}_distinct\\``\n );\n }\n } else if (propType === \"LIST\") {\n withClauses.push(\n `min(size(n.\\`${propName}\\`)) AS \\`${propName}_size_min\\`, max(size(n.\\`${propName}\\`)) AS \\`${propName}_size_max\\``\n );\n returnClauses.push(\n `min_size: \\`${propName}_size_min\\`, max_size: \\`${propName}_size_max\\``\n );\n } else if ([\"BOOLEAN\", \"POINT\", \"DURATION\"].includes(propType)) {\n continue;\n }\n\n outputDict[propName] = `{${returnClauses.pop()}}`;\n }\n }\n\n const withClause = `WITH ${withClauses.join(\", \")}`;\n const returnClause = `RETURN {${Object.entries(outputDict)\n .map(([k, v]) => `\\`${k}\\`: ${v}`)\n .join(\", \")}} AS output`;\n\n const cypherQuery = [matchClause, withClause, returnClause].join(\"\\n\");\n\n return cypherQuery;\n }\n\n async addGraphDocuments(\n graphDocuments: GraphDocument[],\n config: AddGraphDocumentsConfig = {}\n ): Promise<void> {\n const { baseEntityLabel } = config;\n\n if (baseEntityLabel) {\n const constraintExists =\n this.structuredSchema?.metadata?.constraint?.some(\n (el: Any) =>\n JSON.stringify(el.labelsOrTypes) ===\n JSON.stringify([BASE_ENTITY_LABEL]) &&\n JSON.stringify(el.properties) === JSON.stringify([\"id\"])\n ) ?? false;\n\n if (!constraintExists) {\n await this.query(`\n CREATE CONSTRAINT IF NOT EXISTS FOR (b:${BASE_ENTITY_LABEL})\n REQUIRE b.id IS UNIQUE;\n `);\n await this.refreshSchema();\n }\n }\n\n const nodeImportQuery = getNodeImportQuery(config);\n const relImportQuery = getRelImportQuery(config);\n\n for (const document of graphDocuments) {\n if (!document.source.metadata.id) {\n document.source.metadata.id = sha256(document.source.pageContent);\n }\n\n await this.query(nodeImportQuery, {\n data: document.nodes.map((el: Any) => ({ ...el })),\n document: { ...document.source },\n });\n\n await this.query(relImportQuery, {\n data: document.relationships.map((el: Any) => ({\n source: el.source.id,\n source_label: el.source.type,\n target: el.target.id,\n target_label: el.target.type,\n type: el.type.replace(/ /g, \"_\").toUpperCase(),\n properties: el.properties,\n })),\n });\n }\n }\n\n async close() {\n await this.driver.close();\n }\n}\n\nfunction getNodeImportQuery({\n baseEntityLabel,\n includeSource,\n}: AddGraphDocumentsConfig): string {\n if (baseEntityLabel) {\n return `\n ${includeSource ? INCLUDE_DOCS_QUERY : \"\"}\n UNWIND $data AS row\n MERGE(source: \\`${BASE_ENTITY_LABEL}\\` {id: row.id})\n SET source += row.properties\n ${includeSource ? \"MERGE (d)-[:MENTIONS]->(source)\" : \"\"}\n WITH source, row\n CALL apoc.create.addLabels(source, [row.type]) YIELD node\n RETURN distinct 'done' AS result\n `;\n } else {\n return `\n ${includeSource ? INCLUDE_DOCS_QUERY : \"\"}\n UNWIND $data AS row\n CALL apoc.merge.node([row.type], {id: row.id},\n row.properties, {}) YIELD node\n ${includeSource ? \"MERGE (d)-[:MENTIONS]->(node)\" : \"\"}\n RETURN distinct 'done' AS result\n `;\n }\n}\n\nfunction getRelImportQuery({\n baseEntityLabel,\n}: AddGraphDocumentsConfig): string {\n if (baseEntityLabel) {\n return `\n UNWIND $data AS row\n MERGE (source:\\`${BASE_ENTITY_LABEL}\\` {id: row.source})\n MERGE (target:\\`${BASE_ENTITY_LABEL}\\` {id: row.target})\n WITH source, target, row\n CALL apoc.merge.relationship(source, row.type,\n {}, row.properties, target) YIELD rel\n RETURN distinct 'done'\n `;\n } else {\n return `\n UNWIND $data AS row\n CALL apoc.merge.node([row.source_label], {id: row.source},\n {}, {}) YIELD node as source\n CALL apoc.merge.node([row.target_label], {id: row.target},\n {}, {}) YIELD node as target\n CALL apoc.merge.relationship(source, row.type,\n {}, row.properties, target) YIELD rel\n RETURN distinct 'done'\n `;\n }\n}\n\nfunction toObjects<\n RecordShape extends Record<string, Any> = Record<string, Any>,\n>(records: Neo4jRecord<RecordShape>): RecordShape[] {\n return records.map((record: Any) => {\n const rObj = record.toObject();\n const out: Partial<RecordShape> = {};\n Object.keys(rObj).forEach((key: keyof RecordShape) => {\n out[key] = itemIntToString(rObj[key]);\n });\n return out as RecordShape;\n });\n}\n\nfunction itemIntToString(item: Any): Any {\n if (neo4j.isInt(item)) return item.toString();\n if (Array.isArray(item)) return item.map((ii) => itemIntToString(ii));\n if ([\"number\", \"string\", \"boolean\"].indexOf(typeof item) !== -1) return item;\n if (item === null) return item;\n if (typeof item === \"object\") return objIntToString(item);\n}\n\nfunction objIntToString(obj: Any) {\n const entry = extractFromNeoObjects(obj);\n let newObj: Any = null;\n if (Array.isArray(entry)) {\n newObj = entry.map((item) => itemIntToString(item));\n } else if (entry !== null && typeof entry === \"object\") {\n newObj = {};\n Object.keys(entry).forEach((key) => {\n newObj[key] = itemIntToString(entry[key]);\n });\n }\n return newObj;\n}\n\nfunction extractFromNeoObjects(obj: Any) {\n if (\n // eslint-disable-next-line\n obj instanceof (neo4j.types.Node as any) ||\n // eslint-disable-next-line\n obj instanceof (neo4j.types.Relationship as any)\n ) {\n return obj.properties;\n // eslint-disable-next-line\n } else if (obj instanceof (neo4j.types.Path as any)) {\n // eslint-disable-next-line\n return [].concat.apply<any[], any[], any[]>([], extractPathForRows(obj));\n }\n return obj;\n}\n\nconst extractPathForRows = (path: Neo4jPath) => {\n let { segments } = path;\n if (!Array.isArray(path.segments) || path.segments.length < 1) {\n segments = [{ ...path, end: null } as Any];\n }\n\n return segments.map((segment: Any) =>\n [\n objIntToString(segment.start),\n objIntToString(segment.relationship),\n objIntToString(segment.end),\n ].filter((part) => part !== null)\n );\n};\n"],"mappings":";;;AAgDA,MAAa,oBAAoB;AAEjC,MAAM,uBAAuB;AAC7B,MAAM,aAAa;AACnB,MAAM,0BAA0B;AAChC,MAAM,kBAAkB,CAAC,qBAAqB,cAAc;AAC5D,MAAM,gBAAgB,CAAC,kBAAkB;AAEzC,MAAM,qBAAqB;;;;;;AAO3B,MAAM,wBAAwB;;;;;;;;AAS9B,MAAM,uBAAuB;;;;;;;;AAS7B,MAAM,YAAY;;;;;;;;;AAUlB,SAAS,wBACP,iBAAiB,IACjB,QAAQ,sBACC;AACT,QAAO,mBAAmB,KAAA,KAAa,iBAAiB;;AAG1D,SAAS,kBAAkB,MAAc;AACvC,QAAO,KAAK,QAAQ,OAAO,IAAI,CAAC,QAAQ,OAAO,IAAI;;AAGrD,SAAgB,aACd,QACA,YACQ;CACR,IAAI,qBAA+B,EAAE;CACrC,IAAI,oBAA8B,EAAE;AAEpC,KAAI,YAAY;AACd,OAAK,MAAM,CAAC,UAAU,eAAe,OAAO,QAAQ,OAAO,UAAU,EAAE;AACrE,sBAAmB,KAAK,OAAO,SAAS,IAAI;AAE5C,QAAK,MAAM,QAAQ,YAA0C;IAC3D,IAAI,UAAU;AAEd,QAAI,KAAK,SAAS;SACZ,KAAK,OAAO,SAAS,EACvB,KAAI,wBAAwB,KAAK,eAAe,CAC9C,WAAU,YAAY,kBAAkB,KAAK,OAAO,GAAG;SAEvD,WAAU,sBAAsB,KAAK,OAClC,IAAI,kBAAkB,CACtB,KAAK,KAAK;eAIjB;KAAC;KAAW;KAAS;KAAQ;KAAa;KAAkB,CAAC,SAC3D,KAAK,KACN;SAEG,KAAK,QAAQ,KAAA,EACf,WAAU,QAAQ,KAAK,IAAI,SAAS,KAAK;cAErC,KAAK,OAAO,SAAS,E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AAK,SAAS,gBAAgB,KAAK,CAAC;UAC1C,UAAU,QAAQ,OAAO,UAAU,UAAU;AACtD,WAAS,EAAE;AACX,SAAO,KAAK,MAAM,CAAC,SAAS,QAAQ;AAClC,UAAO,OAAO,gBAAgB,MAAM,KAAK;IACzC;;AAEJ,QAAO;;AAGT,SAAS,sBAAsB,KAAU;AACvC,KAEE,eAAgB,MAAM,MAAM,QAE5B,eAAgB,MAAM,MAAM,aAE5B,QAAO,IAAI;UAEF,eAAgB,MAAM,MAAM,KAErC,QAAO,EAAE,CAAC,OAAO,MAA2B,EAAE,EAAE,mBAAmB,IAAI,CAAC;AAE1E,QAAO;;AAGT,MAAM,sBAAsB,SAAoB;CAC9C,IAAI,EAAE,aAAa;AACnB,KAAI,CAAC,MAAM,QAAQ,KAAK,SAAS,IAAI,KAAK,SAAS,SAAS,EAC1D,YAAW,CAAC;EAAE,GAAG;EAAM,KAAK;EAAM,CAAQ;AAG5C,QAAO,SAAS,KAAK,YACnB;EACE,eAAe,QAAQ,MAAM;EAC7B,eAAe,QAAQ,aAAa;EACpC,eAAe,QAAQ,IAAI;EAC5B,CAAC,QAAQ,SAAS,SAAS,KAAK,CAClC"}
package/dist/index.cjs ADDED
@@ -0,0 +1,28 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_neo4j_graph = require("./graphs/neo4j_graph.cjs");
3
+ const require_memgraph_graph = require("./graphs/memgraph_graph.cjs");
4
+ const require_document = require("./graphs/document.cjs");
5
+ require("./graphs/index.cjs");
6
+ const require_neo4j_vector = require("./vectorstores/neo4j_vector.cjs");
7
+ require("./vectorstores/index.cjs");
8
+ const require_neo4j = require("./stores/message/neo4j.cjs");
9
+ require("./stores/message/index.cjs");
10
+ const require_prompts = require("./chains/graph_qa/prompts.cjs");
11
+ const require_cypher = require("./chains/graph_qa/cypher.cjs");
12
+ require("./chains/graph_qa/index.cjs");
13
+ exports.BASE_ENTITY_LABEL = require_neo4j_graph.BASE_ENTITY_LABEL;
14
+ exports.CYPHER_GENERATION_PROMPT = require_prompts.CYPHER_GENERATION_PROMPT;
15
+ exports.CYPHER_QA_PROMPT = require_prompts.CYPHER_QA_PROMPT;
16
+ exports.GraphCypherQAChain = require_cypher.GraphCypherQAChain;
17
+ exports.GraphDocument = require_document.GraphDocument;
18
+ exports.INTERMEDIATE_STEPS_KEY = require_cypher.INTERMEDIATE_STEPS_KEY;
19
+ exports.MemgraphGraph = require_memgraph_graph.MemgraphGraph;
20
+ exports.Neo4jChatMessageHistory = require_neo4j.Neo4jChatMessageHistory;
21
+ exports.Neo4jGraph = require_neo4j_graph.Neo4jGraph;
22
+ exports.Neo4jVectorStore = require_neo4j_vector.Neo4jVectorStore;
23
+ exports.Node = require_document.Node;
24
+ exports.Relationship = require_document.Relationship;
25
+ exports.constructMetadataFilter = require_neo4j_vector.constructMetadataFilter;
26
+ exports.formatSchema = require_neo4j_graph.formatSchema;
27
+ exports.isVersionLessThan = require_neo4j_vector.isVersionLessThan;
28
+ exports.removeLuceneChars = require_neo4j_vector.removeLuceneChars;
@@ -0,0 +1,8 @@
1
+ import { GraphDocument, Node, Relationship } from "./graphs/document.cjs";
2
+ import { AddGraphDocumentsConfig, BASE_ENTITY_LABEL, Neo4jGraph, Neo4jGraphConfig, NodeType, PathType, RelType, StructuredSchema, formatSchema } from "./graphs/neo4j_graph.cjs";
3
+ import { MemgraphGraph, MemgraphGraphConfig } from "./graphs/memgraph_graph.cjs";
4
+ import { DistanceStrategy, IndexType, Metadata, Neo4jVectorStore, Neo4jVectorStoreArgs, SearchType, constructMetadataFilter, isVersionLessThan, removeLuceneChars } from "./vectorstores/neo4j_vector.cjs";
5
+ import { Neo4jChatMessageHistory, Neo4jChatMessageHistoryConfigInput } from "./stores/message/neo4j.cjs";
6
+ import { FromLLMInput, GraphCypherQAChain, GraphCypherQAChainInput, INTERMEDIATE_STEPS_KEY } from "./chains/graph_qa/cypher.cjs";
7
+ import { CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT } from "./chains/graph_qa/prompts.cjs";
8
+ export { type AddGraphDocumentsConfig, BASE_ENTITY_LABEL, CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT, type DistanceStrategy, type FromLLMInput, GraphCypherQAChain, type GraphCypherQAChainInput, GraphDocument, INTERMEDIATE_STEPS_KEY, type IndexType, MemgraphGraph, type MemgraphGraphConfig, type Metadata, Neo4jChatMessageHistory, type Neo4jChatMessageHistoryConfigInput, Neo4jGraph, type Neo4jGraphConfig, Neo4jVectorStore, type Neo4jVectorStoreArgs, Node, type NodeType, type PathType, type RelType, Relationship, type SearchType, type StructuredSchema, constructMetadataFilter, formatSchema, isVersionLessThan, removeLuceneChars };
@@ -0,0 +1,8 @@
1
+ import { GraphDocument, Node, Relationship } from "./graphs/document.js";
2
+ import { AddGraphDocumentsConfig, BASE_ENTITY_LABEL, Neo4jGraph, Neo4jGraphConfig, NodeType, PathType, RelType, StructuredSchema, formatSchema } from "./graphs/neo4j_graph.js";
3
+ import { MemgraphGraph, MemgraphGraphConfig } from "./graphs/memgraph_graph.js";
4
+ import { DistanceStrategy, IndexType, Metadata, Neo4jVectorStore, Neo4jVectorStoreArgs, SearchType, constructMetadataFilter, isVersionLessThan, removeLuceneChars } from "./vectorstores/neo4j_vector.js";
5
+ import { Neo4jChatMessageHistory, Neo4jChatMessageHistoryConfigInput } from "./stores/message/neo4j.js";
6
+ import { FromLLMInput, GraphCypherQAChain, GraphCypherQAChainInput, INTERMEDIATE_STEPS_KEY } from "./chains/graph_qa/cypher.js";
7
+ import { CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT } from "./chains/graph_qa/prompts.js";
8
+ export { type AddGraphDocumentsConfig, BASE_ENTITY_LABEL, CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT, type DistanceStrategy, type FromLLMInput, GraphCypherQAChain, type GraphCypherQAChainInput, GraphDocument, INTERMEDIATE_STEPS_KEY, type IndexType, MemgraphGraph, type MemgraphGraphConfig, type Metadata, Neo4jChatMessageHistory, type Neo4jChatMessageHistoryConfigInput, Neo4jGraph, type Neo4jGraphConfig, Neo4jVectorStore, type Neo4jVectorStoreArgs, Node, type NodeType, type PathType, type RelType, Relationship, type SearchType, type StructuredSchema, constructMetadataFilter, formatSchema, isVersionLessThan, removeLuceneChars };
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import { BASE_ENTITY_LABEL, Neo4jGraph, formatSchema } from "./graphs/neo4j_graph.js";
2
+ import { MemgraphGraph } from "./graphs/memgraph_graph.js";
3
+ import { GraphDocument, Node, Relationship } from "./graphs/document.js";
4
+ import "./graphs/index.js";
5
+ import { Neo4jVectorStore, constructMetadataFilter, isVersionLessThan, removeLuceneChars } from "./vectorstores/neo4j_vector.js";
6
+ import "./vectorstores/index.js";
7
+ import { Neo4jChatMessageHistory } from "./stores/message/neo4j.js";
8
+ import "./stores/message/index.js";
9
+ import { CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT } from "./chains/graph_qa/prompts.js";
10
+ import { GraphCypherQAChain, INTERMEDIATE_STEPS_KEY } from "./chains/graph_qa/cypher.js";
11
+ import "./chains/graph_qa/index.js";
12
+ export { BASE_ENTITY_LABEL, CYPHER_GENERATION_PROMPT, CYPHER_QA_PROMPT, GraphCypherQAChain, GraphDocument, INTERMEDIATE_STEPS_KEY, MemgraphGraph, Neo4jChatMessageHistory, Neo4jGraph, Neo4jVectorStore, Node, Relationship, constructMetadataFilter, formatSchema, isVersionLessThan, removeLuceneChars };
@@ -0,0 +1 @@
1
+ require("./neo4j.cjs");
@@ -0,0 +1 @@
1
+ import { Neo4jChatMessageHistory, Neo4jChatMessageHistoryConfigInput } from "./neo4j.js";
@@ -0,0 +1,2 @@
1
+ import "./neo4j.js";
2
+ export {};