langchain 0.0.177 → 0.0.179

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 (73) hide show
  1. package/chains/combine_documents/reduce.cjs +1 -0
  2. package/chains/combine_documents/reduce.d.ts +1 -0
  3. package/chains/combine_documents/reduce.js +1 -0
  4. package/chat_models/iflytek_xinghuo/web.cjs +1 -0
  5. package/chat_models/iflytek_xinghuo/web.d.ts +1 -0
  6. package/chat_models/iflytek_xinghuo/web.js +1 -0
  7. package/chat_models/iflytek_xinghuo.cjs +1 -0
  8. package/chat_models/iflytek_xinghuo.d.ts +1 -0
  9. package/chat_models/iflytek_xinghuo.js +1 -0
  10. package/dist/cache/base.d.ts +1 -1
  11. package/dist/callbacks/index.d.ts +1 -1
  12. package/dist/chains/combine_documents/reduce.cjs +67 -0
  13. package/dist/chains/combine_documents/reduce.d.ts +28 -0
  14. package/dist/chains/combine_documents/reduce.js +62 -0
  15. package/dist/chat_models/cloudflare_workersai.cjs +70 -24
  16. package/dist/chat_models/cloudflare_workersai.d.ts +6 -2
  17. package/dist/chat_models/cloudflare_workersai.js +71 -25
  18. package/dist/chat_models/iflytek_xinghuo/common.cjs +335 -0
  19. package/dist/chat_models/iflytek_xinghuo/common.d.ts +165 -0
  20. package/dist/chat_models/iflytek_xinghuo/common.js +331 -0
  21. package/dist/chat_models/iflytek_xinghuo/index.cjs +35 -0
  22. package/dist/chat_models/iflytek_xinghuo/index.d.ts +5 -0
  23. package/dist/chat_models/iflytek_xinghuo/index.js +28 -0
  24. package/dist/chat_models/iflytek_xinghuo/web.cjs +30 -0
  25. package/dist/chat_models/iflytek_xinghuo/web.d.ts +5 -0
  26. package/dist/chat_models/iflytek_xinghuo/web.js +26 -0
  27. package/dist/graphs/neo4j_graph.cjs +36 -5
  28. package/dist/graphs/neo4j_graph.js +14 -3
  29. package/dist/llms/cloudflare_workersai.cjs +59 -13
  30. package/dist/llms/cloudflare_workersai.d.ts +9 -3
  31. package/dist/llms/cloudflare_workersai.js +59 -13
  32. package/dist/load/import_constants.cjs +2 -0
  33. package/dist/load/import_constants.js +2 -0
  34. package/dist/load/import_map.cjs +4 -2
  35. package/dist/load/import_map.d.ts +2 -0
  36. package/dist/load/import_map.js +2 -0
  37. package/dist/output_parsers/json.cjs +77 -0
  38. package/dist/output_parsers/json.d.ts +1 -0
  39. package/dist/output_parsers/json.js +73 -0
  40. package/dist/output_parsers/openai_functions.cjs +37 -2
  41. package/dist/output_parsers/openai_functions.d.ts +10 -5
  42. package/dist/output_parsers/openai_functions.js +38 -3
  43. package/dist/prompts/chat.cjs +8 -0
  44. package/dist/prompts/chat.d.ts +5 -0
  45. package/dist/prompts/chat.js +8 -0
  46. package/dist/schema/index.cjs +33 -1
  47. package/dist/schema/index.d.ts +3 -1
  48. package/dist/schema/index.js +31 -0
  49. package/dist/schema/output_parser.cjs +63 -3
  50. package/dist/schema/output_parser.d.ts +16 -1
  51. package/dist/schema/output_parser.js +59 -0
  52. package/dist/schema/prompt_template.cjs +33 -0
  53. package/dist/schema/prompt_template.d.ts +12 -0
  54. package/dist/schema/prompt_template.js +29 -0
  55. package/dist/storage/convex.d.ts +21 -0
  56. package/dist/stores/message/convex.d.ts +21 -0
  57. package/dist/util/event-source-parse.cjs +20 -1
  58. package/dist/util/event-source-parse.d.ts +2 -0
  59. package/dist/util/event-source-parse.js +18 -0
  60. package/dist/util/fast-json-patch/index.cjs +1 -0
  61. package/dist/util/fast-json-patch/index.d.ts +1 -0
  62. package/dist/util/fast-json-patch/index.js +1 -0
  63. package/dist/util/fast-json-patch/src/duplex.cjs +237 -0
  64. package/dist/util/fast-json-patch/src/duplex.d.ts +23 -0
  65. package/dist/util/fast-json-patch/src/duplex.js +230 -0
  66. package/dist/util/iflytek_websocket_stream.cjs +81 -0
  67. package/dist/util/iflytek_websocket_stream.d.ts +27 -0
  68. package/dist/util/iflytek_websocket_stream.js +77 -0
  69. package/dist/vectorstores/convex.d.ts +21 -0
  70. package/package.json +38 -1
  71. package/schema/prompt_template.cjs +1 -0
  72. package/schema/prompt_template.d.ts +1 -0
  73. package/schema/prompt_template.js +1 -0
