langchain 0.0.163 → 0.0.165

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 (43) hide show
  1. package/chat_models/portkey.cjs +1 -0
  2. package/chat_models/portkey.d.ts +1 -0
  3. package/chat_models/portkey.js +1 -0
  4. package/dist/chat_models/bedrock.cjs +3 -0
  5. package/dist/chat_models/bedrock.js +3 -0
  6. package/dist/chat_models/portkey.cjs +159 -0
  7. package/dist/chat_models/portkey.d.ts +17 -0
  8. package/dist/chat_models/portkey.js +155 -0
  9. package/dist/document_loaders/web/notionapi.cjs +28 -5
  10. package/dist/document_loaders/web/notionapi.d.ts +2 -0
  11. package/dist/document_loaders/web/notionapi.js +25 -5
  12. package/dist/embeddings/minimax.cjs +1 -1
  13. package/dist/embeddings/minimax.js +1 -1
  14. package/dist/graphs/neo4j_graph.cjs +86 -10
  15. package/dist/graphs/neo4j_graph.d.ts +2 -1
  16. package/dist/graphs/neo4j_graph.js +86 -10
  17. package/dist/llms/bedrock.cjs +3 -0
  18. package/dist/llms/bedrock.js +3 -0
  19. package/dist/llms/portkey.cjs +147 -0
  20. package/dist/llms/portkey.d.ts +33 -0
  21. package/dist/llms/portkey.js +138 -0
  22. package/dist/llms/sagemaker_endpoint.cjs +76 -14
  23. package/dist/llms/sagemaker_endpoint.d.ts +39 -20
  24. package/dist/llms/sagemaker_endpoint.js +77 -15
  25. package/dist/load/import_constants.cjs +3 -0
  26. package/dist/load/import_constants.js +3 -0
  27. package/dist/output_parsers/list.cjs +1 -1
  28. package/dist/output_parsers/list.js +1 -1
  29. package/dist/util/stream.cjs +4 -4
  30. package/dist/util/stream.js +4 -4
  31. package/dist/vectorstores/cassandra.cjs +212 -0
  32. package/dist/vectorstores/cassandra.d.ts +98 -0
  33. package/dist/vectorstores/cassandra.js +208 -0
  34. package/dist/vectorstores/mongodb_atlas.cjs +29 -39
  35. package/dist/vectorstores/mongodb_atlas.js +29 -39
  36. package/dist/vectorstores/prisma.d.ts +1 -1
  37. package/llms/portkey.cjs +1 -0
  38. package/llms/portkey.d.ts +1 -0
  39. package/llms/portkey.js +1 -0
  40. package/package.json +42 -2
  41. package/vectorstores/cassandra.cjs +1 -0
  42. package/vectorstores/cassandra.d.ts +1 -0
  43. package/vectorstores/cassandra.js +1 -0
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/chat_models/portkey.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/portkey.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/portkey.js'
@@ -171,6 +171,9 @@ class ChatBedrock extends base_js_1.SimpleChatModel {
171
171
  provider,
172
172
  });
173
173
  const json = await response.json();
174
+ if (!response.ok) {
175
+ throw new Error(`Error ${response.status}: ${json.message ?? JSON.stringify(json)}`);
176
+ }
174
177
  const text = bedrock_js_1.BedrockLLMInputOutputAdapter.prepareOutput(provider, json);
175
178
  return text;
176
179
  }
@@ -166,6 +166,9 @@ export class ChatBedrock extends SimpleChatModel {
166
166
  provider,
167
167
  });
168
168
  const json = await response.json();
169
+ if (!response.ok) {
170
+ throw new Error(`Error ${response.status}: ${json.message ?? JSON.stringify(json)}`);
171
+ }
169
172
  const text = BedrockLLMInputOutputAdapter.prepareOutput(provider, json);
170
173
  return text;
