langchain 0.0.166 → 0.0.168

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 (101) hide show
  1. package/README.md +4 -4
  2. package/chat_models/cloudflare_workersai.cjs +1 -0
  3. package/chat_models/cloudflare_workersai.d.ts +1 -0
  4. package/chat_models/cloudflare_workersai.js +1 -0
  5. package/chat_models/fake.cjs +1 -0
  6. package/chat_models/fake.d.ts +1 -0
  7. package/chat_models/fake.js +1 -0
  8. package/dist/agents/chat/index.cjs +3 -2
  9. package/dist/agents/chat/index.d.ts +3 -0
  10. package/dist/agents/chat/index.js +3 -2
  11. package/dist/chat_models/cloudflare_workersai.cjs +140 -0
  12. package/dist/chat_models/cloudflare_workersai.d.ts +46 -0
  13. package/dist/chat_models/cloudflare_workersai.js +136 -0
  14. package/dist/chat_models/fake.cjs +101 -0
  15. package/dist/chat_models/fake.d.ts +36 -0
  16. package/dist/chat_models/fake.js +97 -0
  17. package/dist/embeddings/bedrock.cjs +43 -22
  18. package/dist/embeddings/bedrock.d.ts +11 -4
  19. package/dist/embeddings/bedrock.js +43 -22
  20. package/dist/llms/cloudflare_workersai.cjs +117 -0
  21. package/dist/llms/cloudflare_workersai.d.ts +49 -0
  22. package/dist/llms/cloudflare_workersai.js +113 -0
  23. package/dist/llms/fake.cjs +82 -0
  24. package/dist/llms/fake.d.ts +31 -0
  25. package/dist/llms/fake.js +78 -0
  26. package/dist/llms/sagemaker_endpoint.cjs +9 -7
  27. package/dist/llms/sagemaker_endpoint.d.ts +3 -3
  28. package/dist/llms/sagemaker_endpoint.js +9 -7
  29. package/dist/llms/yandex.cjs +100 -0
  30. package/dist/llms/yandex.d.ts +40 -0
  31. package/dist/llms/yandex.js +96 -0
  32. package/dist/load/import_constants.cjs +4 -0
  33. package/dist/load/import_constants.js +4 -0
  34. package/dist/load/import_map.cjs +8 -2
  35. package/dist/load/import_map.d.ts +6 -0
  36. package/dist/load/import_map.js +6 -0
  37. package/dist/retrievers/multi_vector.d.ts +3 -3
  38. package/dist/retrievers/parent_document.cjs +6 -16
  39. package/dist/retrievers/parent_document.d.ts +5 -12
  40. package/dist/retrievers/parent_document.js +6 -16
  41. package/dist/schema/storage.d.ts +28 -1
  42. package/dist/storage/encoder_backed.cjs +14 -2
  43. package/dist/storage/encoder_backed.d.ts +2 -0
  44. package/dist/storage/encoder_backed.js +12 -1
  45. package/dist/storage/in_memory.cjs +1 -1
  46. package/dist/storage/in_memory.js +1 -1
  47. package/dist/storage/ioredis.cjs +4 -4
  48. package/dist/storage/ioredis.js +4 -4
  49. package/dist/storage/vercel_kv.cjs +146 -0
  50. package/dist/storage/vercel_kv.d.ts +46 -0
  51. package/dist/storage/vercel_kv.js +142 -0
  52. package/dist/stores/doc/in_memory.cjs +13 -0
  53. package/dist/stores/doc/in_memory.d.ts +6 -1
  54. package/dist/stores/doc/in_memory.js +13 -0
  55. package/dist/util/axios-fetch-adapter.cjs +1 -1
  56. package/dist/util/axios-fetch-adapter.js +1 -1
  57. package/dist/util/env.cjs +1 -1
  58. package/dist/util/env.js +1 -1
  59. package/dist/util/event-source-parse.cjs +1 -1
  60. package/dist/util/event-source-parse.js +1 -1
  61. package/dist/vectorstores/cassandra.cjs +4 -2
  62. package/dist/vectorstores/cassandra.js +4 -2
  63. package/dist/vectorstores/closevector/common.cjs +128 -0
  64. package/dist/vectorstores/closevector/common.d.ts +82 -0
  65. package/dist/vectorstores/closevector/common.js +124 -0
  66. package/dist/vectorstores/closevector/node.cjs +109 -0
  67. package/dist/vectorstores/closevector/node.d.ts +83 -0
  68. package/dist/vectorstores/closevector/node.js +105 -0
  69. package/dist/vectorstores/closevector/web.cjs +109 -0
  70. package/dist/vectorstores/closevector/web.d.ts +80 -0
  71. package/dist/vectorstores/closevector/web.js +105 -0
  72. package/dist/vectorstores/elasticsearch.cjs +3 -1
  73. package/dist/vectorstores/elasticsearch.js +3 -1
  74. package/dist/vectorstores/neo4j_vector.cjs +578 -0
  75. package/dist/vectorstores/neo4j_vector.d.ts +61 -0
  76. package/dist/vectorstores/neo4j_vector.js +548 -0
  77. package/llms/cloudflare_workersai.cjs +1 -0
  78. package/llms/cloudflare_workersai.d.ts +1 -0
  79. package/llms/cloudflare_workersai.js +1 -0
  80. package/llms/fake.cjs +1 -0
  81. package/llms/fake.d.ts +1 -0
  82. package/llms/fake.js +1 -0
  83. package/llms/yandex.cjs +1 -0
  84. package/llms/yandex.d.ts +1 -0
  85. package/llms/yandex.js +1 -0
  86. package/package.json +105 -5
  87. package/storage/encoder_backed.cjs +1 -0
  88. package/storage/encoder_backed.d.ts +1 -0
  89. package/storage/encoder_backed.js +1 -0
  90. package/storage/vercel_kv.cjs +1 -0
  91. package/storage/vercel_kv.d.ts +1 -0
  92. package/storage/vercel_kv.js +1 -0
  93. package/vectorstores/closevector/node.cjs +1 -0
  94. package/vectorstores/closevector/node.d.ts +1 -0
  95. package/vectorstores/closevector/node.js +1 -0
  96. package/vectorstores/closevector/web.cjs +1 -0
  97. package/vectorstores/closevector/web.d.ts +1 -0
  98. package/vectorstores/closevector/web.js +1 -0
  99. package/vectorstores/neo4j_vector.cjs +1 -0
  100. package/vectorstores/neo4j_vector.d.ts +1 -0
  101. package/vectorstores/neo4j_vector.js +1 -0
