langchain 0.0.150 → 0.0.152

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 (87) hide show
  1. package/cache/cloudflare_kv.cjs +1 -0
  2. package/cache/cloudflare_kv.d.ts +1 -0
  3. package/cache/cloudflare_kv.js +1 -0
  4. package/dist/agents/chat/index.cjs +1 -1
  5. package/dist/agents/chat/index.js +1 -1
  6. package/dist/agents/chat_convo/index.cjs +1 -1
  7. package/dist/agents/chat_convo/index.js +1 -1
  8. package/dist/agents/openai/index.cjs +1 -1
  9. package/dist/agents/openai/index.js +1 -1
  10. package/dist/agents/structured_chat/index.cjs +1 -1
  11. package/dist/agents/structured_chat/index.js +1 -1
  12. package/dist/agents/xml/index.cjs +1 -1
  13. package/dist/agents/xml/index.js +1 -1
  14. package/dist/base_language/count_tokens.cjs +1 -0
  15. package/dist/base_language/count_tokens.js +1 -0
  16. package/dist/base_language/index.cjs +5 -3
  17. package/dist/base_language/index.d.ts +1 -1
  18. package/dist/base_language/index.js +4 -3
  19. package/dist/cache/cloudflare_kv.cjs +61 -0
  20. package/dist/cache/cloudflare_kv.d.ts +29 -0
  21. package/dist/cache/cloudflare_kv.js +57 -0
  22. package/dist/chains/openai_functions/openapi.cjs +1 -1
  23. package/dist/chains/openai_functions/openapi.js +1 -1
  24. package/dist/chains/question_answering/map_reduce_prompts.cjs +2 -3
  25. package/dist/chains/question_answering/map_reduce_prompts.js +2 -3
  26. package/dist/chains/question_answering/refine_prompts.cjs +2 -2
  27. package/dist/chains/question_answering/refine_prompts.js +2 -2
  28. package/dist/chains/question_answering/stuff_prompts.cjs +1 -2
  29. package/dist/chains/question_answering/stuff_prompts.js +1 -2
  30. package/dist/chat_models/ollama.cjs +3 -7
  31. package/dist/chat_models/ollama.d.ts +1 -1
  32. package/dist/chat_models/ollama.js +3 -7
  33. package/dist/document_loaders/web/pdf.cjs +87 -0
  34. package/dist/document_loaders/web/pdf.d.ts +17 -0
  35. package/dist/document_loaders/web/pdf.js +83 -0
  36. package/dist/evaluation/agents/prompt.cjs +2 -3
  37. package/dist/evaluation/agents/prompt.js +2 -3
  38. package/dist/experimental/chat_models/bittensor.cjs +141 -0
  39. package/dist/experimental/chat_models/bittensor.d.ts +36 -0
  40. package/dist/experimental/chat_models/bittensor.js +137 -0
  41. package/dist/experimental/plan_and_execute/prompt.cjs +1 -1
  42. package/dist/experimental/plan_and_execute/prompt.js +1 -1
  43. package/dist/llms/llama_cpp.cjs +10 -4
  44. package/dist/llms/llama_cpp.d.ts +2 -1
  45. package/dist/llms/llama_cpp.js +10 -4
  46. package/dist/llms/ollama.cjs +5 -6
  47. package/dist/llms/ollama.d.ts +2 -2
  48. package/dist/llms/ollama.js +5 -6
  49. package/dist/llms/openai.cjs +3 -3
  50. package/dist/llms/openai.js +3 -3
  51. package/dist/load/import_constants.cjs +4 -0
  52. package/dist/load/import_constants.js +4 -0
  53. package/dist/load/import_map.cjs +2 -1
  54. package/dist/load/import_map.d.ts +1 -0
  55. package/dist/load/import_map.js +1 -0
  56. package/dist/prompts/chat.cjs +12 -1
  57. package/dist/prompts/chat.d.ts +8 -0
  58. package/dist/prompts/chat.js +12 -1
  59. package/dist/schema/runnable/base.cjs +10 -2
  60. package/dist/schema/runnable/base.d.ts +2 -0
  61. package/dist/schema/runnable/base.js +9 -2
  62. package/dist/schema/runnable/branch.cjs +106 -0
  63. package/dist/schema/runnable/branch.d.ts +66 -0
  64. package/dist/schema/runnable/branch.js +102 -0
  65. package/dist/schema/runnable/index.cjs +12 -16
  66. package/dist/schema/runnable/index.d.ts +2 -1
  67. package/dist/schema/runnable/index.js +2 -1
  68. package/dist/stores/message/cloudflare_d1.cjs +134 -0
  69. package/dist/stores/message/cloudflare_d1.d.ts +49 -0
  70. package/dist/stores/message/cloudflare_d1.js +130 -0
  71. package/dist/types/openai-types.d.ts +2 -0
  72. package/dist/vectorstores/pgvector.cjs +277 -0
  73. package/dist/vectorstores/pgvector.d.ts +132 -0
  74. package/dist/vectorstores/pgvector.js +270 -0
  75. package/document_loaders/web/pdf.cjs +1 -0
  76. package/document_loaders/web/pdf.d.ts +1 -0
  77. package/document_loaders/web/pdf.js +1 -0
  78. package/experimental/chat_models/bittensor.cjs +1 -0
  79. package/experimental/chat_models/bittensor.d.ts +1 -0
  80. package/experimental/chat_models/bittensor.js +1 -0
  81. package/package.json +46 -1
  82. package/stores/message/cloudflare_d1.cjs +1 -0
  83. package/stores/message/cloudflare_d1.d.ts +1 -0
  84. package/stores/message/cloudflare_d1.js +1 -0
  85. package/vectorstores/pgvector.cjs +1 -0
  86. package/vectorstores/pgvector.d.ts +1 -0
  87. package/vectorstores/pgvector.js +1 -0