171
174
  }
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PortkeyChat = void 0;
4
+ const portkey_js_1 = require("../llms/portkey.cjs");
5
+ const index_js_1 = require("../schema/index.cjs");
6
+ const base_js_1 = require("./base.cjs");
7
+ function portkeyResponseToChatMessage(message) {
8
+ switch (message.role) {
9
+ case "user":
10
+ return new index_js_1.HumanMessage(message.content || "");
11
+ case "assistant":
12
+ return new index_js_1.AIMessage(message.content || "");
13
+ case "system":
14
+ return new index_js_1.SystemMessage(message.content || "");
15
+ default:
16
+ return new index_js_1.ChatMessage(message.content || "", message.role ?? "unknown");
17
+ }
18
+ }
19
+ function _convertDeltaToMessageChunk(
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
+ delta) {
22
+ const { role } = delta;
23
+ const content = delta.content ?? "";
24
+ let additional_kwargs;
25
+ if (delta.function_call) {
26
+ additional_kwargs = {
27
+ function_call: delta.function_call,
28
+ };
29
+ }
30
+ else {
31
+ additional_kwargs = {};
32
+ }
33
+ if (role === "user") {
34
+ return new index_js_1.HumanMessageChunk({ content });
35
+ }
36
+ else if (role === "assistant") {
37
+ return new index_js_1.AIMessageChunk({ content, additional_kwargs });
38
+ }
39
+ else if (role === "system") {
40
+ return new index_js_1.SystemMessageChunk({ content });
41
+ }
42
+ else if (role === "function") {
43
+ return new index_js_1.FunctionMessageChunk({
44
+ content,
45
+ additional_kwargs,
46
+ name: delta.name,
47
+ });
48
+ }
49
+ else {
50
+ return new index_js_1.ChatMessageChunk({ content, role });
51
+ }
52
+ }
53
+ class PortkeyChat extends base_js_1.BaseChatModel {
54
+ constructor(init) {
55
+ super(init ?? {});
56
+ Object.defineProperty(this, "apiKey", {
57
+ enumerable: true,
58
+ configurable: true,
59
+ writable: true,
60
+ value: undefined
61
+ });
62
+ Object.defineProperty(this, "baseURL", {
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true,
66
+ value: undefined
67
+ });
68
+ Object.defineProperty(this, "mode", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: undefined
73
+ });
74
+ Object.defineProperty(this, "llms", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: undefined
79
+ });
80
+ Object.defineProperty(this, "session", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: void 0
85
+ });
86
+ this.apiKey = init?.apiKey;
87
+ this.baseURL = init?.baseURL;
88
+ this.mode = init?.mode;
89
+ this.llms = init?.llms;
90
+ this.session = (0, portkey_js_1.getPortkeySession)({
91
+ apiKey: this.apiKey,
92
+ baseURL: this.baseURL,
93
+ llms: this.llms,
94
+ mode: this.mode,
95
+ });
96
+ }
97
+ _llmType() {
98
+ return "portkey";
99
+ }
100
+ async _generate(messages, options, _) {
101
+ const messagesList = messages.map((message) => ({
102
+ role: message._getType(),
103
+ content: message.content,
104
+ }));
105
+ const response = await this.session.portkey.chatCompletions.create({
106
+ messages: messagesList,
107
+ ...options,
108
+ stream: false,
109
+ });
110
+ const generations = [];
111
+ for (const data of response.choices ?? []) {
112
+ const text = data.message?.content ?? "";
113
+ const generation = {
114
+ text,
115
+ message: portkeyResponseToChatMessage(data.message ?? {}),
116
+ };
117
+ if (data.finish_reason) {
118
+ generation.generationInfo = { finish_reason: data.finish_reason };
119
+ }
120
+ generations.push(generation);
121
+ }
122
+ return {
123
+ generations,
124
+ };
125
+ }
126
+ async *_streamResponseChunks(messages, options, runManager) {
127
+ const messagesList = messages.map((message) => ({
128
+ role: message._getType(),
129
+ content: message.content,
130
+ }));
131
+ const response = await this.session.portkey.chatCompletions.create({
132
+ messages: messagesList,
133
+ ...options,
134
+ stream: true,
135
+ });
136
+ for await (const data of response) {
137
+ const choice = data?.choices[0];
138
+ if (!choice) {
139
+ continue;
140
+ }
141
+ const chunk = new index_js_1.ChatGenerationChunk({
142
+ message: _convertDeltaToMessageChunk(choice.delta ?? {}),
143
+ text: choice.message?.content ?? "",
144
+ generationInfo: {
145
+ finishReason: choice.finish_reason,
146
+ },
147
+ });
148
+ yield chunk;
149
+ void runManager?.handleLLMNewToken(chunk.text ?? "");
150
+ }
151
+ if (options.signal?.aborted) {
152
+ throw new Error("AbortError");
153
+ }
154
+ }
155
+ _combineLLMOutput() {
156
+ return {};
157
+ }
158
+ }
159
+ exports.PortkeyChat = PortkeyChat;
@@ -0,0 +1,17 @@
1
+ import { LLMOptions } from "portkey-ai";
2
+ import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
3
+ import { PortkeySession } from "../llms/portkey.js";
4
+ import { BaseMessage, ChatGenerationChunk, ChatResult } from "../schema/index.js";
5
+ import { BaseChatModel } from "./base.js";
6
+ export declare class PortkeyChat extends BaseChatModel {
7
+ apiKey?: string;
8
+ baseURL?: string;
9
+ mode?: string;
10
+ llms?: [LLMOptions] | null;
11
+ session: PortkeySession;
12
+ constructor(init?: Partial<PortkeyChat>);
13
+ _llmType(): string;
14
+ _generate(messages: BaseMessage[], options: this["ParsedCallOptions"], _?: CallbackManagerForLLMRun): Promise<ChatResult>;
15
+ _streamResponseChunks(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
16
+ _combineLLMOutput(): {};
17
+ }
@@ -0,0 +1,155 @@
1
+ import { getPortkeySession } from "../llms/portkey.js";
2
+ import { AIMessage, AIMessageChunk, ChatGenerationChunk, ChatMessage, ChatMessageChunk, FunctionMessageChunk, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, } from "../schema/index.js";
3
+ import { BaseChatModel } from "./base.js";
4
+ function portkeyResponseToChatMessage(message) {
5
+ switch (message.role) {
6
+ case "user":
7
+ return new HumanMessage(message.content || "");
8
+ case "assistant":
9
+ return new AIMessage(message.content || "");
10
+ case "system":
11
+ return new SystemMessage(message.content || "");
12
+ default:
13
+ return new ChatMessage(message.content || "", message.role ?? "unknown");
14
+ }
15
+ }
16
+ function _convertDeltaToMessageChunk(
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ delta) {
19
+ const { role } = delta;
20
+ const content = delta.content ?? "";
21
+ let additional_kwargs;
22
+ if (delta.function_call) {
23
+ additional_kwargs = {
24
+ function_call: delta.function_call,
25
+ };
26
+ }
27
+ else {
28
+ additional_kwargs = {};
29
+ }
30
+ if (role === "user") {
31
+ return new HumanMessageChunk({ content });
32
+ }
33
+ else if (role === "assistant") {
34
+ return new AIMessageChunk({ content, additional_kwargs });
35
+ }
36
+ else if (role === "system") {
37
+ return new SystemMessageChunk({ content });
38
+ }
39
+ else if (role === "function") {
40
+ return new FunctionMessageChunk({
41
+ content,
42
+ additional_kwargs,
43
+ name: delta.name,
44
+ });
45
+ }
46
+ else {
47
+ return new ChatMessageChunk({ content, role });
48
+ }
49
+ }
50
+ export class PortkeyChat extends BaseChatModel {
51
+ constructor(init) {
52
+ super(init ?? {});
53
+ Object.defineProperty(this, "apiKey", {
54
+ enumerable: true,
55
+ configurable: true,
56
+ writable: true,
57
+ value: undefined
58
+ });
59
+ Object.defineProperty(this, "baseURL", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: undefined
64
+ });
65
+ Object.defineProperty(this, "mode", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: undefined
70
+ });
71
+ Object.defineProperty(this, "llms", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: undefined
76
+ });
77
+ Object.defineProperty(this, "session", {
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true,
81
+ value: void 0
82
+ });
83
+ this.apiKey = init?.apiKey;
84
+ this.baseURL = init?.baseURL;
85
+ this.mode = init?.mode;
86
+ this.llms = init?.llms;
87
+ this.session = getPortkeySession({
88
+ apiKey: this.apiKey,
89
+ baseURL: this.baseURL,
90
+ llms: this.llms,
91
+ mode: this.mode,
92
+ });
93
+ }
94
+ _llmType() {
95
+ return "portkey";
96
+ }
97
+ async _generate(messages, options, _) {
98
+ const messagesList = messages.map((message) => ({
99
+ role: message._getType(),
100
+ content: message.content,
101
+ }));
102
+ const response = await this.session.portkey.chatCompletions.create({
103
+ messages: messagesList,
104
+ ...options,
105
+ stream: false,
106
+ });
107
+ const generations = [];
108
+ for (const data of response.choices ?? []) {
109
+ const text = data.message?.content ?? "";
110
+ const generation = {
111
+ text,
112
+ message: portkeyResponseToChatMessage(data.message ?? {}),
113
+ };
114
+ if (data.finish_reason) {
115
+ generation.generationInfo = { finish_reason: data.finish_reason };
116
+ }
117
+ generations.push(generation);
118
+ }
119
+ return {
120
+ generations,
121
+ };
122
+ }
123
+ async *_streamResponseChunks(messages, options, runManager) {
124
+ const messagesList = messages.map((message) => ({
125
+ role: message._getType(),
126
+ content: message.content,
127
+ }));
128
+ const response = await this.session.portkey.chatCompletions.create({
129
+ messages: messagesList,
130
+ ...options,
131
+ stream: true,
132
+ });
133
+ for await (const data of response) {
134
+ const choice = data?.choices[0];
135
+ if (!choice) {
136
+ continue;
137
+ }
138
+ const chunk = new ChatGenerationChunk({
139
+ message: _convertDeltaToMessageChunk(choice.delta ?? {}),
140
+ text: choice.message?.content ?? "",
141
+ generationInfo: {
142
+ finishReason: choice.finish_reason,
143
+ },
144
+ });
145
+ yield chunk;
146
+ void runManager?.handleLLMNewToken(chunk.text ?? "");
147
+ }
148
+ if (options.signal?.aborted) {
149
+ throw new Error("AbortError");
150
+ }
151
+ }
152
+ _combineLLMOutput() {
153
+ return {};
154
+ }
155
+ }
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.NotionAPILoader = exports.isDatabase = exports.isPage = exports.isErrorResponse = exports.isDatabaseResponse = exports.isPageResponse = void 0;
4
7
  const client_1 = require("@notionhq/client");