@@ -22,6 +22,12 @@ class BedrockEmbeddings extends base_js_1.Embeddings {
22
22
  writable: true,
23
23
  value: void 0
24
24
  });
25
+ Object.defineProperty(this, "batchSize", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: 512
30
+ });
25
31
  this.model = fields?.model ?? "amazon.titan-embed-text-v1";
26
32
  this.client =
27
33
  fields?.client ??
@@ -30,24 +36,40 @@ class BedrockEmbeddings extends base_js_1.Embeddings {
30
36
  credentials: fields?.credentials,
31
37
  });
32
38
  }
39
+ /**
40
+ * Protected method to make a request to the Bedrock API to generate
41
+ * embeddings. Handles the retry logic and returns the response from the
42
+ * API.
43
+ * @param request Request to send to the Bedrock API.
44
+ * @returns Promise that resolves to the response from the API.
45
+ */
33
46
  async _embedText(text) {
34
- // replace newlines, which can negatively affect performance.
35
- const cleanedText = text.replace(/\n/g, " ");
36
- const res = await this.client.send(new client_bedrock_runtime_1.InvokeModelCommand({
37
- modelId: this.model,
38
- body: JSON.stringify({
39
- inputText: cleanedText,
40
- }),
41
- contentType: "application/json",
42
- accept: "application/json",
43
- }));
44
- try {
45
- const body = new TextDecoder().decode(res.body);
46
- return JSON.parse(body).embedding;
47
- }
48
- catch (e) {
49
- throw new Error("An invalid response was returned by Bedrock.");
50
- }
47
+ return this.caller.call(async () => {
48
+ try {
49
+ // replace newlines, which can negatively affect performance.
50
+ const cleanedText = text.replace(/\n/g, " ");
51
+ const res = await this.client.send(new client_bedrock_runtime_1.InvokeModelCommand({
52
+ modelId: this.model,
53
+ body: JSON.stringify({
54
+ inputText: cleanedText,
55
+ }),
56
+ contentType: "application/json",
57
+ accept: "application/json",
58
+ }));
59
+ const body = new TextDecoder().decode(res.body);
60
+ return JSON.parse(body).embedding;
61
+ }
62
+ catch (e) {
63
+ console.error({
64
+ error: e,
65
+ });
66
+ // eslint-disable-next-line no-instanceof/no-instanceof
67
+ if (e instanceof Error) {
68
+ throw new Error(`An error occurred while embedding documents with Bedrock: ${e.message}`);
69
+ }
70
+ throw new Error("An error occurred while embedding documents with Bedrock");
71
+ }
72
+ });
51
73
  }