@@ -48,6 +48,7 @@ exports.optionalImportEntrypoints = [
48
48
  "langchain/vectorstores/qdrant",
49
49
  "langchain/vectorstores/supabase",
50
50
  "langchain/vectorstores/opensearch",
51
+ "langchain/vectorstores/pgvector",
51
52
  "langchain/vectorstores/milvus",
52
53
  "langchain/vectorstores/typeorm",
53
54
  "langchain/vectorstores/myscale",
@@ -74,6 +75,7 @@ exports.optionalImportEntrypoints = [
74
75
  "langchain/document_loaders/web/github",
75
76
  "langchain/document_loaders/web/notiondb",
76
77
  "langchain/document_loaders/web/notionapi",
78
+ "langchain/document_loaders/web/pdf",
77
79
  "langchain/document_loaders/web/recursive_url",
78
80
  "langchain/document_loaders/web/s3",
79
81
  "langchain/document_loaders/web/sonix_audio",
@@ -109,12 +111,14 @@ exports.optionalImportEntrypoints = [
109
111
  "langchain/retrievers/self_query/pinecone",
110
112
  "langchain/retrievers/self_query/supabase",
111
113
  "langchain/retrievers/self_query/weaviate",
114
+ "langchain/cache/cloudflare_kv",
112
115
  "langchain/cache/momento",
113
116
  "langchain/cache/redis",
114
117
  "langchain/cache/ioredis",
115
118
  "langchain/cache/upstash_redis",
116
119
  "langchain/stores/doc/gcs",
117
120
  "langchain/stores/file/node",
121
+ "langchain/stores/message/cloudflare_d1",
118
122
  "langchain/stores/message/dynamodb",
119
123
  "langchain/stores/message/firestore",
120
124
  "langchain/stores/message/momento",
@@ -45,6 +45,7 @@ export const optionalImportEntrypoints = [
45
45
  "langchain/vectorstores/qdrant",
46
46
  "langchain/vectorstores/supabase",
47
47
  "langchain/vectorstores/opensearch",
48
+ "langchain/vectorstores/pgvector",
48
49
  "langchain/vectorstores/milvus",
49
50
  "langchain/vectorstores/typeorm",
50
51
  "langchain/vectorstores/myscale",
@@ -71,6 +72,7 @@ export const optionalImportEntrypoints = [
71
72
  "langchain/document_loaders/web/github",
72
73
  "langchain/document_loaders/web/notiondb",
73
74
  "langchain/document_loaders/web/notionapi",
75
+ "langchain/document_loaders/web/pdf",
74
76
  "langchain/document_loaders/web/recursive_url",
75
77
  "langchain/document_loaders/web/s3",
76
78
  "langchain/document_loaders/web/sonix_audio",
@@ -106,12 +108,14 @@ export const optionalImportEntrypoints = [
106
108
  "langchain/retrievers/self_query/pinecone",
107
109
  "langchain/retrievers/self_query/supabase",
108
110
  "langchain/retrievers/self_query/weaviate",
111
+ "langchain/cache/cloudflare_kv",
109
112
  "langchain/cache/momento",
110
113
  "langchain/cache/redis",
111
114
  "langchain/cache/ioredis",
112
115
  "langchain/cache/upstash_redis",
113
116
  "langchain/stores/doc/gcs",
114
117
  "langchain/stores/file/node",
118
+ "langchain/stores/message/cloudflare_d1",
115
119
  "langchain/stores/message/dynamodb",
116
120
  "langchain/stores/message/firestore",
117
121
  "langchain/stores/message/momento",
@@ -25,7 +25,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
25
25
  };
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
27
  exports.retrievers__document_compressors = exports.retrievers__contextual_compression = exports.retrievers__databerry = exports.retrievers__remote = exports.output_parsers = exports.callbacks = exports.schema__storage = exports.schema__runnable = exports.schema__retriever = exports.schema__query_constructor = exports.schema__output_parser = exports.schema__document = exports.schema = exports.chat_models__minimax = exports.chat_models__ollama = exports.chat_models__baiduwenxin = exports.chat_models__anthropic = exports.chat_models__openai = exports.chat_models__base = exports.document_transformers__openai_functions = exports.document_loaders__web__sort_xyz_blockchain = exports.document_loaders__web__serpapi = exports.document_loaders__base = exports.document = exports.memory = exports.text_splitter = exports.vectorstores__xata = exports.vectorstores__vectara = exports.vectorstores__prisma = exports.vectorstores__memory = exports.vectorstores__base = exports.prompts = exports.llms__ollama = exports.llms__aleph_alpha = exports.llms__ai21 = exports.llms__openai = exports.llms__base = exports.embeddings__minimax = exports.embeddings__openai = exports.embeddings__ollama = exports.embeddings__fake = exports.embeddings__cache_backed = exports.embeddings__base = exports.chains__openai_functions = exports.chains = exports.tools = exports.base_language = exports.agents__toolkits = exports.agents = exports.load__serializable = void 0;
28
- exports.evaluation = exports.experimental__plan_and_execute = exports.experimental__generative_agents = exports.experimental__babyagi = exports.experimental__autogpt = exports.util__math = exports.storage__in_memory = exports.stores__message__in_memory = exports.stores__file__in_memory = exports.stores__doc__in_memory = exports.cache = exports.retrievers__vespa = exports.retrievers__score_threshold = exports.retrievers__hyde = exports.retrievers__document_compressors__chain_extract = exports.retrievers__time_weighted = exports.retrievers__parent_document = exports.retrievers__multi_vector = exports.retrievers__multi_query = void 0;
28
+ exports.evaluation = exports.experimental__chat_models__bittensor = exports.experimental__plan_and_execute = exports.experimental__generative_agents = exports.experimental__babyagi = exports.experimental__autogpt = exports.util__math = exports.storage__in_memory = exports.stores__message__in_memory = exports.stores__file__in_memory = exports.stores__doc__in_memory = exports.cache = exports.retrievers__vespa = exports.retrievers__score_threshold = exports.retrievers__hyde = exports.retrievers__document_compressors__chain_extract = exports.retrievers__time_weighted = exports.retrievers__parent_document = exports.retrievers__multi_vector = exports.retrievers__multi_query = void 0;
29
29
  exports.load__serializable = __importStar(require("../load/serializable.cjs"));
30
30
  exports.agents = __importStar(require("../agents/index.cjs"));
31
31
  exports.agents__toolkits = __importStar(require("../agents/toolkits/index.cjs"));
@@ -94,4 +94,5 @@ exports.experimental__autogpt = __importStar(require("../experimental/autogpt/in
94
94
  exports.experimental__babyagi = __importStar(require("../experimental/babyagi/index.cjs"));
95
95
  exports.experimental__generative_agents = __importStar(require("../experimental/generative_agents/index.cjs"));
96
96
  exports.experimental__plan_and_execute = __importStar(require("../experimental/plan_and_execute/index.cjs"));
97
+ exports.experimental__chat_models__bittensor = __importStar(require("../experimental/chat_models/bittensor.cjs"));
97
98
  exports.evaluation = __importStar(require("../evaluation/index.cjs"));
@@ -66,4 +66,5 @@ export * as experimental__autogpt from "../experimental/autogpt/index.js";
66
66
  export * as experimental__babyagi from "../experimental/babyagi/index.js";
67
67
  export * as experimental__generative_agents from "../experimental/generative_agents/index.js";
68
68
  export * as experimental__plan_and_execute from "../experimental/plan_and_execute/index.js";
69
+ export * as experimental__chat_models__bittensor from "../experimental/chat_models/bittensor.js";
69
70
  export * as evaluation from "../evaluation/index.js";
@@ -67,4 +67,5 @@ export * as experimental__autogpt from "../experimental/autogpt/index.js";
67
67
  export * as experimental__babyagi from "../experimental/babyagi/index.js";
68
68
  export * as experimental__generative_agents from "../experimental/generative_agents/index.js";
69
69
  export * as experimental__plan_and_execute from "../experimental/plan_and_execute/index.js";
70
+ export * as experimental__chat_models__bittensor from "../experimental/chat_models/bittensor.js";
70
71
  export * as evaluation from "../evaluation/index.js";
@@ -356,8 +356,14 @@ class ChatPromptTemplate extends BaseChatPromptTemplate {
356
356
  };
357
357
  return new ChatPromptTemplate(promptDict);
358
358
  }
359
+ /**
360
+ * Create a chat model-specific prompt from individual chat messages
361
+ * or message-like tuples.
362
+ * @param promptMessages Messages to be passed to the chat model
363
+ * @returns A new ChatPromptTemplate
364
+ */
359
365
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
360
- static fromPromptMessages(promptMessages) {
366
+ static fromMessages(promptMessages) {
361
367
  const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(
362
368
  // eslint-disable-next-line no-instanceof/no-instanceof
363
369
  promptMessage instanceof ChatPromptTemplate
@@ -386,5 +392,10 @@ class ChatPromptTemplate extends BaseChatPromptTemplate {
386
392
  partialVariables: flattenedPartialVariables,
387
393
  });
388
394
  }
395
+ /** @deprecated Renamed to .fromMessages */
396
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
397
+ static fromPromptMessages(promptMessages) {
398
+ return this.fromMessages(promptMessages);
399
+ }
389
400
  }
390
401
  exports.ChatPromptTemplate = ChatPromptTemplate;
@@ -169,5 +169,13 @@ export declare class ChatPromptTemplate<RunInput extends InputValues = any, Part
169
169
  _getPromptType(): "chat";
170
170
  formatMessages(values: TypedPromptInputValues<RunInput>): Promise<BaseMessage[]>;
171
171
  partial<NewPartialVariableName extends string>(values: PartialValues<NewPartialVariableName>): Promise<ChatPromptTemplate<InputValues<Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>>, any>>;
172
+ /**
173
+ * Create a chat model-specific prompt from individual chat messages
174
+ * or message-like tuples.
175
+ * @param promptMessages Messages to be passed to the chat model
176
+ * @returns A new ChatPromptTemplate
177
+ */
178
+ static fromMessages<RunInput extends InputValues = any>(promptMessages: (ChatPromptTemplate<InputValues, string> | BaseMessagePromptTemplateLike)[]): ChatPromptTemplate<RunInput>;
179
+ /** @deprecated Renamed to .fromMessages */
172
180
  static fromPromptMessages<RunInput extends InputValues = any>(promptMessages: (ChatPromptTemplate<InputValues, string> | BaseMessagePromptTemplateLike)[]): ChatPromptTemplate<RunInput>;
173
181
  }
@@ -344,8 +344,14 @@ export class ChatPromptTemplate extends BaseChatPromptTemplate {
344
344
  };
345
345
  return new ChatPromptTemplate(promptDict);
346
346
  }
347
+ /**
348
+ * Create a chat model-specific prompt from individual chat messages
349
+ * or message-like tuples.
350
+ * @param promptMessages Messages to be passed to the chat model
351
+ * @returns A new ChatPromptTemplate
352
+ */
347
353
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
348
- static fromPromptMessages(promptMessages) {
354
+ static fromMessages(promptMessages) {
349
355
  const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(
350
356
  // eslint-disable-next-line no-instanceof/no-instanceof
351
357
  promptMessage instanceof ChatPromptTemplate
@@ -374,4 +380,9 @@ export class ChatPromptTemplate extends BaseChatPromptTemplate {
374
380
  partialVariables: flattenedPartialVariables,
375
381
  });
376
382
  }
383
+ /** @deprecated Renamed to .fromMessages */
384
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
385
+ static fromPromptMessages(promptMessages) {
386
+ return this.fromMessages(promptMessages);
387
+ }
377
388
  }
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
6
+ exports._coerceToRunnable = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
7
7
  const p_retry_1 = __importDefault(require("p-retry"));
8
8
  const manager_js_1 = require("../../callbacks/manager.cjs");
9
9
  const serializable_js_1 = require("../../load/serializable.cjs");
@@ -790,8 +790,15 @@ class RunnableLambda extends Runnable {
790
790
  });
791
791
  this.func = fields.func;
792
792
  }
793
+ async _invoke(input, config, runManager) {
794
+ let output = await this.func(input);
795
+ if (output && Runnable.isRunnable(output)) {
796
+ output = await output.invoke(input, this._patchConfig(config, runManager?.getChild()));
797
+ }
798
+ return output;
799
+ }
793
800
  async invoke(input, options) {
794
- return this._callWithConfig(async (input) => this.func(input), input, options);
801
+ return this._callWithConfig(this._invoke, input, options);
795
802
  }
796
803
  }
797
804
  exports.RunnableLambda = RunnableLambda;
@@ -909,3 +916,4 @@ function _coerceToRunnable(coerceable) {
909
916
  throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`);
910
917
  }
911
918
  }
919
+ exports._coerceToRunnable = _coerceToRunnable;
@@ -272,6 +272,7 @@ export declare class RunnableLambda<RunInput, RunOutput> extends Runnable<RunInp
272
272
  constructor(fields: {
273
273
  func: RunnableFunc<RunInput, RunOutput>;
274
274
  });
275
+ _invoke(input: RunInput, config?: Partial<BaseCallbackConfig>, runManager?: CallbackManagerForChainRun): Promise<RunOutput>;
275
276
  invoke(input: RunInput, options?: Partial<BaseCallbackConfig>): Promise<RunOutput>;
276
277
  }
277
278
  /**
@@ -297,4 +298,5 @@ export declare class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable
297
298
  }): Promise<(RunOutput | Error)[]>;
298
299
  batch(inputs: RunInput[], options?: Partial<BaseCallbackConfig> | Partial<BaseCallbackConfig>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
299
300
  }
301
+ export declare function _coerceToRunnable<RunInput, RunOutput>(coerceable: RunnableLike<RunInput, RunOutput>): Runnable<RunInput, Exclude<RunOutput, Error>>;
300
302
  export {};
@@ -778,8 +778,15 @@ export class RunnableLambda extends Runnable {
778
778
  });
779
779
  this.func = fields.func;
780
780
  }
781
+ async _invoke(input, config, runManager) {
782
+ let output = await this.func(input);
783
+ if (output && Runnable.isRunnable(output)) {
784
+ output = await output.invoke(input, this._patchConfig(config, runManager?.getChild()));
785
+ }
786
+ return output;
787
+ }
781
788
  async invoke(input, options) {
782
- return this._callWithConfig(async (input) => this.func(input), input, options);
789
+ return this._callWithConfig(this._invoke, input, options);
783
790
  }
784
791
  }
785
792
  /**
@@ -875,7 +882,7 @@ export class RunnableWithFallbacks extends Runnable {
875
882
  }
876
883
  }
877
884
  // TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
878
- function _coerceToRunnable(coerceable) {
885
+ export function _coerceToRunnable(coerceable) {
879
886
  if (typeof coerceable === "function") {
880
887
  return new RunnableLambda({ func: coerceable });
881
888
  }
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RunnableBranch = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ /**
6
+ * Class that represents a runnable branch. The RunnableBranch is
7
+ * initialized with an array of branches and a default branch. When invoked,
8
+ * it evaluates the condition of each branch in order and executes the
9
+ * corresponding branch if the condition is true. If none of the conditions
10
+ * are true, it executes the default branch.
11
+ */
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+ class RunnableBranch extends base_js_1.Runnable {
14
+ static lc_name() {
15
+ return "RunnableBranch";
16
+ }
17
+ constructor(fields) {
18
+ super(fields);
19
+ Object.defineProperty(this, "lc_namespace", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: ["langchain", "runnable", "branch"]
24
+ });
25
+ Object.defineProperty(this, "lc_serializable", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: true
30
+ });
31
+ Object.defineProperty(this, "default", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: void 0
36
+ });
37
+ Object.defineProperty(this, "branches", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ this.branches = fields.branches;
44
+ this.default = fields.default;
45
+ }
46
+ /**
47
+ * Convenience method for instantiating a RunnableBranch from
48
+ * RunnableLikes (objects, functions, or Runnables).
49
+ *
50
+ * Each item in the input except for the last one should be a
51
+ * tuple with two items. The first is a "condition" RunnableLike that
52
+ * returns "true" if the second RunnableLike in the tuple should run.
53
+ *
54
+ * The final item in the input should be a RunnableLike that acts as a
55
+ * default branch if no other branches match.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * import { RunnableBranch } from "langchain/schema/runnable";
60
+ *
61
+ * const branch = RunnableBranch.from([
62
+ * [(x: number) => x > 0, (x: number) => x + 1],
63
+ * [(x: number) => x < 0, (x: number) => x - 1],
64
+ * (x: number) => x
65
+ * ]);
66
+ * ```
67
+ * @param branches An array where the every item except the last is a tuple of [condition, runnable]
68
+ * pairs. The last item is a default runnable which is invoked if no other condition matches.
69
+ * @returns A new RunnableBranch.
70
+ */
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ static from(branches) {
73
+ if (branches.length < 1) {
74
+ throw new Error("RunnableBranch requires at least one branch");
75
+ }
76
+ const branchLikes = branches.slice(0, -1);
77
+ const coercedBranches = branchLikes.map(([condition, runnable]) => [
78
+ (0, base_js_1._coerceToRunnable)(condition),
79
+ (0, base_js_1._coerceToRunnable)(runnable),
80
+ ]);
81
+ const defaultBranch = (0, base_js_1._coerceToRunnable)(branches[branches.length - 1]);
82
+ return new this({
83
+ branches: coercedBranches,
84
+ default: defaultBranch,
85
+ });
86
+ }
87
+ async _invoke(input, config, runManager) {
88
+ let result;
89
+ for (let i = 0; i < this.branches.length; i += 1) {
90
+ const [condition, branchRunnable] = this.branches[i];
91
+ const conditionValue = await condition.invoke(input, this._patchConfig(config, runManager?.getChild(`condition:${i + 1}`)));
92
+ if (conditionValue) {
93
+ result = await branchRunnable.invoke(input, this._patchConfig(config, runManager?.getChild(`branch:${i + 1}`)));
94
+ break;
95
+ }
96
+ }
97
+ if (!result) {
98
+ result = await this.default.invoke(input, this._patchConfig(config, runManager?.getChild("default")));
99
+ }
100
+ return result;
101
+ }
102
+ async invoke(input, config = {}) {
103
+ return this._callWithConfig(this._invoke, input, config);
104
+ }
105
+ }
106
+ exports.RunnableBranch = RunnableBranch;
@@ -0,0 +1,66 @@
1
+ import { Runnable, RunnableLike } from "./base.js";
2
+ import { RunnableConfig } from "./config.js";
3
+ import { CallbackManagerForChainRun } from "../../callbacks/manager.js";
4
+ /**
5
+ * Type for a branch in the RunnableBranch. It consists of a condition
6
+ * runnable and a branch runnable. The condition runnable is used to
7
+ * determine whether the branch should be executed, and the branch runnable
8
+ * is executed if the condition is true.
9
+ */
10
+ export type Branch<RunInput, RunOutput> = [
11
+ Runnable<RunInput, boolean>,
12
+ Runnable<RunInput, RunOutput>
13
+ ];
14
+ export type BranchLike<RunInput, RunOutput> = [
15
+ RunnableLike<RunInput, boolean>,
16
+ RunnableLike<RunInput, RunOutput>
17
+ ];
18
+ /**
19
+ * Class that represents a runnable branch. The RunnableBranch is
20
+ * initialized with an array of branches and a default branch. When invoked,
21
+ * it evaluates the condition of each branch in order and executes the
22
+ * corresponding branch if the condition is true. If none of the conditions
23
+ * are true, it executes the default branch.
24
+ */
25
+ export declare class RunnableBranch<RunInput = any, RunOutput = any> extends Runnable<RunInput, RunOutput> {
26
+ static lc_name(): string;
27
+ lc_namespace: string[];
28
+ lc_serializable: boolean;
29
+ default: Runnable<RunInput, RunOutput>;
30
+ branches: Branch<RunInput, RunOutput>[];
31
+ constructor(fields: {
32
+ branches: Branch<RunInput, RunOutput>[];
33
+ default: Runnable<RunInput, RunOutput>;
34
+ });
35
+ /**
36
+ * Convenience method for instantiating a RunnableBranch from
37
+ * RunnableLikes (objects, functions, or Runnables).
38
+ *
39
+ * Each item in the input except for the last one should be a
40
+ * tuple with two items. The first is a "condition" RunnableLike that
41
+ * returns "true" if the second RunnableLike in the tuple should run.
42
+ *
43
+ * The final item in the input should be a RunnableLike that acts as a
44
+ * default branch if no other branches match.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import { RunnableBranch } from "langchain/schema/runnable";
49
+ *
50
+ * const branch = RunnableBranch.from([
51
+ * [(x: number) => x > 0, (x: number) => x + 1],
52
+ * [(x: number) => x < 0, (x: number) => x - 1],
53
+ * (x: number) => x
54
+ * ]);
55
+ * ```
56
+ * @param branches An array where the every item except the last is a tuple of [condition, runnable]
57
+ * pairs. The last item is a default runnable which is invoked if no other condition matches.
58
+ * @returns A new RunnableBranch.
59
+ */
60
+ static from<RunInput = any, RunOutput = any>(branches: [
61
+ ...BranchLike<RunInput, RunOutput>[],
62
+ RunnableLike<RunInput, RunOutput>
63
+ ]): RunnableBranch<RunInput, RunOutput>;
64
+ _invoke(input: RunInput, config?: Partial<RunnableConfig>, runManager?: CallbackManagerForChainRun): Promise<RunOutput>;
65
+ invoke(input: RunInput, config?: RunnableConfig): Promise<RunOutput>;
66
+ }
@@ -0,0 +1,102 @@
1
+ import { Runnable, _coerceToRunnable } from "./base.js";
2
+ /**
3
+ * Class that represents a runnable branch. The RunnableBranch is
4
+ * initialized with an array of branches and a default branch. When invoked,
5
+ * it evaluates the condition of each branch in order and executes the
6
+ * corresponding branch if the condition is true. If none of the conditions
7
+ * are true, it executes the default branch.
8
+ */
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ export class RunnableBranch extends Runnable {
11
+ static lc_name() {
12
+ return "RunnableBranch";
13
+ }
14
+ constructor(fields) {
15
+ super(fields);
16
+ Object.defineProperty(this, "lc_namespace", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: ["langchain", "runnable", "branch"]
21
+ });
22
+ Object.defineProperty(this, "lc_serializable", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: true
27
+ });
28
+ Object.defineProperty(this, "default", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: void 0
33
+ });
34
+ Object.defineProperty(this, "branches", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: void 0
39
+ });
40
+ this.branches = fields.branches;
41
+ this.default = fields.default;
42
+ }
43
+ /**
44
+ * Convenience method for instantiating a RunnableBranch from
45
+ * RunnableLikes (objects, functions, or Runnables).
46
+ *
47
+ * Each item in the input except for the last one should be a
48
+ * tuple with two items. The first is a "condition" RunnableLike that
49
+ * returns "true" if the second RunnableLike in the tuple should run.
50
+ *
51
+ * The final item in the input should be a RunnableLike that acts as a
52
+ * default branch if no other branches match.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { RunnableBranch } from "langchain/schema/runnable";
57
+ *
58
+ * const branch = RunnableBranch.from([
59
+ * [(x: number) => x > 0, (x: number) => x + 1],
60
+ * [(x: number) => x < 0, (x: number) => x - 1],
61
+ * (x: number) => x
62
+ * ]);
63
+ * ```
64
+ * @param branches An array where the every item except the last is a tuple of [condition, runnable]
65
+ * pairs. The last item is a default runnable which is invoked if no other condition matches.
66
+ * @returns A new RunnableBranch.
67
+ */
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ static from(branches) {
70
+ if (branches.length < 1) {
71
+ throw new Error("RunnableBranch requires at least one branch");
72
+ }
73
+ const branchLikes = branches.slice(0, -1);
74
+ const coercedBranches = branchLikes.map(([condition, runnable]) => [
75
+ _coerceToRunnable(condition),
76
+ _coerceToRunnable(runnable),
77
+ ]);
78
+ const defaultBranch = _coerceToRunnable(branches[branches.length - 1]);
79
+ return new this({
80
+ branches: coercedBranches,
81
+ default: defaultBranch,
82
+ });
83
+ }
84
+ async _invoke(input, config, runManager) {
85
+ let result;
86
+ for (let i = 0; i < this.branches.length; i += 1) {
87
+ const [condition, branchRunnable] = this.branches[i];
88
+ const conditionValue = await condition.invoke(input, this._patchConfig(config, runManager?.getChild(`condition:${i + 1}`)));
89
+ if (conditionValue) {
90
+ result = await branchRunnable.invoke(input, this._patchConfig(config, runManager?.getChild(`branch:${i + 1}`)));
91
+ break;
92
+ }
93
+ }
94
+ if (!result) {
95
+ result = await this.default.invoke(input, this._patchConfig(config, runManager?.getChild("default")));
96
+ }
97
+ return result;
98
+ }
99
+ async invoke(input, config = {}) {
100
+ return this._callWithConfig(this._invoke, input, config);
101
+ }
102
+ }
@@ -1,22 +1,18 @@
1
1
  "use strict";
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
2
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.RouterRunnable = exports.RunnablePassthrough = void 0;
18
- __exportStar(require("./base.cjs"), exports);
3
+ exports.RunnableBranch = exports.RouterRunnable = exports.RunnablePassthrough = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
4
+ var base_js_1 = require("./base.cjs");
5
+ Object.defineProperty(exports, "Runnable", { enumerable: true, get: function () { return base_js_1.Runnable; } });
6
+ Object.defineProperty(exports, "RunnableBinding", { enumerable: true, get: function () { return base_js_1.RunnableBinding; } });
7
+ Object.defineProperty(exports, "RunnableEach", { enumerable: true, get: function () { return base_js_1.RunnableEach; } });
8
+ Object.defineProperty(exports, "RunnableRetry", { enumerable: true, get: function () { return base_js_1.RunnableRetry; } });
9
+ Object.defineProperty(exports, "RunnableSequence", { enumerable: true, get: function () { return base_js_1.RunnableSequence; } });
10
+ Object.defineProperty(exports, "RunnableMap", { enumerable: true, get: function () { return base_js_1.RunnableMap; } });
11
+ Object.defineProperty(exports, "RunnableLambda", { enumerable: true, get: function () { return base_js_1.RunnableLambda; } });
12
+ Object.defineProperty(exports, "RunnableWithFallbacks", { enumerable: true, get: function () { return base_js_1.RunnableWithFallbacks; } });
19
13
  var passthrough_js_1 = require("./passthrough.cjs");