5
8
  const notion_to_md_1 = require("notion-to-md");
6
9
  const notion_js_1 = require("notion-to-md/build/utils/notion.js");
10
+ const js_yaml_1 = __importDefault(require("js-yaml"));
7
11
  const document_js_1 = require("../../document.cjs");
8
12
  const base_js_1 = require("../base.cjs");
9
13
  const async_caller_js_1 = require("../../util/async_caller.cjs");
@@ -84,6 +88,12 @@ class NotionAPILoader extends base_js_1.BaseDocumentLoader {
84
88
  writable: true,
85
89
  value: void 0
86
90
  });
91
+ Object.defineProperty(this, "propertiesAsHeader", {
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true,
95
+ value: void 0
96
+ });
87
97
  this.caller = new async_caller_js_1.AsyncCaller({
88
98
  maxConcurrency: 64,
89
99
  ...options.callerOptions,
@@ -103,6 +113,7 @@ class NotionAPILoader extends base_js_1.BaseDocumentLoader {
103
113
  this.documents = [];
104
114
  this.rootTitle = "";
105
115
  this.onDocumentLoaded = options.onDocumentLoaded ?? ((_ti, _cu) => { });
116
+ this.propertiesAsHeader = options.propertiesAsHeader || false;
106
117
  }
107
118
  /**
108
119
  * Adds a selection of page ids to the pageQueue and removes duplicates.
@@ -278,14 +289,26 @@ class NotionAPILoader extends base_js_1.BaseDocumentLoader {
278
289
  pageData,
279
290
  this.caller.call(() => (0, notion_js_1.getBlockChildren)(this.notionClient, pageId, null)),
280
291
  ]);
281
- if (!(0, client_1.isFullPage)(pageDetails))
292
+ if (!(0, client_1.isFullPage)(pageDetails)) {
293
+ this.pageCompleted.push(pageId);
282
294
  return;
295
+ }
283
296
  const mdBlocks = await this.loadBlocks(pageBlocks);
284
297
  const mdStringObject = this.n2mClient.toMarkdownString(mdBlocks);
285
- const pageDocument = new document_js_1.Document({
286
- pageContent: mdStringObject.parent,
287
- metadata: this.parsePageDetails(pageDetails),
288
- });
298
+ let pageContent = mdStringObject.parent;
299
+ const metadata = this.parsePageDetails(pageDetails);
300
+ if (this.propertiesAsHeader) {
301
+ pageContent =
302
+ `---\n` +
303
+ `${js_yaml_1.default.dump(metadata.properties)}` +
304
+ `---\n\n` +
305
+ `${pageContent ?? ""}`;
306
+ }
307
+ if (!pageContent) {
308
+ this.pageCompleted.push(pageId);
309
+ return;
310
+ }
311
+ const pageDocument = new document_js_1.Document({ pageContent, metadata });
289
312
  this.documents.push(pageDocument);
290
313
  this.pageCompleted.push(pageId);
291
314
  this.onDocumentLoaded(this.documents.length, this.pageQueueTotal, this.getTitle(pageDetails) || undefined, this.rootTitle);
@@ -29,6 +29,7 @@ export type NotionAPILoaderOptions = {
29
29
  type?: NotionAPIType;
30
30
  callerOptions?: ConstructorParameters<typeof AsyncCaller>[0];
31
31
  onDocumentLoaded?: OnDocumentLoadedCallback;
32
+ propertiesAsHeader?: boolean;
32
33
  };
33
34
  /**
34
35
  * A class that extends the BaseDocumentLoader class. It represents a
@@ -45,6 +46,7 @@ export declare class NotionAPILoader extends BaseDocumentLoader {
45
46
  private documents;
46
47
  private rootTitle;
47
48
  private onDocumentLoaded;
49
+ private propertiesAsHeader;
48
50
  constructor(options: NotionAPILoaderOptions);
49
51
  /**
50
52
  * Adds a selection of page ids to the pageQueue and removes duplicates.
@@ -1,6 +1,7 @@
1
1
  import { Client, isFullBlock, isFullPage, iteratePaginatedAPI, APIErrorCode, isNotionClientError, isFullDatabase, } from "@notionhq/client";
2
2
  import { NotionToMarkdown } from "notion-to-md";
3
3
  import { getBlockChildren } from "notion-to-md/build/utils/notion.js";
4
+ import yaml from "js-yaml";
4
5
  import { Document } from "../../document.js";
5
6
  import { BaseDocumentLoader } from "../base.js";
6
7
  import { AsyncCaller } from "../../util/async_caller.js";
@@ -76,6 +77,12 @@ export class NotionAPILoader extends BaseDocumentLoader {
76
77
  writable: true,
77
78
  value: void 0
78
79
  });
80
+ Object.defineProperty(this, "propertiesAsHeader", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: void 0
85
+ });
79
86
  this.caller = new AsyncCaller({
80
87
  maxConcurrency: 64,
81
88
  ...options.callerOptions,
@@ -95,6 +102,7 @@ export class NotionAPILoader extends BaseDocumentLoader {
95
102
  this.documents = [];
96
103
  this.rootTitle = "";
97
104
  this.onDocumentLoaded = options.onDocumentLoaded ?? ((_ti, _cu) => { });
105
+ this.propertiesAsHeader = options.propertiesAsHeader || false;
98
106
  }
99
107
  /**
100
108
  * Adds a selection of page ids to the pageQueue and removes duplicates.
@@ -270,14 +278,26 @@ export class NotionAPILoader extends BaseDocumentLoader {
270
278
  pageData,
271
279
  this.caller.call(() => getBlockChildren(this.notionClient, pageId, null)),
272
280
  ]);
273
- if (!isFullPage(pageDetails))
281
+ if (!isFullPage(pageDetails)) {
282
+ this.pageCompleted.push(pageId);
274
283
  return;
284
+ }
275
285
  const mdBlocks = await this.loadBlocks(pageBlocks);
276
286
  const mdStringObject = this.n2mClient.toMarkdownString(mdBlocks);
277
- const pageDocument = new Document({
278
- pageContent: mdStringObject.parent,
279
- metadata: this.parsePageDetails(pageDetails),
280
- });
287
+ let pageContent = mdStringObject.parent;
288
+ const metadata = this.parsePageDetails(pageDetails);
289
+ if (this.propertiesAsHeader) {
290
+ pageContent =
291
+ `---\n` +
292
+ `${yaml.dump(metadata.properties)}` +
293
+ `---\n\n` +
294
+ `${pageContent ?? ""}`;
295
+ }
296
+ if (!pageContent) {
297
+ this.pageCompleted.push(pageId);
298
+ return;
299
+ }
300
+ const pageDocument = new Document({ pageContent, metadata });
281
301
  this.documents.push(pageDocument);
282
302
  this.pageCompleted.push(pageId);
283
303
  this.onDocumentLoaded(this.documents.length, this.pageQueueTotal, this.getTitle(pageDetails) || undefined, this.rootTitle);
@@ -81,8 +81,8 @@ class MinimaxEmbeddings extends base_js_1.Embeddings {
81
81
  this.type = fieldsWithDefaults?.type ?? this.type;
82
82
  this.stripNewLines =
83
83
  fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
84
- this.apiUrl = `${this.basePath}/embeddings`;
85
84
  this.basePath = fields?.configuration?.basePath ?? this.basePath;
85
+ this.apiUrl = `${this.basePath}/embeddings`;
86
86
  this.headers = fields?.configuration?.headers ?? this.headers;
87
87
  }
88
88
  /**
@@ -78,8 +78,8 @@ export class MinimaxEmbeddings extends Embeddings {
78
78
  this.type = fieldsWithDefaults?.type ?? this.type;
79
79
  this.stripNewLines =
80
80
  fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
81
- this.apiUrl = `${this.basePath}/embeddings`;
82
81
  this.basePath = fields?.configuration?.basePath ?? this.basePath;
82
+ this.apiUrl = `${this.basePath}/embeddings`;
83
83
  this.headers = fields?.configuration?.headers ?? this.headers;
84
84
  }
85
85
  /**
@@ -59,18 +59,19 @@ class Neo4jGraph {
59
59
  }
60
60
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
61
  async query(query, params = {}) {
62
- const session = this.driver.session({ database: this.database });
63
62
  try {
64
- const result = await session.run(query, params);
65
- return result.records.map((record) => record.toObject());
63
+ const result = await this.driver.executeQuery(query, params, {
64
+ database: this.database,
65
+ });
66
+ return toObjects(result.records);
66
67
  }
67
- finally {
68
- await session.close();
68
+ catch (error) {
69
+ // ignore errors
69
70
  }
71
+ return undefined;
70
72
  }
71
73
  async verifyConnectivity() {
72
- const session = this.driver.session({ database: this.database });
73
- await session.close();
74
+ await this.driver.verifyAuthentication();
74
75
  }
75
76
  async refreshSchema() {
76
77
  const nodePropertiesQuery = `
@@ -99,14 +100,89 @@ class Neo4jGraph {
99
100
  const relationships = await this.query(relQuery);
100
101
  this.schema = `
101
102
  Node properties are the following:
102
- ${nodeProperties.map((el) => el.output)}
103
+ ${JSON.stringify(nodeProperties?.map((el) => el.output))}
103
104
 
104
105
  Relationship properties are the following:
105
- ${relationshipsProperties.map((el) => el.output)}
106
+ ${JSON.stringify(relationshipsProperties?.map((el) => el.output))}
106
107
 
107
108
  The relationships are the following:
108
- ${relationships.map((el) => el.output)}
109
+ ${JSON.stringify(relationships?.map((el) => el.output))}
109
110
  `;
110
111
  }
112
+ async close() {
113
+ await this.driver.close();
114
+ }
111
115
  }
112
116
  exports.Neo4jGraph = Neo4jGraph;
117
+ function toObjects(records) {
118
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
119
+ const recordValues = records.map((record) => {
120
+ const rObj = record.toObject();
121
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
122
+ const out = {};
123
+ Object.keys(rObj).forEach((key) => {
124
+ out[key] = itemIntToString(rObj[key]);
125
+ });
126
+ return out;
127
+ });
128
+ return recordValues;
129
+ }
130
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
131
+ function itemIntToString(item) {
132
+ if (neo4j_driver_1.default.isInt(item))
133
+ return item.toString();
134
+ if (Array.isArray(item))
135
+ return item.map((ii) => itemIntToString(ii));
136
+ if (["number", "string", "boolean"].indexOf(typeof item) !== -1)
137
+ return item;
138
+ if (item === null)
139
+ return item;
140
+ if (typeof item === "object")
141
+ return objIntToString(item);
142
+ }
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
144
+ function objIntToString(obj) {
145
+ const entry = extractFromNeoObjects(obj);
146
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
147
+ let newObj = null;
148
+ if (Array.isArray(entry)) {
149
+ newObj = entry.map((item) => itemIntToString(item));
150
+ }
151
+ else if (entry !== null && typeof entry === "object") {
152
+ newObj = {};
153
+ Object.keys(entry).forEach((key) => {
154
+ newObj[key] = itemIntToString(entry[key]);
155
+ });
156
+ }
157
+ return newObj;
158
+ }
159
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
160
+ function extractFromNeoObjects(obj) {
161
+ if (
162
+ // eslint-disable-next-line
163
+ obj instanceof neo4j_driver_1.default.types.Node ||
164
+ // eslint-disable-next-line
165
+ obj instanceof neo4j_driver_1.default.types.Relationship) {
166
+ return obj.properties;
167
+ // eslint-disable-next-line
168
+ }
169
+ else if (obj instanceof neo4j_driver_1.default.types.Path) {
170
+ // eslint-disable-next-line
171
+ return [].concat.apply([], extractPathForRows(obj));
172
+ }
173
+ return obj;
174
+ }
175
+ const extractPathForRows = (path) => {
176
+ let { segments } = path;
177
+ // Zero length path. No relationship, end === start
178
+ if (!Array.isArray(path.segments) || path.segments.length < 1) {
179
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
180
+ segments = [{ ...path, end: null }];
181
+ }
182
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
183
+ return segments.map((segment) => [
184
+ objIntToString(segment.start),
185
+ objIntToString(segment.relationship),
186
+ objIntToString(segment.end),
187
+ ].filter((part) => part !== null));
188
+ };
@@ -11,8 +11,9 @@ export declare class Neo4jGraph {
11
11
  constructor({ url, username, password, database, }: Neo4jGraphConfig);
12
12
  static initialize(config: Neo4jGraphConfig): Promise<Neo4jGraph>;
13
13
  getSchema(): string;
14
- query(query: string, params?: any): Promise<any[]>;
14
+ query(query: string, params?: any): Promise<any[] | undefined>;
15
15
  verifyConnectivity(): Promise<void>;
16
16
  refreshSchema(): Promise<void>;
17
+ close(): Promise<void>;
17
18
  }
18
19
  export {};