52
74
  /**
53
75
  * Method that takes a document as input and returns a promise that
@@ -60,13 +82,12 @@ class BedrockEmbeddings extends base_js_1.Embeddings {
60
82
  return this.caller.callWithOptions({}, this._embedText.bind(this), document);
61
83
  }
62
84
  /**
63
- * Method that takes an array of documents as input and returns a promise
64
- * that resolves to a 2D array of embeddings for each document. It calls
65
- * the _embedText method for each document in the array.
66
- * @param documents Array of documents for which to generate embeddings.
85
+ * Method to generate embeddings for an array of texts. Calls _embedText
86
+ * method which batches and handles retry logic when calling the AWS Bedrock API.
87
+ * @param documents Array of texts for which to generate embeddings.
67
88
  * @returns Promise that resolves to a 2D array of embeddings for each input document.
68
89
  */
69
- embedDocuments(documents) {
90
+ async embedDocuments(documents) {
70
91
  return Promise.all(documents.map((document) => this._embedText(document)));
71
92
  }
72
93
  }
@@ -26,7 +26,15 @@ export interface BedrockEmbeddingsParams extends EmbeddingsParams {
26
26
  export declare class BedrockEmbeddings extends Embeddings implements BedrockEmbeddingsParams {
27
27
  model: string;
28
28
  client: BedrockRuntimeClient;
29
+ batchSize: number;
29
30
  constructor(fields?: BedrockEmbeddingsParams);
31
+ /**
32
+ * Protected method to make a request to the Bedrock API to generate
33
+ * embeddings. Handles the retry logic and returns the response from the
34
+ * API.
35
+ * @param request Request to send to the Bedrock API.
36
+ * @returns Promise that resolves to the response from the API.
37
+ */
30
38
  protected _embedText(text: string): Promise<number[]>;
31
39
  /**
32
40
  * Method that takes a document as input and returns a promise that
@@ -37,10 +45,9 @@ export declare class BedrockEmbeddings extends Embeddings implements BedrockEmbe
37
45
  */
38
46
  embedQuery(document: string): Promise<number[]>;
39
47
  /**
40
- * Method that takes an array of documents as input and returns a promise
41
- * that resolves to a 2D array of embeddings for each document. It calls
42
- * the _embedText method for each document in the array.
43
- * @param documents Array of documents for which to generate embeddings.
48
+ * Method to generate embeddings for an array of texts. Calls _embedText
49
+ * method which batches and handles retry logic when calling the AWS Bedrock API.
50
+ * @param documents Array of texts for which to generate embeddings.
44
51
  * @returns Promise that resolves to a 2D array of embeddings for each input document.
45
52
  */
46
53
  embedDocuments(documents: string[]): Promise<number[][]>;
@@ -19,6 +19,12 @@ export class BedrockEmbeddings extends Embeddings {
19
19
  writable: true,
20
20
  value: void 0
21
21
  });
22
+ Object.defineProperty(this, "batchSize", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: 512
27
+ });
22
28
  this.model = fields?.model ?? "amazon.titan-embed-text-v1";