@@ -0,0 +1,331 @@
1
+ import { AIMessage, ChatMessage, } from "../../schema/index.js";
2
+ import { getEnvironmentVariable } from "../../util/env.js";
3
+ import { IterableReadableStream } from "../../util/stream.js";
4
+ import { BaseChatModel } from "../base.js";
5
+ /**
6
+ * Function that extracts the custom role of a generic chat message.
7
+ * @param message Chat message from which to extract the custom role.
8
+ * @returns The custom role of the chat message.
9
+ */
10
+ function extractGenericMessageCustomRole(message) {
11
+ if (message.role !== "assistant" && message.role !== "user") {
12
+ console.warn(`Unknown message role: ${message.role}`);
13
+ }
14
+ return message.role;
15
+ }
16
+ /**
17
+ * Function that converts a base message to a Xinghuo message role.
18
+ * @param message Base message to convert.
19
+ * @returns The Xinghuo message role.
20
+ */
21
+ function messageToXinghuoRole(message) {
22
+ const type = message._getType();
23
+ switch (type) {
24
+ case "ai":
25
+ return "assistant";
26
+ case "human":
27
+ return "user";
28
+ case "system":
29
+ throw new Error("System messages should not be here");
30
+ case "function":
31
+ throw new Error("Function messages not supported");
32
+ case "generic": {
33
+ if (!ChatMessage.isInstance(message))
34
+ throw new Error("Invalid generic chat message");
35
+ return extractGenericMessageCustomRole(message);
36
+ }
37
+ default:
38
+ throw new Error(`Unknown message type: ${type}`);
39
+ }
40
+ }
41
+ /**
42
+ * Wrapper around IflytekXingHuo large language models that use the Chat endpoint.
43
+ *
44
+ * To use you should have the `IFLYTEK_API_KEY` and `IFLYTEK_API_SECRET` and `IFLYTEK_APPID`
45
+ * environment variable set.
46
+ *
47
+ * @augments BaseChatModel
48
+ * @augments IflytekXinghuoChatInput
49
+ */
50
+ export class BaseChatIflytekXinghuo extends BaseChatModel {
51
+ static lc_name() {
52
+ return "ChatIflytekXinghuo";
53
+ }
54
+ get callKeys() {
55
+ return ["stop", "signal", "options"];
56
+ }
57
+ get lc_secrets() {
58
+ return {
59
+ iflytekApiKey: "IFLYTEK_API_KEY",
60
+ iflytekApiSecret: "IFLYTEK_API_SECRET",
61
+ };
62
+ }
63
+ get lc_aliases() {
64
+ return undefined;
65
+ }
66
+ constructor(fields) {
67
+ super(fields ?? {});
68
+ Object.defineProperty(this, "lc_serializable", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: true
73
+ });
74
+ Object.defineProperty(this, "version", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: "v2.1"
79
+ });
80
+ Object.defineProperty(this, "iflytekAppid", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: void 0
85
+ });
86
+ Object.defineProperty(this, "iflytekApiKey", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: void 0
91
+ });
92
+ Object.defineProperty(this, "iflytekApiSecret", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: void 0
97
+ });
98
+ Object.defineProperty(this, "userId", {
99
+ enumerable: true,
100
+ configurable: true,
101
+ writable: true,
102
+ value: void 0
103
+ });
104
+ Object.defineProperty(this, "apiUrl", {
105
+ enumerable: true,
106
+ configurable: true,
107
+ writable: true,
108
+ value: void 0
109
+ });
110
+ Object.defineProperty(this, "domain", {
111
+ enumerable: true,
112
+ configurable: true,
113
+ writable: true,
114
+ value: void 0
115
+ });
116
+ Object.defineProperty(this, "temperature", {
117
+ enumerable: true,
118
+ configurable: true,
119
+ writable: true,
120
+ value: 0.5
121
+ });
122
+ Object.defineProperty(this, "max_tokens", {
123
+ enumerable: true,
124
+ configurable: true,
125
+ writable: true,
126
+ value: 2048
127
+ });
128
+ Object.defineProperty(this, "top_k", {
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true,
132
+ value: 4
133
+ });
134
+ Object.defineProperty(this, "streaming", {
135
+ enumerable: true,
136
+ configurable: true,
137
+ writable: true,
138
+ value: false
139
+ });
140
+ const iflytekAppid = fields?.iflytekAppid ?? getEnvironmentVariable("IFLYTEK_APPID");
141
+ if (!iflytekAppid) {
142
+ throw new Error("Iflytek APPID not found");
143
+ }
144
+ else {
145
+ this.iflytekAppid = iflytekAppid;
146
+ }
147
+ const iflytekApiKey = fields?.iflytekApiKey ?? getEnvironmentVariable("IFLYTEK_API_KEY");
148
+ if (!iflytekApiKey) {
149
+ throw new Error("Iflytek API key not found");
150
+ }
151
+ else {
152
+ this.iflytekApiKey = iflytekApiKey;
153
+ }
154
+ const iflytekApiSecret = fields?.iflytekApiSecret ?? getEnvironmentVariable("IFLYTEK_API_SECRET");
155
+ if (!iflytekApiSecret) {
156
+ throw new Error("Iflytek API secret not found");
157
+ }
158
+ else {
159
+ this.iflytekApiSecret = iflytekApiSecret;
160
+ }
161
+ this.userId = fields?.userId ?? this.userId;
162
+ this.streaming = fields?.streaming ?? this.streaming;
163
+ this.temperature = fields?.temperature ?? this.temperature;
164
+ this.max_tokens = fields?.max_tokens ?? this.max_tokens;
165
+ this.top_k = fields?.top_k ?? this.top_k;
166
+ this.version = fields?.version ?? this.version;
167
+ if (["v1.1", "v2.1", "v3.1"].includes(this.version)) {
168
+ switch (this.version) {
169
+ case "v1.1":
170
+ this.domain = "general";
171
+ break;
172
+ case "v2.1":
173
+ this.domain = "generalv2";
174
+ break;
175
+ case "v3.1":
176
+ this.domain = "generalv3";
177
+ break;
178
+ default:
179
+ this.domain = "generalv2";
180
+ }
181
+ this.apiUrl = `wss://spark-api.xf-yun.com/${this.version}/chat`;
182
+ }
183
+ else {
184
+ throw new Error(`Invalid model version: ${this.version}`);
185
+ }
186
+ }
187
+ /**
188
+ * Get the identifying parameters for the model
189
+ */
190
+ identifyingParams() {
191
+ return {
192
+ version: this.version,
193
+ ...this.invocationParams(),
194
+ };
195
+ }
196
+ /**
197
+ * Get the parameters used to invoke the model
198
+ */
199
+ invocationParams() {
200
+ return {
201
+ streaming: this.streaming,
202
+ temperature: this.temperature,
203
+ top_k: this.top_k,
204
+ };
205
+ }
206
+ async completion(request, stream, signal) {
207
+ const webSocketStream = await this.openWebSocketStream({
208
+ signal,
209
+ });
210
+ const connection = await webSocketStream.connection;
211
+ const header = {
212
+ app_id: this.iflytekAppid,
213
+ uid: this.userId,
214
+ };
215
+ const parameter = {
216
+ chat: {
217
+ domain: this.domain,
218
+ temperature: request.temperature ?? this.temperature,
219
+ max_tokens: request.max_tokens ?? this.max_tokens,
220
+ top_k: request.top_k ?? this.top_k,
221
+ },
222
+ };
223
+ const payload = {
224
+ message: {
225
+ text: request.messages,
226
+ },
227
+ };
228
+ const message = JSON.stringify({
229
+ header,
230
+ parameter,
231
+ payload,
232
+ });
233
+ const { writable, readable } = connection;
234
+ const writer = writable.getWriter();
235
+ await writer.write(message);
236
+ const streams = IterableReadableStream.fromReadableStream(readable);
237
+ if (stream) {
238
+ return streams;
239
+ }
240
+ else {
241
+ let response = { result: "" };
242
+ for await (const chunk of streams) {
243
+ const data = JSON.parse(chunk);
244
+ const { header, payload } = data;
245
+ if (header.code === 0) {
246
+ if (header.status === 0) {
247
+ response.result = payload.choices?.text[0]?.content ?? "";
248
+ }
249
+ else if (header.status === 1) {
250
+ response.result += payload.choices?.text[0]?.content ?? "";
251
+ }
252
+ else if (header.status === 2) {
253
+ response = { ...response, usage: payload.usage?.text };
254
+ break;
255
+ }
256
+ }
257
+ else {
258
+ break;
259
+ }
260
+ }
261
+ void streams.cancel();
262
+ void webSocketStream.close();
263
+ return response;
264
+ }
265
+ }
266
+ async _generate(messages, options, runManager) {
267
+ const tokenUsage = {};
268
+ const params = this.invocationParams();
269
+ const messagesMapped = messages.map((message) => ({
270
+ role: messageToXinghuoRole(message),
271
+ content: message.content,
272
+ }));
273
+ const data = params.streaming
274
+ ? await (async () => {
275
+ const streams = await this.completion({ messages: messagesMapped, ...params }, true, options.signal);
276
+ let response = { result: "" };
277
+ for await (const chunk of streams) {
278
+ const data = JSON.parse(chunk);
279
+ const { header, payload } = data;
280
+ if (header.code === 0) {
281
+ if (header.status === 0) {
282
+ response.result = payload.choices?.text[0]?.content ?? "";
283
+ }
284
+ else if (header.status === 1) {
285
+ response.result += payload.choices?.text[0]?.content ?? "";
286
+ }
287
+ else if (header.status === 2) {
288
+ response = { ...response, usage: payload.usage?.text };
289
+ break;
290
+ }
291
+ void runManager?.handleLLMNewToken(payload.choices?.text[0]?.content);
292
+ }
293
+ else {
294
+ break;
295
+ }
296
+ }
297
+ void streams.cancel();
298
+ return response;
299
+ })()
300
+ : await this.completion({ messages: messagesMapped, ...params }, false, options.signal);
301
+ const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage ?? {};
302
+ if (completionTokens) {
303
+ tokenUsage.completionTokens =
304
+ (tokenUsage.completionTokens ?? 0) + completionTokens;
305
+ }
306
+ if (promptTokens) {
307
+ tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;
308
+ }
309
+ if (totalTokens) {
310
+ tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;
311
+ }
312
+ const generations = [];
313
+ const text = data.result ?? "";
314
+ generations.push({
315
+ text,
316
+ message: new AIMessage(text),
317
+ });
318
+ return {
319
+ generations,
320
+ llmOutput: { tokenUsage },
321
+ };
322
+ }
323
+ /** @ignore */
324
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
325
+ _combineLLMOutput() {
326
+ return [];
327
+ }
328
+ _llmType() {
329
+ return "iflytek_xinghuo";
330
+ }
331
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ChatIflytekXinghuo = void 0;
7
+ const ws_1 = __importDefault(require("ws"));
8
+ const common_js_1 = require("./common.cjs");
9
+ const iflytek_websocket_stream_js_1 = require("../../util/iflytek_websocket_stream.cjs");
10
+ class WebSocketStream extends iflytek_websocket_stream_js_1.BaseWebSocketStream {
11
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
12
+ // @ts-ignore
13
+ openWebSocket(url, options) {
14
+ return new ws_1.default(url, options.protocols ?? []);
15
+ }
16
+ }
17
+ class ChatIflytekXinghuo extends common_js_1.BaseChatIflytekXinghuo {
18
+ async openWebSocketStream(options) {
19
+ const host = "spark-api.xf-yun.com";
20
+ const date = new Date().toUTCString();
21
+ const url = `GET /${this.version}/chat HTTP/1.1`;
22
+ const { createHmac } = await import("node:crypto");
23
+ const hash = createHmac("sha256", this.iflytekApiSecret)
24
+ .update(`host: ${host}\ndate: ${date}\n${url}`)
25
+ .digest("base64");
26
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
27
+ const authorization = Buffer.from(authorization_origin).toString("base64");
28
+ let authWebSocketUrl = this.apiUrl;
29
+ authWebSocketUrl += `?authorization=${authorization}`;
30
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
31
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
32
+ return new WebSocketStream(authWebSocketUrl, options);
33
+ }
34
+ }
35
+ exports.ChatIflytekXinghuo = ChatIflytekXinghuo;
@@ -0,0 +1,5 @@
1
+ import { BaseChatIflytekXinghuo } from "./common.js";
2
+ import { WebSocketStreamOptions } from "../../util/iflytek_websocket_stream.js";
3
+ export declare class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
4
+ openWebSocketStream<WebSocketStream>(options: WebSocketStreamOptions): Promise<WebSocketStream>;
5
+ }
@@ -0,0 +1,28 @@
1
+ import WebSocket from "ws";
2
+ import { BaseChatIflytekXinghuo } from "./common.js";
3
+ import { BaseWebSocketStream, } from "../../util/iflytek_websocket_stream.js";
4
+ class WebSocketStream extends BaseWebSocketStream {
5
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
6
+ // @ts-ignore
7
+ openWebSocket(url, options) {
8
+ return new WebSocket(url, options.protocols ?? []);
9
+ }
10
+ }
11
+ export class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
12
+ async openWebSocketStream(options) {
13
+ const host = "spark-api.xf-yun.com";
14
+ const date = new Date().toUTCString();
15
+ const url = `GET /${this.version}/chat HTTP/1.1`;
16
+ const { createHmac } = await import("node:crypto");
17
+ const hash = createHmac("sha256", this.iflytekApiSecret)
18
+ .update(`host: ${host}\ndate: ${date}\n${url}`)
19
+ .digest("base64");
20
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
21
+ const authorization = Buffer.from(authorization_origin).toString("base64");
22
+ let authWebSocketUrl = this.apiUrl;
23
+ authWebSocketUrl += `?authorization=${authorization}`;
24
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
25
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
26
+ return new WebSocketStream(authWebSocketUrl, options);
27
+ }
28
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatIflytekXinghuo = void 0;
4
+ const common_js_1 = require("./common.cjs");
5
+ const iflytek_websocket_stream_js_1 = require("../../util/iflytek_websocket_stream.cjs");
6
+ class WebSocketStream extends iflytek_websocket_stream_js_1.BaseWebSocketStream {
7
+ openWebSocket(url, options) {
8
+ return new WebSocket(url, options.protocols ?? []);
9
+ }
10
+ }
11
+ class ChatIflytekXinghuo extends common_js_1.BaseChatIflytekXinghuo {
12
+ async openWebSocketStream(options) {
13
+ const host = "spark-api.xf-yun.com";
14
+ const date = new Date().toUTCString();
15
+ const url = `GET /${this.version}/chat HTTP/1.1`;
16
+ const keyBuffer = new TextEncoder().encode(this.iflytekApiSecret);
17
+ const dataBuffer = new TextEncoder().encode(`host: ${host}\ndate: ${date}\n${url}`);
18
+ const cryptoKey = await crypto.subtle.importKey("raw", keyBuffer, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
19
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, dataBuffer);
20
+ const hash = window.btoa(String.fromCharCode(...new Uint8Array(signature)));
21
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
22
+ const authorization = window.btoa(authorization_origin);
23
+ let authWebSocketUrl = this.apiUrl;
24
+ authWebSocketUrl += `?authorization=${authorization}`;
25
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
26
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
27
+ return new WebSocketStream(authWebSocketUrl, options);
28
+ }
29
+ }
30
+ exports.ChatIflytekXinghuo = ChatIflytekXinghuo;
@@ -0,0 +1,5 @@
1
+ import { BaseChatIflytekXinghuo } from "./common.js";
2
+ import { WebSocketStreamOptions } from "../../util/iflytek_websocket_stream.js";
3
+ export declare class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
4
+ openWebSocketStream<WebSocketStream>(options: WebSocketStreamOptions): Promise<WebSocketStream>;
5
+ }
@@ -0,0 +1,26 @@
1
+ import { BaseChatIflytekXinghuo } from "./common.js";
2
+ import { BaseWebSocketStream, } from "../../util/iflytek_websocket_stream.js";
3
+ class WebSocketStream extends BaseWebSocketStream {
4
+ openWebSocket(url, options) {
5
+ return new WebSocket(url, options.protocols ?? []);
6
+ }
7
+ }
8
+ export class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
9
+ async openWebSocketStream(options) {
10
+ const host = "spark-api.xf-yun.com";
11
+ const date = new Date().toUTCString();
12
+ const url = `GET /${this.version}/chat HTTP/1.1`;
13
+ const keyBuffer = new TextEncoder().encode(this.iflytekApiSecret);
14
+ const dataBuffer = new TextEncoder().encode(`host: ${host}\ndate: ${date}\n${url}`);
15
+ const cryptoKey = await crypto.subtle.importKey("raw", keyBuffer, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
16
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, dataBuffer);
17
+ const hash = window.btoa(String.fromCharCode(...new Uint8Array(signature)));
18
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
19
+ const authorization = window.btoa(authorization_origin);
20
+ let authWebSocketUrl = this.apiUrl;
21
+ authWebSocketUrl += `?authorization=${authorization}`;
22
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
23
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
24
+ return new WebSocketStream(authWebSocketUrl, options);
25
+ }
26
+ }
@@ -1,10 +1,30 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
4
24
  };
