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
package/README.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  ⚡ Building applications with LLMs through composability ⚡
4
4
 
5
- [![CI](https://github.com/hwchase17/langchainjs/actions/workflows/ci.yml/badge.svg)](https://github.com/hwchase17/langchainjs/actions/workflows/ci.yml) ![npm](https://img.shields.io/npm/dw/langchain) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai) [![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.gg/6adMQxSpJS) [![Open in Dev Containers](https://img.shields.io/static/v1?label=Dev%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/hwchase17/langchainjs)
5
+ [![CI](https://github.com/langchain-ai/langchainjs/actions/workflows/ci.yml/badge.svg)](https://github.com/langchain-ai/langchainjs/actions/workflows/ci.yml) ![npm](https://img.shields.io/npm/dw/langchain) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai) [![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.gg/6adMQxSpJS) [![Open in Dev Containers](https://img.shields.io/static/v1?label=Dev%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/langchain-ai/langchainjs)
6
6
  [<img src="https://github.com/codespaces/badge.svg" title="Open in Github Codespace" width="150" height="20">](https://codespaces.new/hwchase17/langchainjs)
7
7
 
8
8
  Looking for the Python version? Check out [LangChain](https://github.com/hwchase17/langchain).
9
9
 
10
- To help you ship LangChain apps to production faster, check out [LangSmith](https://smith.langchain.com).
11
- [LangSmith](https://smith.langchain.com) is a unified developer platform for building, testing, and monitoring LLM applications.
10
+ To help you ship LangChain apps to production faster, check out [LangSmith](https://smith.langchain.com).
11
+ [LangSmith](https://smith.langchain.com) is a unified developer platform for building, testing, and monitoring LLM applications.
12
12
  Fill out [this form](https://airtable.com/appwQzlErAS2qiP0L/shrGtGaVBVAz7NcV2) to get off the waitlist or speak with our sales team
13
13
 
14
14
  ## Quick Install
@@ -53,4 +53,4 @@ The [LangChainHub](https://github.com/hwchase17/langchain-hub) is a central plac
53
53
 
54
54
  As an open source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infra, or better documentation.
55
55
 
56
- Check out [our contributing guidelines](https://github.com/hwchase17/langchainjs/blob/main/CONTRIBUTING.md) for instructions on how to contribute.
56
+ Check out [our contributing guidelines](https://github.com/langchain-ai/langchainjs/blob/main/CONTRIBUTING.md) for instructions on how to contribute.
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/chat_models/cloudflare_workersai.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/cloudflare_workersai.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/cloudflare_workersai.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/chat_models/fake.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/fake.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/fake.js'
@@ -80,13 +80,14 @@ class ChatAgent extends agent_js_1.Agent {
80
80
  * @param args.suffix - String to put after the list of tools.
81
81
  * @param args.prefix - String to put before the list of tools.
82
82
  * @param args.humanMessageTemplate - String to use directly as the human message template
83
+ * @param args.formatInstructions - Formattable string to use as the instructions template
83
84
  */
84
85
  static createPrompt(tools, args) {
85
- const { prefix = prompt_js_1.PREFIX, suffix = prompt_js_1.SUFFIX, humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE, } = args ?? {};
86
+ const { prefix = prompt_js_1.PREFIX, suffix = prompt_js_1.SUFFIX, humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE, formatInstructions = prompt_js_1.FORMAT_INSTRUCTIONS, } = args ?? {};
86
87
  const toolStrings = tools
87
88
  .map((tool) => `${tool.name}: ${tool.description}`)
88
89
  .join("\n");
89
- const template = [prefix, toolStrings, prompt_js_1.FORMAT_INSTRUCTIONS, suffix].join("\n\n");
90
+ const template = [prefix, toolStrings, formatInstructions, suffix].join("\n\n");
90
91
  const messages = [
91
92
  chat_js_1.SystemMessagePromptTemplate.fromTemplate(template),
92
93
  chat_js_1.HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),
@@ -16,6 +16,8 @@ export interface ChatCreatePromptArgs {
16
16
  prefix?: string;
17
17
  /** String to use directly as the human message template. */
18
18
  humanMessageTemplate?: string;
19
+ /** Formattable string to use as the instructions template. */
20
+ formatInstructions?: string;
19
21
  /** List of input variables the final prompt will expect. */
20
22
  inputVariables?: string[];
21
23
  }
@@ -65,6 +67,7 @@ export declare class ChatAgent extends Agent {
65
67
  * @param args.suffix - String to put after the list of tools.
66
68
  * @param args.prefix - String to put before the list of tools.
67
69
  * @param args.humanMessageTemplate - String to use directly as the human message template
70
+ * @param args.formatInstructions - Formattable string to use as the instructions template
68
71
  */
69
72
  static createPrompt(tools: Tool[], args?: ChatCreatePromptArgs): ChatPromptTemplate<any, any>;
70
73
  /**
@@ -77,13 +77,14 @@ export class ChatAgent extends Agent {
77
77
  * @param args.suffix - String to put after the list of tools.
78
78
  * @param args.prefix - String to put before the list of tools.
79
79
  * @param args.humanMessageTemplate - String to use directly as the human message template
80
+ * @param args.formatInstructions - Formattable string to use as the instructions template
80
81
  */
81
82
  static createPrompt(tools, args) {
82
- const { prefix = PREFIX, suffix = SUFFIX, humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE, } = args ?? {};
83
+ const { prefix = PREFIX, suffix = SUFFIX, humanMessageTemplate = DEFAULT_HUMAN_MESSAGE_TEMPLATE, formatInstructions = FORMAT_INSTRUCTIONS, } = args ?? {};
83
84
  const toolStrings = tools
84
85
  .map((tool) => `${tool.name}: ${tool.description}`)
85
86
  .join("\n");
86
- const template = [prefix, toolStrings, FORMAT_INSTRUCTIONS, suffix].join("\n\n");
87
+ const template = [prefix, toolStrings, formatInstructions, suffix].join("\n\n");
87
88
  const messages = [
88
89
  SystemMessagePromptTemplate.fromTemplate(template),
89
90
  HumanMessagePromptTemplate.fromTemplate(humanMessageTemplate),
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatCloudflareWorkersAI = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ const index_js_1 = require("../schema/index.cjs");
6
+ const env_js_1 = require("../util/env.cjs");
7
+ /**
8
+ * A class that enables calls to the Cloudflare Workers AI API to access large language
9
+ * models in a chat-like fashion. It extends the SimpleChatModel class and
10
+ * implements the CloudflareWorkersAIInput interface.
11
+ */
12
+ class ChatCloudflareWorkersAI extends base_js_1.SimpleChatModel {
13
+ static lc_name() {
14
+ return "ChatCloudflareWorkersAI";
15
+ }
16
+ constructor(fields) {
17
+ super(fields ?? {});
18
+ Object.defineProperty(this, "lc_serializable", {
19
+ enumerable: true,
20
+ configurable: true,
21
+ writable: true,
22
+ value: true
23
+ });
24
+ Object.defineProperty(this, "model", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: "@cf/meta/llama-2-7b-chat-int8"
29
+ });
30
+ Object.defineProperty(this, "cloudflareAccountId", {
31
+ enumerable: true,
32
+ configurable: true,
33
+ writable: true,
34
+ value: void 0
35
+ });
36
+ Object.defineProperty(this, "cloudflareApiToken", {
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true,
40
+ value: void 0
41
+ });
42
+ Object.defineProperty(this, "baseUrl", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: void 0
47
+ });
48
+ this.model = fields?.model ?? this.model;
49
+ this.cloudflareAccountId =
50
+ fields?.cloudflareAccountId ??
51
+ (0, env_js_1.getEnvironmentVariable)("CLOUDFLARE_ACCOUNT_ID");
52
+ this.cloudflareApiToken =
53
+ fields?.cloudflareApiToken ??
54
+ (0, env_js_1.getEnvironmentVariable)("CLOUDFLARE_API_TOKEN");
55
+ this.baseUrl = fields?.baseUrl;
56
+ }
57
+ _llmType() {
58
+ return "cloudflare";
59
+ }
60
+ /** Get the identifying parameters for this LLM. */
61
+ get identifyingParams() {
62
+ return { model: this.model };
63
+ }
64
+ /**
65
+ * Get the parameters used to invoke the model
66
+ */
67
+ invocationParams(_options) {
68
+ return {
69
+ model: this.model,
70
+ };
71
+ }
72
+ _combineLLMOutput() {
73
+ return {};
74
+ }
75
+ /**
76
+ * Method to validate the environment.
77
+ */
78
+ validateEnvironment() {
79
+ if (!this.cloudflareAccountId) {
80
+ 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.`);
81
+ }
82
+ if (!this.cloudflareApiToken) {
83
+ 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.`);
84
+ }
85
+ }
86
+ _formatMessages(messages) {
87
+ const formattedMessages = messages.map((message) => {
88
+ let role;
89
+ if (message._getType() === "human") {
90
+ role = "user";
91
+ }
92
+ else if (message._getType() === "ai") {
93
+ role = "assistant";
94
+ }
95
+ else if (message._getType() === "system") {
96
+ role = "system";
97
+ }
98
+ else if (index_js_1.ChatMessage.isInstance(message)) {
99
+ role = message.role;
100
+ }
101
+ else {
102
+ console.warn(`Unsupported message type passed to Cloudflare: "${message._getType()}"`);
103
+ role = "user";
104
+ }
105
+ return {
106
+ role,
107
+ content: message.content,
108
+ };
109
+ });
110
+ return formattedMessages;
111
+ }
112
+ /** @ignore */
113
+ async _call(messages, options) {
114
+ this.validateEnvironment();
115
+ const url = `https://api.cloudflare.com/client/v4/accounts/${this.cloudflareAccountId}/ai/run/${this.model}`;
116
+ const headers = {
117
+ Authorization: `Bearer ${this.cloudflareApiToken}`,
118
+ "Content-Type": "application/json",
119
+ };
120
+ const formattedMessages = this._formatMessages(messages);
121
+ const data = { messages: formattedMessages };
122
+ const responseData = await this.caller.call(async () => {
123
+ const response = await fetch(url, {
124
+ method: "POST",
125
+ headers,
126
+ body: JSON.stringify(data),
127
+ signal: options.signal,
128
+ });
129
+ if (!response.ok) {
130
+ const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
131
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
132
+ error.response = response;
133
+ throw error;
134
+ }
135
+ return response.json();
136
+ });
137
+ return responseData.result.response;
138
+ }
139
+ }
140
+ exports.ChatCloudflareWorkersAI = ChatCloudflareWorkersAI;
@@ -0,0 +1,46 @@
1
+ import { SimpleChatModel, BaseChatModelParams } from "./base.js";
2
+ import { BaseLanguageModelCallOptions } from "../base_language/index.js";
3
+ import { BaseMessage } from "../schema/index.js";
4
+ import { CloudflareWorkersAIInput } from "../llms/cloudflare_workersai.js";
5
+ /**
6
+ * An interface defining the options for a Cloudflare Workers AI call. It extends
7
+ * the BaseLanguageModelCallOptions interface.
8
+ */
9
+ export interface ChatCloudflareWorkersAICallOptions extends BaseLanguageModelCallOptions {
10
+ }
11
+ /**
12
+ * A class that enables calls to the Cloudflare Workers AI API to access large language
13
+ * models in a chat-like fashion. It extends the SimpleChatModel class and
14
+ * implements the CloudflareWorkersAIInput interface.
15
+ */
16
+ export declare class ChatCloudflareWorkersAI extends SimpleChatModel implements CloudflareWorkersAIInput {
17
+ static lc_name(): string;
18
+ lc_serializable: boolean;
19
+ model: string;
20
+ cloudflareAccountId?: string;
21
+ cloudflareApiToken?: string;
22
+ baseUrl?: string;
23
+ constructor(fields?: CloudflareWorkersAIInput & BaseChatModelParams);
24
+ _llmType(): string;
25
+ /** Get the identifying parameters for this LLM. */
26
+ get identifyingParams(): {
27
+ model: string;
28
+ };
29
+ /**
30
+ * Get the parameters used to invoke the model
31
+ */
32
+ invocationParams(_options?: this["ParsedCallOptions"]): {
33
+ model: string;
34
+ };
35
+ _combineLLMOutput(): {};
36
+ /**
37
+ * Method to validate the environment.
38
+ */
39
+ validateEnvironment(): void;
40
+ protected _formatMessages(messages: BaseMessage[]): {
41
+ role: string;
42
+ content: string;
43
+ }[];
44
+ /** @ignore */
45
+ _call(messages: BaseMessage[], options: this["ParsedCallOptions"]): Promise<string>;
46
+ }
@@ -0,0 +1,136 @@
1
+ import { SimpleChatModel } from "./base.js";
2
+ import { ChatMessage } from "../schema/index.js";
3
+ import { getEnvironmentVariable } from "../util/env.js";
4
+ /**
5
+ * A class that enables calls to the Cloudflare Workers AI API to access large language
6
+ * models in a chat-like fashion. It extends the SimpleChatModel class and
7
+ * implements the CloudflareWorkersAIInput interface.
8
+ */
9
+ export class ChatCloudflareWorkersAI extends SimpleChatModel {
10
+ static lc_name() {
11
+ return "ChatCloudflareWorkersAI";
12
+ }
13
+ constructor(fields) {
14
+ super(fields ?? {});
15
+ Object.defineProperty(this, "lc_serializable", {
16
+ enumerable: true,
17
+ configurable: true,
18
+ writable: true,
19
+ value: true
20
+ });
21
+ Object.defineProperty(this, "model", {
22
+ enumerable: true,
23
+ configurable: true,
24
+ writable: true,
25
+ value: "@cf/meta/llama-2-7b-chat-int8"
26
+ });
27
+ Object.defineProperty(this, "cloudflareAccountId", {
28
+ enumerable: true,
29
+ configurable: true,
30
+ writable: true,
31
+ value: void 0
32
+ });
33
+ Object.defineProperty(this, "cloudflareApiToken", {
34
+ enumerable: true,
35
+ configurable: true,
36
+ writable: true,
37
+ value: void 0
38
+ });
39
+ Object.defineProperty(this, "baseUrl", {
40
+ enumerable: true,
41
+ configurable: true,
42
+ writable: true,
43
+ value: void 0
44
+ });
45
+ this.model = fields?.model ?? this.model;
46
+ this.cloudflareAccountId =
47
+ fields?.cloudflareAccountId ??
48
+ getEnvironmentVariable("CLOUDFLARE_ACCOUNT_ID");
49
+ this.cloudflareApiToken =
50
+ fields?.cloudflareApiToken ??
51
+ getEnvironmentVariable("CLOUDFLARE_API_TOKEN");
52
+ this.baseUrl = fields?.baseUrl;
53
+ }
54
+ _llmType() {
55
+ return "cloudflare";
56
+ }
57
+ /** Get the identifying parameters for this LLM. */
58
+ get identifyingParams() {
59
+ return { model: this.model };
60
+ }
61
+ /**
62
+ * Get the parameters used to invoke the model
63
+ */
64
+ invocationParams(_options) {
65
+ return {
66
+ model: this.model,
67
+ };
68
+ }
69
+ _combineLLMOutput() {
70
+ return {};
71
+ }
72
+ /**
73
+ * Method to validate the environment.
74
+ */
75
+ validateEnvironment() {
76
+ if (!this.cloudflareAccountId) {
77
+ 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.`);
78
+ }
79
+ if (!this.cloudflareApiToken) {
80
+ 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.`);
81
+ }
82
+ }
83
+ _formatMessages(messages) {
84
+ const formattedMessages = messages.map((message) => {
85
+ let role;
86
+ if (message._getType() === "human") {
87
+ role = "user";
88
+ }
89
+ else if (message._getType() === "ai") {
90
+ role = "assistant";
91
+ }
92
+ else if (message._getType() === "system") {
93
+ role = "system";
94
+ }
95
+ else if (ChatMessage.isInstance(message)) {
96
+ role = message.role;
97
+ }
98
+ else {
99
+ console.warn(`Unsupported message type passed to Cloudflare: "${message._getType()}"`);
100
+ role = "user";
101
+ }
102
+ return {
103
+ role,
104
+ content: message.content,
105
+ };
106
+ });
107
+ return formattedMessages;
108
+ }
109
+ /** @ignore */
110
+ async _call(messages, options) {
111
+ this.validateEnvironment();
112
+ const url = `https://api.cloudflare.com/client/v4/accounts/${this.cloudflareAccountId}/ai/run/${this.model}`;
113
+ const headers = {
114
+ Authorization: `Bearer ${this.cloudflareApiToken}`,
115
+ "Content-Type": "application/json",
116
+ };
117
+ const formattedMessages = this._formatMessages(messages);
118
+ const data = { messages: formattedMessages };
119
+ const responseData = await this.caller.call(async () => {
120
+ const response = await fetch(url, {
121
+ method: "POST",
122
+ headers,
123
+ body: JSON.stringify(data),
124
+ signal: options.signal,
125
+ });
126
+ if (!response.ok) {
127
+ const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
128
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
+ error.response = response;
130
+ throw error;
131
+ }
132
+ return response.json();
133
+ });
134
+ return responseData.result.response;
135
+ }
136
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FakeListChatModel = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ const index_js_1 = require("../schema/index.cjs");
6
+ /**
7
+ * A fake Chat Model that returns a predefined list of responses. It can be used
8
+ * for testing purposes.
9
+ */
10
+ class FakeListChatModel extends base_js_1.BaseChatModel {
11
+ static lc_name() {
12
+ return "FakeListChatModel";
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
+ _combineLLMOutput() {
38
+ return [];
39
+ }
40
+ _llmType() {
41
+ return "fake-list";
42
+ }
43
+ async _generate(_messages, options) {
44
+ await this._sleepIfRequested();
45
+ if (options?.stop?.length) {
46
+ return {
47
+ generations: [this._formatGeneration(options.stop[0])],
48
+ };
49
+ }
50
+ else {
51
+ const response = this._currentResponse();
52
+ this._incrementResponse();
53
+ return {
54
+ generations: [this._formatGeneration(response)],
55
+ llmOutput: {},
56
+ };
57
+ }
58
+ }
59
+ _formatGeneration(text) {
60
+ return {
61
+ message: new index_js_1.AIMessage(text),
62
+ text,
63
+ };
64
+ }
65
+ async *_streamResponseChunks(_messages, _options, _runManager) {
66
+ const response = this._currentResponse();
67
+ this._incrementResponse();
68
+ for await (const text of response) {
69
+ await this._sleepIfRequested();
70
+ yield this._createResponseChunk(text);
71
+ }
72
+ }
73
+ async _sleepIfRequested() {
74
+ if (this.sleep !== undefined) {
75
+ await this._sleep();
76
+ }
77
+ }
78
+ async _sleep() {
79
+ return new Promise((resolve) => {
80
+ setTimeout(() => resolve(), this.sleep);
81
+ });
82
+ }
83
+ _createResponseChunk(text) {
84
+ return new index_js_1.ChatGenerationChunk({
85
+ message: new index_js_1.AIMessageChunk({ content: text }),
86
+ text,
87
+ });
88
+ }
89
+ _currentResponse() {
90
+ return this.responses[this.i];
91
+ }
92
+ _incrementResponse() {
93
+ if (this.i < this.responses.length - 1) {
94
+ this.i += 1;
95
+ }
96
+ else {
97
+ this.i = 0;
98
+ }
99
+ }
100
+ }
101
+ exports.FakeListChatModel = FakeListChatModel;
@@ -0,0 +1,36 @@
1
+ import { BaseChatModel, BaseChatModelParams } from "./base.js";
2
+ import { AIMessage, BaseMessage, ChatGenerationChunk, ChatResult } from "../schema/index.js";
3
+ import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
4
+ /**
5
+ * Interface for the input parameters specific to the Fake List Chat model.
6
+ */
7
+ export interface FakeChatInput extends BaseChatModelParams {
8
+ /** Responses to return */
9
+ responses: string[];
10
+ /** Time to sleep in milliseconds between responses */
11
+ sleep?: number;
12
+ }
13
+ /**
14
+ * A fake Chat Model that returns a predefined list of responses. It can be used
15
+ * for testing purposes.
16
+ */
17
+ export declare class FakeListChatModel extends BaseChatModel {
18
+ static lc_name(): string;
19
+ responses: string[];
20
+ i: number;
21
+ sleep?: number;
22
+ constructor({ responses, sleep }: FakeChatInput);
23
+ _combineLLMOutput(): never[];
24
+ _llmType(): string;
25
+ _generate(_messages: BaseMessage[], options?: this["ParsedCallOptions"]): Promise<ChatResult>;
26
+ _formatGeneration(text: string): {
27
+ message: AIMessage;
28
+ text: string;
29
+ };
30
+ _streamResponseChunks(_messages: BaseMessage[], _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
31
+ _sleepIfRequested(): Promise<void>;
32
+ _sleep(): Promise<void>;
33
+ _createResponseChunk(text: string): ChatGenerationChunk;
34
+ _currentResponse(): string;
35
+ _incrementResponse(): void;
36
+ }
@@ -0,0 +1,97 @@
1
+ import { BaseChatModel } from "./base.js";
2
+ import { AIMessage, AIMessageChunk, ChatGenerationChunk, } from "../schema/index.js";
3
+ /**
4
+ * A fake Chat Model that returns a predefined list of responses. It can be used
5
+ * for testing purposes.
6
+ */
7
+ export class FakeListChatModel extends BaseChatModel {
8
+ static lc_name() {
9
+ return "FakeListChatModel";
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
+ _combineLLMOutput() {
35
+ return [];
36
+ }
37
+ _llmType() {
38
+ return "fake-list";
39
+ }
40
+ async _generate(_messages, options) {
41
+ await this._sleepIfRequested();
42
+ if (options?.stop?.length) {
43
+ return {
44
+ generations: [this._formatGeneration(options.stop[0])],
45
+ };
46
+ }
47
+ else {
48
+ const response = this._currentResponse();
49
+ this._incrementResponse();
50
+ return {
51
+ generations: [this._formatGeneration(response)],
52
+ llmOutput: {},
53
+ };
54
+ }
55
+ }
56
+ _formatGeneration(text) {
57
+ return {
58
+ message: new AIMessage(text),
59
+ text,
60
+ };
61
+ }
62
+ async *_streamResponseChunks(_messages, _options, _runManager) {
63
+ const response = this._currentResponse();
64
+ this._incrementResponse();
65
+ for await (const text of response) {
66
+ await this._sleepIfRequested();
67
+ yield this._createResponseChunk(text);
68
+ }
69
+ }
70
+ async _sleepIfRequested() {
71
+ if (this.sleep !== undefined) {
72
+ await this._sleep();
73
+ }
74
+ }
75
+ async _sleep() {
76
+ return new Promise((resolve) => {
77
+ setTimeout(() => resolve(), this.sleep);
78
+ });
79
+ }
80
+ _createResponseChunk(text) {
81
+ return new ChatGenerationChunk({
82
+ message: new AIMessageChunk({ content: text }),
83
+ text,
84
+ });
85
+ }
86
+ _currentResponse() {
87
+ return this.responses[this.i];
88
+ }
89
+ _incrementResponse() {
90
+ if (this.i < this.responses.length - 1) {
91
+ this.i += 1;
92
+ }
93
+ else {
94
+ this.i = 0;
95
+ }
96
+ }
97
+ }