23
29
  this.client =
24
30
  fields?.client ??
@@ -27,24 +33,40 @@ export class BedrockEmbeddings extends Embeddings {
27
33
  credentials: fields?.credentials,
28
34
  });
29
35
  }
36
+ /**
37
+ * Protected method to make a request to the Bedrock API to generate
38
+ * embeddings. Handles the retry logic and returns the response from the
39
+ * API.
40
+ * @param request Request to send to the Bedrock API.
41
+ * @returns Promise that resolves to the response from the API.
42
+ */
30
43
  async _embedText(text) {
31
- // replace newlines, which can negatively affect performance.
32
- const cleanedText = text.replace(/\n/g, " ");
33
- const res = await this.client.send(new InvokeModelCommand({
34
- modelId: this.model,
35
- body: JSON.stringify({
36
- inputText: cleanedText,
37
- }),
38
- contentType: "application/json",
39
- accept: "application/json",
40
- }));
41
- try {
42
- const body = new TextDecoder().decode(res.body);
43
- return JSON.parse(body).embedding;
44
- }
45
- catch (e) {
46
- throw new Error("An invalid response was returned by Bedrock.");
47
- }
44
+ return this.caller.call(async () => {
45
+ try {
46
+ // replace newlines, which can negatively affect performance.
47
+ const cleanedText = text.replace(/\n/g, " ");
48
+ const res = await this.client.send(new InvokeModelCommand({
49
+ modelId: this.model,
50
+ body: JSON.stringify({
51
+ inputText: cleanedText,
52
+ }),
53
+ contentType: "application/json",
54
+ accept: "application/json",
55
+ }));
56
+ const body = new TextDecoder().decode(res.body);
57
+ return JSON.parse(body).embedding;
58
+ }
59
+ catch (e) {
60
+ console.error({
61
+ error: e,
62
+ });
63
+ // eslint-disable-next-line no-instanceof/no-instanceof
64
+ if (e instanceof Error) {
65
+ throw new Error(`An error occurred while embedding documents with Bedrock: ${e.message}`);
66
+ }
67
+ throw new Error("An error occurred while embedding documents with Bedrock");
68
+ }
69
+ });
48
70
  }
49
71
  /**
50
72
  * Method that takes a document as input and returns a promise that
@@ -57,13 +79,12 @@ export class BedrockEmbeddings extends Embeddings {
57
79
  return this.caller.callWithOptions({}, this._embedText.bind(this), document);
58
80
  }
59
81
  /**
60
- * Method that takes an array of documents as input and returns a promise
61
- * that resolves to a 2D array of embeddings for each document. It calls
62
- * the _embedText method for each document in the array.
63
- * @param documents Array of documents for which to generate embeddings.
82
+ * Method to generate embeddings for an array of texts. Calls _embedText
83
+ * method which batches and handles retry logic when calling the AWS Bedrock API.
84
+ * @param documents Array of texts for which to generate embeddings.
64
85
  * @returns Promise that resolves to a 2D array of embeddings for each input document.
65
86
  */