5
25
  Object.defineProperty(exports, "__esModule", { value: true });
6
26
  exports.Neo4jGraph = void 0;
7
- const neo4j_driver_1 = __importDefault(require("neo4j-driver"));
27
+ const neo4j_driver_1 = __importStar(require("neo4j-driver"));
8
28
  /**
9
29
  * @security *Security note*: Make sure that the database connection uses credentials
10
30
  * that are narrowly-scoped to only include necessary permissions.
@@ -61,7 +81,12 @@ class Neo4jGraph {
61
81
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
82
  }
63
83
  catch (error) {
64
- throw new Error(`Error: ${error.message}`);
84
+ const message = [
85
+ "Could not use APOC procedures.",
86
+ "Please ensure the APOC plugin is installed in Neo4j and that",
87
+ "'apoc.meta.data()' is allowed in Neo4j configuration",
88
+ ].join("\n");
89
+ throw new Error(message);
65
90
  }
66
91
  finally {
67
92
  console.log("Schema refreshed successfully.");
@@ -78,9 +103,15 @@ class Neo4jGraph {
78
103
  database: this.database,
79
104
  });
80
105
  return toObjects(result.records);
106
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
107
  }
82
108
  catch (error) {
83
- // ignore errors
109
+ if (
110
+ // eslint-disable-next-line
111
+ error instanceof neo4j_driver_1.Neo4jError &&
112
+ error.code === "Neo.ClientError.Procedure.ProcedureNotFound") {
113
+ throw new Error("Procedure not found in Neo4j.");
114
+ }
84
115
  }
85
116
  return undefined;
86
117
  }
@@ -1,4 +1,4 @@
1
- import neo4j from "neo4j-driver";
1
+ import neo4j, { Neo4jError } from "neo4j-driver";
2
2
  /**
3
3
  * @security *Security note*: Make sure that the database connection uses credentials
4
4
  * that are narrowly-scoped to only include necessary permissions.
@@ -55,7 +55,12 @@ export class Neo4jGraph {
55
55
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
56
  }
57
57
  catch (error) {
58
- throw new Error(`Error: ${error.message}`);
58
+ const message = [
59
+ "Could not use APOC procedures.",
60
+ "Please ensure the APOC plugin is installed in Neo4j and that",
61
+ "'apoc.meta.data()' is allowed in Neo4j configuration",
62
+ ].join("\n");
63
+ throw new Error(message);
59
64
  }
60
65
  finally {
61
66
  console.log("Schema refreshed successfully.");
@@ -72,9 +77,15 @@ export class Neo4jGraph {
72
77
  database: this.database,
73
78
  });
74
79
  return toObjects(result.records);
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
81
  }
76
82
  catch (error) {
77
- // ignore errors
83
+ if (
84
+ // eslint-disable-next-line
85
+ error instanceof Neo4jError &&
86
+ error.code === "Neo.ClientError.Procedure.ProcedureNotFound") {
87
+ throw new Error("Procedure not found in Neo4j.");
88
+ }
78
89
  }
79
90
  return undefined;
80
91
  }
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CloudflareWorkersAI = void 0;
4
4
  const base_js_1 = require("./base.cjs");
5
5
  const env_js_1 = require("../util/env.cjs");
6
+ const index_js_1 = require("../schema/index.cjs");
7
+ const event_source_parse_js_1 = require("../util/event-source-parse.cjs");
6
8
  /**
7
9
  * Class representing the CloudflareWorkersAI language model. It extends the LLM (Large
8
10
  * Language Model) class, providing a standard interface for interacting
@@ -38,6 +40,12 @@ class CloudflareWorkersAI extends base_js_1.LLM {
38
40
  writable: true,
39
41
  value: void 0
40
42
  });
43
+ Object.defineProperty(this, "streaming", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: false
48
+ });
41
49
  Object.defineProperty(this, "lc_serializable", {
42
50
  enumerable: true,
43
51
  configurable: true,
@@ -45,6 +53,7 @@ class CloudflareWorkersAI extends base_js_1.LLM {
45
53
  value: true
46
54
  });
47
55
  this.model = fields?.model ?? this.model;
56
+ this.streaming = fields?.streaming ?? this.streaming;
48
57
  this.cloudflareAccountId =
49
58
  fields?.cloudflareAccountId ??
50
59
  (0, env_js_1.getEnvironmentVariable)("CLOUDFLARE_ACCOUNT_ID");
@@ -87,23 +96,15 @@ class CloudflareWorkersAI extends base_js_1.LLM {
87
96
  _llmType() {
88
97
  return "cloudflare";
89
98
  }
90
- /** Call out to CloudflareWorkersAI's complete endpoint.
91
- Args:
92
- prompt: The prompt to pass into the model.
93
- Returns:
94
- The string generated by the model.
95
- Example:
96
- let response = CloudflareWorkersAI.call("Tell me a joke.");
97
- */
98
- async _call(prompt, options) {
99
+ async _request(prompt, options, stream) {
99
100
  this.validateEnvironment();
100
101
  const url = `${this.baseUrl}/${this.model}`;
101
102
  const headers = {
102
103
  Authorization: `Bearer ${this.cloudflareApiToken}`,
103
104
  "Content-Type": "application/json",
104
105
  };
105
- const data = { prompt };
106
- const responseData = await this.caller.call(async () => {
106
+ const data = { prompt, stream };
107
+ return this.caller.call(async () => {
107
108
  const response = await fetch(url, {
108
109
  method: "POST",
109
110
  headers,
@@ -116,9 +117,54 @@ class CloudflareWorkersAI extends base_js_1.LLM {
116
117
  error.response = response;
117
118
  throw error;
118
119
  }
119
- return response.json();
120
+ return response;
120
121
  });
121
- return responseData.result.response;
122
+ }
123
+ async *_streamResponseChunks(prompt, options, runManager) {
124
+ const response = await this._request(prompt, options, true);
125
+ if (!response.body) {
126
+ throw new Error("Empty response from Cloudflare. Please try again.");
127
+ }
128
+ const stream = (0, event_source_parse_js_1.convertEventStreamToIterableReadableDataStream)(response.body);
129
+ for await (const chunk of stream) {
130
+ if (chunk !== "[DONE]") {
131
+ const parsedChunk = JSON.parse(chunk);
132
+ const generationChunk = new index_js_1.GenerationChunk({
133
+ text: parsedChunk.response,
134
+ });
135
+ yield generationChunk;
136
+ // eslint-disable-next-line no-void
137
+ void runManager?.handleLLMNewToken(generationChunk.text ?? "");
138
+ }
139
+ }
140
+ }
141
+ /** Call out to CloudflareWorkersAI's complete endpoint.
142
+ Args:
143
+ prompt: The prompt to pass into the model.
144
+ Returns:
145
+ The string generated by the model.
146
+ Example:
147
+ let response = CloudflareWorkersAI.call("Tell me a joke.");
148
+ */
149
+ async _call(prompt, options, runManager) {
150
+ if (!this.streaming) {
151
+ const response = await this._request(prompt, options);
152
+ const responseData = await response.json();
153
+ return responseData.result.response;
154
+ }
155
+ else {
156
+ const stream = this._streamResponseChunks(prompt, options, runManager);
157
+ let finalResult;
158
+ for await (const chunk of stream) {
159
+ if (finalResult === undefined) {
160
+ finalResult = chunk;
161
+ }
162
+ else {
163
+ finalResult = finalResult.concat(chunk);
164
+ }
165
+ }
166
+ return finalResult?.text ?? "";
167
+ }
122
168
  }
123
169
  }
124
170
  exports.CloudflareWorkersAI = CloudflareWorkersAI;