20
14
  Object.defineProperty(exports, "RunnablePassthrough", { enumerable: true, get: function () { return passthrough_js_1.RunnablePassthrough; } });
21
15
  var router_js_1 = require("./router.cjs");
22
16
  Object.defineProperty(exports, "RouterRunnable", { enumerable: true, get: function () { return router_js_1.RouterRunnable; } });
17
+ var branch_js_1 = require("./branch.cjs");
18
+ Object.defineProperty(exports, "RunnableBranch", { enumerable: true, get: function () { return branch_js_1.RunnableBranch; } });
@@ -1,4 +1,5 @@
1
- export * from "./base.js";
1
+ export { RunnableFunc, RunnableLike, RunnableBatchOptions, RunnableRetryFailedAttemptHandler, Runnable, RunnableBindingArgs, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableLambda, RunnableWithFallbacks, } from "./base.js";
2
2
  export { RunnableConfig } from "./config.js";
3
3
  export { RunnablePassthrough } from "./passthrough.js";
4
4
  export { RouterRunnable } from "./router.js";
5
+ export { RunnableBranch, Branch, BranchLike } from "./branch.js";
@@ -1,3 +1,4 @@
1
- export * from "./base.js";
1
+ export { Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableLambda, RunnableWithFallbacks, } from "./base.js";
2
2
  export { RunnablePassthrough } from "./passthrough.js";
3
3
  export { RouterRunnable } from "./router.js";
4
+ export { RunnableBranch } from "./branch.js";