66
- embedDocuments(documents) {
87
+ async embedDocuments(documents) {
67
88
  return Promise.all(documents.map((document) => this._embedText(document)));
68
89
  }
69
90
  }
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CloudflareWorkersAI = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ const env_js_1 = require("../util/env.cjs");
6
+ /**
7
+ * Class representing the CloudflareWorkersAI language model. It extends the LLM (Large
8
+ * Language Model) class, providing a standard interface for interacting
9
+ * with the CloudflareWorkersAI language model.
10
+ */
11
+ class CloudflareWorkersAI extends base_js_1.LLM {
12
+ static lc_name() {
13
+ return "CloudflareWorkersAI";
14
+ }
15
+ constructor(fields) {
16
+ super(fields ?? {});
17
+ Object.defineProperty(this, "model", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: "@cf/meta/llama-2-7b-chat-int8"
22
+ });
23
+ Object.defineProperty(this, "cloudflareAccountId", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: void 0
28
+ });
29
+ Object.defineProperty(this, "cloudflareApiToken", {
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true,
33
+ value: void 0
34
+ });
35
+ Object.defineProperty(this, "baseUrl", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: void 0
40
+ });
41
+ Object.defineProperty(this, "lc_serializable", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: true
46
+ });
47
+ this.model = fields?.model ?? this.model;
48
+ this.cloudflareAccountId =
49
+ fields?.cloudflareAccountId ??
50
+ (0, env_js_1.getEnvironmentVariable)("CLOUDFLARE_ACCOUNT_ID");
51
+ this.cloudflareApiToken =
52
+ fields?.cloudflareApiToken ??
53
+ (0, env_js_1.getEnvironmentVariable)("CLOUDFLARE_API_TOKEN");
54
+ this.baseUrl = fields?.baseUrl;
55
+ }
56
+ /**
57
+ * Method to validate the environment.
58
+ */
59
+ validateEnvironment() {
60
+ if (!this.cloudflareAccountId) {
61
+ throw new Error(`No Cloudflare account ID found. Please provide it when instantiating the CloudflareWorkersAI class, or set it as "CLOUDFLARE_ACCOUNT_ID" in your environment variables.`);
62
+ }
63
+ if (!this.cloudflareApiToken) {
64
+ throw new Error(`No Cloudflare API key found. Please provide it when instantiating the CloudflareWorkersAI class, or set it as "CLOUDFLARE_API_KEY" in your environment variables.`);
65
+ }
66
+ }
67
+ /** Get the identifying parameters for this LLM. */
68
+ get identifyingParams() {
69
+ return { model: this.model };
70
+ }
71
+ /**
72
+ * Get the parameters used to invoke the model
73
+ */
74
+ invocationParams() {
75
+ return {
76
+ model: this.model,
77
+ };
78
+ }
79
+ /** Get the type of LLM. */
80
+ _llmType() {
81
+ return "cloudflare";
82
+ }
83
+ /** Call out to CloudflareWorkersAI's complete endpoint.
84
+ Args:
85
+ prompt: The prompt to pass into the model.
86
+ Returns:
87
+ The string generated by the model.
88
+ Example:
89
+ let response = CloudflareWorkersAI.call("Tell me a joke.");
90
+ */
91
+ async _call(prompt, options) {
92
+ this.validateEnvironment();
93
+ const url = `https://api.cloudflare.com/client/v4/accounts/${this.cloudflareAccountId}/ai/run/${this.model}`;
94
+ const headers = {
95
+ Authorization: `Bearer ${this.cloudflareApiToken}`,
96
+ "Content-Type": "application/json",
97
+ };
98
+ const data = { prompt };
99
+ const responseData = await this.caller.call(async () => {
100
+ const response = await fetch(url, {
101
+ method: "POST",
102
+ headers,
103
+ body: JSON.stringify(data),
104
+ signal: options.signal,
105
+ });
106
+ if (!response.ok) {
107
+ const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
108
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
109
+ error.response = response;
110
+ throw error;
111
+ }
112
+ return response.json();
113
+ });
114
+ return responseData.result.response;
115
+ }
116
+ }
117
+ exports.CloudflareWorkersAI = CloudflareWorkersAI;
@@ -0,0 +1,49 @@
1
+ import { LLM, BaseLLMParams } from "./base.js";
2
+ /**
3
+ * Interface for CloudflareWorkersAI input parameters.
4
+ */
5
+ export interface CloudflareWorkersAIInput {
6
+ cloudflareAccountId?: string;
7
+ cloudflareApiToken?: string;
8
+ model?: string;
9
+ baseUrl?: string;
10
+ }
11
+ /**
12
+ * Class representing the CloudflareWorkersAI language model. It extends the LLM (Large
13
+ * Language Model) class, providing a standard interface for interacting
14
+ * with the CloudflareWorkersAI language model.
15
+ */
16
+ export declare class CloudflareWorkersAI extends LLM implements CloudflareWorkersAIInput {
17
+ model: string;
18
+ cloudflareAccountId?: string;
19
+ cloudflareApiToken?: string;
20
+ baseUrl?: string;
21
+ static lc_name(): string;
22
+ lc_serializable: boolean;
23
+ constructor(fields?: CloudflareWorkersAIInput & BaseLLMParams);
24
+ /**
25
+ * Method to validate the environment.
26
+ */
27
+ validateEnvironment(): void;
28
+ /** Get the identifying parameters for this LLM. */
29
+ get identifyingParams(): {
30
+ model: string;
31
+ };
32
+ /**
33
+ * Get the parameters used to invoke the model
34
+ */
35
+ invocationParams(): {
36
+ model: string;
37
+ };
38
+ /** Get the type of LLM. */
39
+ _llmType(): string;
40
+ /** Call out to CloudflareWorkersAI's complete endpoint.
41
+ Args:
42
+ prompt: The prompt to pass into the model.
43
+ Returns:
44
+ The string generated by the model.
45
+ Example:
46
+ let response = CloudflareWorkersAI.call("Tell me a joke.");
47
+ */
48
+ _call(prompt: string, options: this["ParsedCallOptions"]): Promise<string>;
49
+ }
@@ -0,0 +1,113 @@
1
+ import { LLM } from "./base.js";
2
+ import { getEnvironmentVariable } from "../util/env.js";
3
+ /**
4
+ * Class representing the CloudflareWorkersAI language model. It extends the LLM (Large
5
+ * Language Model) class, providing a standard interface for interacting
6
+ * with the CloudflareWorkersAI language model.
7
+ */
8
+ export class CloudflareWorkersAI extends LLM {
9
+ static lc_name() {
10
+ return "CloudflareWorkersAI";
11
+ }
12
+ constructor(fields) {
13
+ super(fields ?? {});
14
+ Object.defineProperty(this, "model", {
15
+ enumerable: true,
16
+ configurable: true,
17
+ writable: true,
18
+ value: "@cf/meta/llama-2-7b-chat-int8"
19
+ });
20
+ Object.defineProperty(this, "cloudflareAccountId", {
21
+ enumerable: true,
22
+ configurable: true,
23
+ writable: true,
24
+ value: void 0
25
+ });
26
+ Object.defineProperty(this, "cloudflareApiToken", {
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true,
30
+ value: void 0
31
+ });
32
+ Object.defineProperty(this, "baseUrl", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: void 0
37
+ });
38
+ Object.defineProperty(this, "lc_serializable", {
39
+ enumerable: true,
40
+ configurable: true,
41
+ writable: true,
42
+ value: true
43
+ });
44
+ this.model = fields?.model ?? this.model;
45
+ this.cloudflareAccountId =
46
+ fields?.cloudflareAccountId ??
47
+ getEnvironmentVariable("CLOUDFLARE_ACCOUNT_ID");
48
+ this.cloudflareApiToken =
49
+ fields?.cloudflareApiToken ??
50
+ getEnvironmentVariable("CLOUDFLARE_API_TOKEN");
51
+ this.baseUrl = fields?.baseUrl;
52
+ }
53
+ /**
54
+ * Method to validate the environment.
55
+ */
56
+ validateEnvironment() {
57
+ if (!this.cloudflareAccountId) {
58
+ throw new Error(`No Cloudflare account ID found. Please provide it when instantiating the CloudflareWorkersAI class, or set it as "CLOUDFLARE_ACCOUNT_ID" in your environment variables.`);
59
+ }
60
+ if (!this.cloudflareApiToken) {
61
+ throw new Error(`No Cloudflare API key found. Please provide it when instantiating the CloudflareWorkersAI class, or set it as "CLOUDFLARE_API_KEY" in your environment variables.`);
62
+ }
63
+ }
64
+ /** Get the identifying parameters for this LLM. */
65
+ get identifyingParams() {
66
+ return { model: this.model };
67
+ }
68
+ /**
69
+ * Get the parameters used to invoke the model
70
+ */
71
+ invocationParams() {
72
+ return {
73
+ model: this.model,
74
+ };
75
+ }
76
+ /** Get the type of LLM. */
77
+ _llmType() {
78
+ return "cloudflare";
79
+ }
80
+ /** Call out to CloudflareWorkersAI's complete endpoint.
81
+ Args:
82
+ prompt: The prompt to pass into the model.
83
+ Returns:
84
+ The string generated by the model.
85
+ Example:
86
+ let response = CloudflareWorkersAI.call("Tell me a joke.");
87
+ */
88
+ async _call(prompt, options) {
89
+ this.validateEnvironment();
90
+ const url = `https://api.cloudflare.com/client/v4/accounts/${this.cloudflareAccountId}/ai/run/${this.model}`;
91
+ const headers = {
92
+ Authorization: `Bearer ${this.cloudflareApiToken}`,
93
+ "Content-Type": "application/json",
94
+ };
95
+ const data = { prompt };
96
+ const responseData = await this.caller.call(async () => {
97
+ const response = await fetch(url, {
98
+ method: "POST",
99
+ headers,
100
+ body: JSON.stringify(data),
101
+ signal: options.signal,
102
+ });
103
+ if (!response.ok) {
104
+ const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
+ error.response = response;
107
+ throw error;
108
+ }
109
+ return response.json();
110
+ });
111
+ return responseData.result.response;
112
+ }
113
+ }
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FakeListLLM = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ const index_js_1 = require("../schema/index.cjs");
6
+ /**
7
+ * A fake LLM that returns a predefined list of responses. It can be used for
8
+ * testing purposes.
9
+ */
10
+ class FakeListLLM extends base_js_1.LLM {
11
+ static lc_name() {
12
+ return "FakeListLLM";
13
+ }
14
+ constructor({ responses, sleep }) {
15
+ super({});
16
+ Object.defineProperty(this, "responses", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: void 0
21
+ });
22
+ Object.defineProperty(this, "i", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: 0
27
+ });
28
+ Object.defineProperty(this, "sleep", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: void 0
33
+ });
34
+ this.responses = responses;
35
+ this.sleep = sleep;
36
+ }
37
+ _llmType() {
38
+ return "fake-list";
39
+ }
40
+ async _call(_prompt, _options, _runManager) {
41
+ const response = this._currentResponse();
42
+ this._incrementResponse();
43
+ await this._sleepIfRequested();
44
+ return response;
45
+ }
46
+ _currentResponse() {
47
+ return this.responses[this.i];
48
+ }
49
+ _incrementResponse() {
50
+ if (this.i < this.responses.length - 1) {
51
+ this.i += 1;
52
+ }
53
+ else {
54
+ this.i = 0;
55
+ }
56
+ }
57
+ async *_streamResponseChunks(_input, _options, _runManager) {
58
+ const response = this._currentResponse();
59
+ this._incrementResponse();
60
+ for await (const text of response) {
61
+ await this._sleepIfRequested();
62
+ yield this._createResponseChunk(text);
63
+ }
64
+ }
65
+ async _sleepIfRequested() {
66
+ if (this.sleep !== undefined) {
67
+ await this._sleep();
68
+ }
69
+ }
70
+ async _sleep() {
71
+ return new Promise((resolve) => {
72
+ setTimeout(() => resolve(), this.sleep);
73
+ });
74
+ }
75
+ _createResponseChunk(text) {
76
+ return new index_js_1.GenerationChunk({
77
+ text,
78
+ generationInfo: {},
79
+ });
80
+ }
81
+ }
82
+ exports.FakeListLLM = FakeListLLM;
@@ -0,0 +1,31 @@
1
+ import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
2
+ import { LLM, BaseLLMParams } from "./base.js";
3
+ import { GenerationChunk } from "../schema/index.js";
4
+ /**
5
+ * Interface for the input parameters specific to the Fake List model.
6
+ */
7
+ export interface FakeListInput extends BaseLLMParams {
8
+ /** Responses to return */
9
+ responses: string[];
10
+ /** Time to sleep in milliseconds between responses */
11
+ sleep?: number;
12
+ }
13
+ /**
14
+ * A fake LLM that returns a predefined list of responses. It can be used for
15
+ * testing purposes.
16
+ */
17
+ export declare class FakeListLLM extends LLM {
18
+ static lc_name(): string;
19
+ responses: string[];
20
+ i: number;
21
+ sleep?: number;
22
+ constructor({ responses, sleep }: FakeListInput);
23
+ _llmType(): string;
24
+ _call(_prompt: string, _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): Promise<string>;
25
+ _currentResponse(): string;
26
+ _incrementResponse(): void;
27
+ _streamResponseChunks(_input: string, _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<GenerationChunk>;
28
+ _sleepIfRequested(): Promise<void>;
29
+ _sleep(): Promise<void>;
30
+ _createResponseChunk(text: string): GenerationChunk;
31
+ }
@@ -0,0 +1,78 @@
1
+ import { LLM } from "./base.js";
2
+ import { GenerationChunk } from "../schema/index.js";
3
+ /**
4
+ * A fake LLM that returns a predefined list of responses. It can be used for
5
+ * testing purposes.
6
+ */
7
+ export class FakeListLLM extends LLM {
8
+ static lc_name() {
9
+ return "FakeListLLM";
10
+ }
11
+ constructor({ responses, sleep }) {
12
+ super({});
13
+ Object.defineProperty(this, "responses", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: void 0
18
+ });
19
+ Object.defineProperty(this, "i", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: 0
24
+ });
25
+ Object.defineProperty(this, "sleep", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: void 0
30
+ });
31
+ this.responses = responses;
32
+ this.sleep = sleep;
33
+ }
34
+ _llmType() {
35
+ return "fake-list";
36
+ }
37
+ async _call(_prompt, _options, _runManager) {
38
+ const response = this._currentResponse();
39
+ this._incrementResponse();
40
+ await this._sleepIfRequested();
41
+ return response;
42
+ }
43
+ _currentResponse() {
44
+ return this.responses[this.i];
45
+ }
46
+ _incrementResponse() {
47
+ if (this.i < this.responses.length - 1) {
48
+ this.i += 1;
49
+ }
50
+ else {
51
+ this.i = 0;
52
+ }
53
+ }
54
+ async *_streamResponseChunks(_input, _options, _runManager) {
55
+ const response = this._currentResponse();
56
+ this._incrementResponse();
57
+ for await (const text of response) {
58
+ await this._sleepIfRequested();
59
+ yield this._createResponseChunk(text);
60
+ }
61
+ }
62
+ async _sleepIfRequested() {
63
+ if (this.sleep !== undefined) {
64
+ await this._sleep();
65
+ }
66
+ }
67
+ async _sleep() {
68
+ return new Promise((resolve) => {
69
+ setTimeout(() => resolve(), this.sleep);
70
+ });
71
+ }
72
+ _createResponseChunk(text) {
73
+ return new GenerationChunk({
74
+ text,
75
+ generationInfo: {},
76
+ });
77
+ }
78
+ }