@langchain/core 1.1.2 → 1.1.3
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.
- package/CHANGELOG.md +10 -0
- package/dist/agents.d.cts +0 -2
- package/dist/agents.d.ts +0 -2
- package/dist/callbacks/base.d.cts +22 -60
- package/dist/callbacks/base.d.ts +22 -60
- package/dist/callbacks/dispatch/index.d.cts +1 -3
- package/dist/callbacks/dispatch/index.d.ts +1 -3
- package/dist/callbacks/dispatch/web.d.cts +1 -3
- package/dist/callbacks/dispatch/web.d.ts +1 -3
- package/dist/callbacks/manager.d.cts +2 -12
- package/dist/callbacks/manager.d.ts +2 -12
- package/dist/chat_history.cjs +1 -1
- package/dist/chat_history.d.cts +0 -1
- package/dist/chat_history.d.ts +0 -1
- package/dist/chat_history.js +1 -1
- package/dist/document_loaders/langsmith.d.cts +0 -3
- package/dist/document_loaders/langsmith.d.ts +0 -3
- package/dist/documents/document.d.cts +3 -12
- package/dist/documents/document.d.ts +3 -12
- package/dist/example_selectors/length_based.d.cts +1 -1
- package/dist/example_selectors/length_based.d.ts +1 -1
- package/dist/indexing/base.d.cts +0 -1
- package/dist/indexing/base.d.ts +0 -1
- package/dist/indexing/record_manager.d.cts +0 -1
- package/dist/indexing/record_manager.d.ts +0 -1
- package/dist/language_models/base.d.cts +8 -38
- package/dist/language_models/base.d.ts +8 -38
- package/dist/language_models/chat_models.cjs +1 -1
- package/dist/language_models/chat_models.d.cts +6 -33
- package/dist/language_models/chat_models.d.ts +6 -33
- package/dist/language_models/chat_models.js +1 -1
- package/dist/language_models/llms.d.cts +0 -6
- package/dist/language_models/llms.d.ts +0 -6
- package/dist/load/import_type.d.cts +0 -1
- package/dist/load/import_type.d.ts +0 -1
- package/dist/load/map_keys.cjs +4 -5
- package/dist/load/map_keys.cjs.map +1 -1
- package/dist/load/map_keys.d.cts +0 -1
- package/dist/load/map_keys.d.ts +0 -1
- package/dist/load/map_keys.js +3 -3
- package/dist/load/map_keys.js.map +1 -1
- package/dist/load/serializable.d.cts +0 -1
- package/dist/load/serializable.d.ts +0 -1
- package/dist/memory.d.cts +0 -3
- package/dist/memory.d.ts +0 -3
- package/dist/messages/ai.cjs +6 -48
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js +6 -48
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs +3 -2
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts +1 -13
- package/dist/messages/base.d.ts +1 -13
- package/dist/messages/base.js +3 -2
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/content/data.d.cts +2 -7
- package/dist/messages/content/data.d.ts +2 -7
- package/dist/messages/content/index.d.cts +1 -4
- package/dist/messages/content/index.d.ts +1 -4
- package/dist/messages/content/multimodal.d.cts +0 -1
- package/dist/messages/content/multimodal.d.ts +0 -1
- package/dist/messages/content/tools.d.cts +0 -1
- package/dist/messages/content/tools.d.ts +0 -1
- package/dist/messages/index.cjs +4 -2
- package/dist/messages/index.d.cts +2 -2
- package/dist/messages/index.d.ts +2 -2
- package/dist/messages/index.js +5 -4
- package/dist/messages/tool.d.cts +2 -9
- package/dist/messages/tool.d.ts +2 -9
- package/dist/messages/transformers.cjs +2 -2
- package/dist/messages/transformers.d.cts +0 -3
- package/dist/messages/transformers.d.ts +0 -3
- package/dist/messages/transformers.js +2 -2
- package/dist/messages/utils.cjs +77 -4
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.d.cts +35 -7
- package/dist/messages/utils.d.ts +35 -7
- package/dist/messages/utils.js +77 -5
- package/dist/messages/utils.js.map +1 -1
- package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.cjs +169 -0
- package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.js +168 -0
- package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.js.map +1 -0
- package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.cjs +122 -0
- package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.js +121 -0
- package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.js.map +1 -0
- package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.cjs +18 -0
- package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.js +17 -0
- package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.js.map +1 -0
- package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.cjs +27 -0
- package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js +26 -0
- package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js.map +1 -0
- package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.cjs +141 -0
- package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.js +141 -0
- package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.js.map +1 -0
- package/dist/output_parsers/json.d.cts +1 -5
- package/dist/output_parsers/json.d.ts +1 -5
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.cts +2 -6
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.ts +2 -6
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts +10 -34
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts +10 -34
- package/dist/output_parsers/transform.d.cts +0 -1
- package/dist/output_parsers/transform.d.ts +0 -1
- package/dist/outputs.d.cts +0 -6
- package/dist/outputs.d.ts +0 -6
- package/dist/prompts/base.d.cts +2 -10
- package/dist/prompts/base.d.ts +2 -10
- package/dist/prompts/chat.cjs +2 -2
- package/dist/prompts/chat.d.cts +13 -51
- package/dist/prompts/chat.d.ts +13 -51
- package/dist/prompts/chat.js +2 -2
- package/dist/prompts/few_shot.d.cts +1 -5
- package/dist/prompts/few_shot.d.ts +1 -5
- package/dist/prompts/image.d.cts +2 -10
- package/dist/prompts/image.d.ts +2 -10
- package/dist/prompts/prompt.d.cts +4 -15
- package/dist/prompts/prompt.d.ts +4 -16
- package/dist/prompts/serde.d.cts +0 -1
- package/dist/prompts/serde.d.ts +0 -1
- package/dist/prompts/string.d.cts +1 -5
- package/dist/prompts/string.d.ts +1 -5
- package/dist/prompts/structured.d.cts +3 -16
- package/dist/prompts/structured.d.ts +3 -16
- package/dist/retrievers/document_compressors/index.d.cts +0 -1
- package/dist/retrievers/document_compressors/index.d.ts +0 -1
- package/dist/retrievers/index.d.cts +2 -6
- package/dist/retrievers/index.d.ts +2 -6
- package/dist/runnables/base.cjs +7 -7
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.d.cts +12 -64
- package/dist/runnables/base.d.ts +12 -64
- package/dist/runnables/base.js +1 -1
- package/dist/runnables/branch.d.cts +0 -2
- package/dist/runnables/branch.d.ts +0 -2
- package/dist/runnables/config.d.cts +0 -1
- package/dist/runnables/config.d.ts +0 -1
- package/dist/runnables/graph.d.cts +1 -5
- package/dist/runnables/graph.d.ts +1 -5
- package/dist/runnables/graph_mermaid.cjs +2 -1
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js +3 -1
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/dist/runnables/history.cjs +1 -1
- package/dist/runnables/history.d.cts +4 -12
- package/dist/runnables/history.d.ts +4 -12
- package/dist/runnables/history.js +1 -1
- package/dist/runnables/passthrough.d.cts +0 -2
- package/dist/runnables/passthrough.d.ts +0 -2
- package/dist/runnables/router.d.cts +0 -1
- package/dist/runnables/router.d.ts +0 -1
- package/dist/runnables/types.d.cts +2 -9
- package/dist/runnables/types.d.ts +2 -9
- package/dist/runnables/utils.cjs +5 -0
- package/dist/runnables/utils.cjs.map +1 -1
- package/dist/runnables/utils.js +5 -1
- package/dist/runnables/utils.js.map +1 -1
- package/dist/singletons/async_local_storage/context.d.cts +0 -2
- package/dist/singletons/async_local_storage/context.d.ts +0 -2
- package/dist/singletons/async_local_storage/globals.d.cts +0 -1
- package/dist/singletons/async_local_storage/globals.d.ts +0 -1
- package/dist/singletons/callbacks.cjs.map +1 -1
- package/dist/singletons/callbacks.js.map +1 -1
- package/dist/stores.d.cts +0 -1
- package/dist/stores.d.ts +0 -1
- package/dist/structured_query/utils.d.cts +1 -4
- package/dist/structured_query/utils.d.ts +1 -4
- package/dist/tools/index.d.cts +1 -6
- package/dist/tools/index.d.ts +1 -6
- package/dist/tools/types.d.cts +3 -13
- package/dist/tools/types.d.ts +3 -13
- package/dist/tracers/base.d.cts +1 -20
- package/dist/tracers/base.d.ts +1 -20
- package/dist/tracers/console.cjs +3 -3
- package/dist/tracers/console.cjs.map +1 -1
- package/dist/tracers/console.d.cts +0 -2
- package/dist/tracers/console.d.ts +0 -2
- package/dist/tracers/console.js +3 -3
- package/dist/tracers/console.js.map +1 -1
- package/dist/tracers/event_stream.d.cts +0 -4
- package/dist/tracers/event_stream.d.ts +0 -4
- package/dist/tracers/log_stream.d.cts +0 -6
- package/dist/tracers/log_stream.d.ts +0 -6
- package/dist/types/_internal.d.cts +0 -3
- package/dist/types/_internal.d.ts +0 -3
- package/dist/types/type-utils.d.cts +0 -2
- package/dist/types/type-utils.d.ts +0 -2
- package/dist/utils/async_caller.cjs +2 -7
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.d.cts +0 -3
- package/dist/utils/async_caller.d.ts +0 -3
- package/dist/utils/async_caller.js +1 -6
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/env.d.cts +0 -4
- package/dist/utils/env.d.ts +0 -4
- package/dist/utils/event_source_parse.d.cts +1 -4
- package/dist/utils/event_source_parse.d.ts +1 -4
- package/dist/utils/function_calling.d.cts +1 -3
- package/dist/utils/function_calling.d.ts +1 -3
- package/dist/utils/json.d.cts +0 -1
- package/dist/utils/json.d.ts +0 -1
- package/dist/utils/stream.d.cts +1 -13
- package/dist/utils/stream.d.ts +1 -13
- package/dist/utils/testing/chat_models.d.cts +3 -11
- package/dist/utils/testing/chat_models.d.ts +3 -11
- package/dist/utils/testing/message_history.cjs +1 -1
- package/dist/utils/testing/message_history.js +1 -1
- package/dist/utils/testing/retrievers.d.cts +1 -3
- package/dist/utils/testing/retrievers.d.ts +1 -3
- package/dist/utils/testing/vectorstores.d.cts +0 -1
- package/dist/utils/testing/vectorstores.d.ts +0 -1
- package/dist/utils/types/index.cjs +4 -0
- package/dist/utils/types/index.d.cts +2 -4
- package/dist/utils/types/index.d.ts +2 -4
- package/dist/utils/types/index.js +4 -2
- package/dist/utils/types/zod.cjs +24 -0
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.d.cts +4 -4
- package/dist/utils/types/zod.d.ts +4 -4
- package/dist/utils/types/zod.js +23 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/vectorstores.d.cts +5 -17
- package/dist/vectorstores.d.ts +5 -17
- package/package.json +6 -6
|
@@ -11,33 +11,15 @@ import { Graph } from "./graph.cjs";
|
|
|
11
11
|
import { TraceableFunction } from "langsmith/singletons/traceable";
|
|
12
12
|
|
|
13
13
|
//#region src/runnables/base.d.ts
|
|
14
|
-
type RunnableFunc<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = (input: RunInput, options: CallOptions
|
|
15
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
-
| Record<string, any>
|
|
17
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
18
|
-
| (Record<string, any> & CallOptions)) => RunOutput | Promise<RunOutput>;
|
|
14
|
+
type RunnableFunc<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = (input: RunInput, options: CallOptions | Record<string, any> | (Record<string, any> & CallOptions)) => RunOutput | Promise<RunOutput>;
|
|
19
15
|
type RunnableMapLike<RunInput, RunOutput> = { [K in keyof RunOutput]: RunnableLike<RunInput, RunOutput[K]> };
|
|
20
|
-
type RunnableLike<
|
|
21
|
-
|
|
22
|
-
RunInput = any,
|
|
23
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
24
|
-
RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> = RunnableInterface<RunInput, RunOutput, CallOptions> | RunnableFunc<RunInput, RunOutput, CallOptions> | RunnableMapLike<RunInput, RunOutput>;
|
|
25
|
-
type RunnableRetryFailedAttemptHandler = (
|
|
26
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
27
|
-
error: any,
|
|
28
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
29
|
-
input: any
|
|
30
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
31
|
-
) => any;
|
|
16
|
+
type RunnableLike<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> = RunnableInterface<RunInput, RunOutput, CallOptions> | RunnableFunc<RunInput, RunOutput, CallOptions> | RunnableMapLike<RunInput, RunOutput>;
|
|
17
|
+
type RunnableRetryFailedAttemptHandler = (error: any, input: any) => any;
|
|
32
18
|
/**
|
|
33
19
|
* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
|
|
34
20
|
* transformed.
|
|
35
21
|
*/
|
|
36
|
-
declare abstract class Runnable<
|
|
37
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
38
|
-
RunInput = any,
|
|
39
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
40
|
-
RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Serializable implements RunnableInterface<RunInput, RunOutput, CallOptions> {
|
|
22
|
+
declare abstract class Runnable<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Serializable implements RunnableInterface<RunInput, RunOutput, CallOptions> {
|
|
41
23
|
protected lc_runnable: boolean;
|
|
42
24
|
name?: string;
|
|
43
25
|
getName(suffix?: string): string;
|
|
@@ -281,7 +263,6 @@ RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Se
|
|
|
281
263
|
}, streamOptions?: Omit<EventStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<Uint8Array>;
|
|
282
264
|
private _streamEventsV2;
|
|
283
265
|
private _streamEventsV1;
|
|
284
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
285
266
|
static isRunnable(thing: any): thing is Runnable;
|
|
286
267
|
/**
|
|
287
268
|
* Bind lifecycle listeners to a Runnable, returning a new Runnable.
|
|
@@ -405,11 +386,7 @@ declare class RunnableBinding<RunInput, RunOutput, CallOptions extends RunnableC
|
|
|
405
386
|
version: "v1" | "v2";
|
|
406
387
|
encoding: "text/event-stream";
|
|
407
388
|
}, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<Uint8Array>;
|
|
408
|
-
static isRunnableBinding(
|
|
409
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
410
|
-
thing: any
|
|
411
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
412
|
-
): thing is RunnableBinding<any, any, any>;
|
|
389
|
+
static isRunnableBinding(thing: any): thing is RunnableBinding<any, any, any>;
|
|
413
390
|
/**
|
|
414
391
|
* Bind lifecycle listeners to a Runnable, returning a new Runnable.
|
|
415
392
|
* The Run object contains information about the run, including its id,
|
|
@@ -539,11 +516,7 @@ declare class RunnableEach<RunInputItem, RunOutputItem, CallOptions extends Runn
|
|
|
539
516
|
* });
|
|
540
517
|
* ```
|
|
541
518
|
*/
|
|
542
|
-
declare class RunnableRetry<
|
|
543
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
544
|
-
RunInput = any,
|
|
545
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
546
|
-
RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends RunnableBinding<RunInput, RunOutput, CallOptions> {
|
|
519
|
+
declare class RunnableRetry<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends RunnableBinding<RunInput, RunOutput, CallOptions> {
|
|
547
520
|
static lc_name(): string;
|
|
548
521
|
lc_namespace: string[];
|
|
549
522
|
protected maxAttemptNumber: number;
|
|
@@ -577,7 +550,6 @@ RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Ru
|
|
|
577
550
|
type RunnableSequenceFields<RunInput, RunOutput> = {
|
|
578
551
|
first: Runnable<RunInput>;
|
|
579
552
|
middle?: Runnable[];
|
|
580
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
581
553
|
last: Runnable<any, RunOutput>;
|
|
582
554
|
name?: string;
|
|
583
555
|
omitSequenceTags?: boolean;
|
|
@@ -593,15 +565,10 @@ type RunnableSequenceFields<RunInput, RunOutput> = {
|
|
|
593
565
|
* const result = await chain.invoke({ topic: "bears" });
|
|
594
566
|
* ```
|
|
595
567
|
*/
|
|
596
|
-
declare class RunnableSequence<
|
|
597
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
598
|
-
RunInput = any,
|
|
599
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
600
|
-
RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
568
|
+
declare class RunnableSequence<RunInput = any, RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
601
569
|
static lc_name(): string;
|
|
602
570
|
protected first: Runnable<RunInput>;
|
|
603
571
|
protected middle: Runnable[];
|
|
604
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
605
572
|
protected last: Runnable<any, RunOutput>;
|
|
606
573
|
omitSequenceTags: boolean;
|
|
607
574
|
lc_serializable: boolean;
|
|
@@ -621,12 +588,8 @@ RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
|
621
588
|
_streamIterator(input: RunInput, options?: RunnableConfig): AsyncGenerator<RunOutput>;
|
|
622
589
|
getGraph(config?: RunnableConfig): Graph;
|
|
623
590
|
pipe<NewRunOutput>(coerceable: RunnableLike<RunOutput, NewRunOutput>): RunnableSequence<RunInput, Exclude<NewRunOutput, Error>>;
|
|
624
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
625
591
|
static isRunnableSequence(thing: any): thing is RunnableSequence;
|
|
626
|
-
|
|
627
|
-
static from<RunInput = any, RunOutput = any>([first, ...runnables]: [RunnableLike<RunInput>, ...RunnableLike[],
|
|
628
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
629
|
-
RunnableLike<any, RunOutput>], nameOrFields?: string | Omit<RunnableSequenceFields<RunInput, RunOutput>, "first" | "middle" | "last">): RunnableSequence<RunInput, Exclude<RunOutput, Error>>;
|
|
592
|
+
static from<RunInput = any, RunOutput = any>([first, ...runnables]: [RunnableLike<RunInput>, ...RunnableLike[], RunnableLike<any, RunOutput>], nameOrFields?: string | Omit<RunnableSequenceFields<RunInput, RunOutput>, "first" | "middle" | "last">): RunnableSequence<RunInput, Exclude<RunOutput, Error>>;
|
|
630
593
|
}
|
|
631
594
|
/**
|
|
632
595
|
* A runnable that runs a mapping of runnables in parallel,
|
|
@@ -644,11 +607,7 @@ RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
|
644
607
|
* const result = await mapChain.invoke({ topic: "bear" });
|
|
645
608
|
* ```
|
|
646
609
|
*/
|
|
647
|
-
declare class RunnableMap<
|
|
648
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
649
|
-
RunInput = any,
|
|
650
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
651
|
-
RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<RunInput, RunOutput> {
|
|
610
|
+
declare class RunnableMap<RunInput = any, RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<RunInput, RunOutput> {
|
|
652
611
|
static lc_name(): string;
|
|
653
612
|
lc_namespace: string[];
|
|
654
613
|
lc_serializable: boolean;
|
|
@@ -657,9 +616,7 @@ RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<Ru
|
|
|
657
616
|
constructor(fields: {
|
|
658
617
|
steps: RunnableMapLike<RunInput, RunOutput>;
|
|
659
618
|
});
|
|
660
|
-
static from<RunInput,
|
|
661
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
662
|
-
RunOutput extends Record<string, any> = Record<string, any>>(steps: RunnableMapLike<RunInput, RunOutput>): RunnableMap<RunInput, RunOutput>;
|
|
619
|
+
static from<RunInput, RunOutput extends Record<string, any> = Record<string, any>>(steps: RunnableMapLike<RunInput, RunOutput>): RunnableMap<RunInput, RunOutput>;
|
|
663
620
|
invoke(input: RunInput, options?: Partial<RunnableConfig>): Promise<RunOutput>;
|
|
664
621
|
_transform(generator: AsyncGenerator<RunInput>, runManager?: CallbackManagerForChainRun, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
|
|
665
622
|
transform(generator: AsyncGenerator<RunInput>, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
|
|
@@ -829,7 +786,6 @@ declare class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable<RunInp
|
|
|
829
786
|
}): Promise<(RunOutput | Error)[]>;
|
|
830
787
|
batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
|
|
831
788
|
}
|
|
832
|
-
// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
|
|
833
789
|
declare function _coerceToRunnable<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig>(coerceable: RunnableLike<RunInput, RunOutput, CallOptions>): Runnable<RunInput, Exclude<RunOutput, Error>, CallOptions>;
|
|
834
790
|
interface RunnableAssignFields<RunInput> {
|
|
835
791
|
mapper: RunnableMap<RunInput>;
|
|
@@ -865,11 +821,7 @@ interface RunnableAssignFields<RunInput> {
|
|
|
865
821
|
* // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } }
|
|
866
822
|
* ```
|
|
867
823
|
*/
|
|
868
|
-
declare class RunnableAssign<
|
|
869
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
870
|
-
RunInput extends Record<string, any> = Record<string, any>,
|
|
871
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
872
|
-
RunOutput extends Record<string, any> = Record<string, any>, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnableAssignFields<RunInput> {
|
|
824
|
+
declare class RunnableAssign<RunInput extends Record<string, any> = Record<string, any>, RunOutput extends Record<string, any> = Record<string, any>, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnableAssignFields<RunInput> {
|
|
873
825
|
static lc_name(): string;
|
|
874
826
|
lc_namespace: string[];
|
|
875
827
|
lc_serializable: boolean;
|
|
@@ -907,11 +859,7 @@ interface RunnablePickFields {
|
|
|
907
859
|
* // { name: 'John', city: 'New York' }
|
|
908
860
|
* ```
|
|
909
861
|
*/
|
|
910
|
-
declare class RunnablePick<
|
|
911
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
912
|
-
RunInput extends Record<string, any> = Record<string, any>,
|
|
913
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
914
|
-
RunOutput extends Record<string, any> | any = Record<string, any> | any, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnablePickFields {
|
|
862
|
+
declare class RunnablePick<RunInput extends Record<string, any> = Record<string, any>, RunOutput extends Record<string, any> | any = Record<string, any> | any, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnablePickFields {
|
|
915
863
|
static lc_name(): string;
|
|
916
864
|
lc_namespace: string[];
|
|
917
865
|
lc_serializable: boolean;
|
package/dist/runnables/base.d.ts
CHANGED
|
@@ -11,33 +11,15 @@ import { Graph } from "./graph.js";
|
|
|
11
11
|
import { TraceableFunction } from "langsmith/singletons/traceable";
|
|
12
12
|
|
|
13
13
|
//#region src/runnables/base.d.ts
|
|
14
|
-
type RunnableFunc<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = (input: RunInput, options: CallOptions
|
|
15
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
-
| Record<string, any>
|
|
17
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
18
|
-
| (Record<string, any> & CallOptions)) => RunOutput | Promise<RunOutput>;
|
|
14
|
+
type RunnableFunc<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = (input: RunInput, options: CallOptions | Record<string, any> | (Record<string, any> & CallOptions)) => RunOutput | Promise<RunOutput>;
|
|
19
15
|
type RunnableMapLike<RunInput, RunOutput> = { [K in keyof RunOutput]: RunnableLike<RunInput, RunOutput[K]> };
|
|
20
|
-
type RunnableLike<
|
|
21
|
-
|
|
22
|
-
RunInput = any,
|
|
23
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
24
|
-
RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> = RunnableInterface<RunInput, RunOutput, CallOptions> | RunnableFunc<RunInput, RunOutput, CallOptions> | RunnableMapLike<RunInput, RunOutput>;
|
|
25
|
-
type RunnableRetryFailedAttemptHandler = (
|
|
26
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
27
|
-
error: any,
|
|
28
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
29
|
-
input: any
|
|
30
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
31
|
-
) => any;
|
|
16
|
+
type RunnableLike<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> = RunnableInterface<RunInput, RunOutput, CallOptions> | RunnableFunc<RunInput, RunOutput, CallOptions> | RunnableMapLike<RunInput, RunOutput>;
|
|
17
|
+
type RunnableRetryFailedAttemptHandler = (error: any, input: any) => any;
|
|
32
18
|
/**
|
|
33
19
|
* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
|
|
34
20
|
* transformed.
|
|
35
21
|
*/
|
|
36
|
-
declare abstract class Runnable<
|
|
37
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
38
|
-
RunInput = any,
|
|
39
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
40
|
-
RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Serializable implements RunnableInterface<RunInput, RunOutput, CallOptions> {
|
|
22
|
+
declare abstract class Runnable<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Serializable implements RunnableInterface<RunInput, RunOutput, CallOptions> {
|
|
41
23
|
protected lc_runnable: boolean;
|
|
42
24
|
name?: string;
|
|
43
25
|
getName(suffix?: string): string;
|
|
@@ -281,7 +263,6 @@ RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Se
|
|
|
281
263
|
}, streamOptions?: Omit<EventStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<Uint8Array>;
|
|
282
264
|
private _streamEventsV2;
|
|
283
265
|
private _streamEventsV1;
|
|
284
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
285
266
|
static isRunnable(thing: any): thing is Runnable;
|
|
286
267
|
/**
|
|
287
268
|
* Bind lifecycle listeners to a Runnable, returning a new Runnable.
|
|
@@ -405,11 +386,7 @@ declare class RunnableBinding<RunInput, RunOutput, CallOptions extends RunnableC
|
|
|
405
386
|
version: "v1" | "v2";
|
|
406
387
|
encoding: "text/event-stream";
|
|
407
388
|
}, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<Uint8Array>;
|
|
408
|
-
static isRunnableBinding(
|
|
409
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
410
|
-
thing: any
|
|
411
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
412
|
-
): thing is RunnableBinding<any, any, any>;
|
|
389
|
+
static isRunnableBinding(thing: any): thing is RunnableBinding<any, any, any>;
|
|
413
390
|
/**
|
|
414
391
|
* Bind lifecycle listeners to a Runnable, returning a new Runnable.
|
|
415
392
|
* The Run object contains information about the run, including its id,
|
|
@@ -539,11 +516,7 @@ declare class RunnableEach<RunInputItem, RunOutputItem, CallOptions extends Runn
|
|
|
539
516
|
* });
|
|
540
517
|
* ```
|
|
541
518
|
*/
|
|
542
|
-
declare class RunnableRetry<
|
|
543
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
544
|
-
RunInput = any,
|
|
545
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
546
|
-
RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends RunnableBinding<RunInput, RunOutput, CallOptions> {
|
|
519
|
+
declare class RunnableRetry<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends RunnableBinding<RunInput, RunOutput, CallOptions> {
|
|
547
520
|
static lc_name(): string;
|
|
548
521
|
lc_namespace: string[];
|
|
549
522
|
protected maxAttemptNumber: number;
|
|
@@ -577,7 +550,6 @@ RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Ru
|
|
|
577
550
|
type RunnableSequenceFields<RunInput, RunOutput> = {
|
|
578
551
|
first: Runnable<RunInput>;
|
|
579
552
|
middle?: Runnable[];
|
|
580
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
581
553
|
last: Runnable<any, RunOutput>;
|
|
582
554
|
name?: string;
|
|
583
555
|
omitSequenceTags?: boolean;
|
|
@@ -593,15 +565,10 @@ type RunnableSequenceFields<RunInput, RunOutput> = {
|
|
|
593
565
|
* const result = await chain.invoke({ topic: "bears" });
|
|
594
566
|
* ```
|
|
595
567
|
*/
|
|
596
|
-
declare class RunnableSequence<
|
|
597
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
598
|
-
RunInput = any,
|
|
599
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
600
|
-
RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
568
|
+
declare class RunnableSequence<RunInput = any, RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
601
569
|
static lc_name(): string;
|
|
602
570
|
protected first: Runnable<RunInput>;
|
|
603
571
|
protected middle: Runnable[];
|
|
604
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
605
572
|
protected last: Runnable<any, RunOutput>;
|
|
606
573
|
omitSequenceTags: boolean;
|
|
607
574
|
lc_serializable: boolean;
|
|
@@ -621,12 +588,8 @@ RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
|
621
588
|
_streamIterator(input: RunInput, options?: RunnableConfig): AsyncGenerator<RunOutput>;
|
|
622
589
|
getGraph(config?: RunnableConfig): Graph;
|
|
623
590
|
pipe<NewRunOutput>(coerceable: RunnableLike<RunOutput, NewRunOutput>): RunnableSequence<RunInput, Exclude<NewRunOutput, Error>>;
|
|
624
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
625
591
|
static isRunnableSequence(thing: any): thing is RunnableSequence;
|
|
626
|
-
|
|
627
|
-
static from<RunInput = any, RunOutput = any>([first, ...runnables]: [RunnableLike<RunInput>, ...RunnableLike[],
|
|
628
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
629
|
-
RunnableLike<any, RunOutput>], nameOrFields?: string | Omit<RunnableSequenceFields<RunInput, RunOutput>, "first" | "middle" | "last">): RunnableSequence<RunInput, Exclude<RunOutput, Error>>;
|
|
592
|
+
static from<RunInput = any, RunOutput = any>([first, ...runnables]: [RunnableLike<RunInput>, ...RunnableLike[], RunnableLike<any, RunOutput>], nameOrFields?: string | Omit<RunnableSequenceFields<RunInput, RunOutput>, "first" | "middle" | "last">): RunnableSequence<RunInput, Exclude<RunOutput, Error>>;
|
|
630
593
|
}
|
|
631
594
|
/**
|
|
632
595
|
* A runnable that runs a mapping of runnables in parallel,
|
|
@@ -644,11 +607,7 @@ RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
|
644
607
|
* const result = await mapChain.invoke({ topic: "bear" });
|
|
645
608
|
* ```
|
|
646
609
|
*/
|
|
647
|
-
declare class RunnableMap<
|
|
648
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
649
|
-
RunInput = any,
|
|
650
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
651
|
-
RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<RunInput, RunOutput> {
|
|
610
|
+
declare class RunnableMap<RunInput = any, RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<RunInput, RunOutput> {
|
|
652
611
|
static lc_name(): string;
|
|
653
612
|
lc_namespace: string[];
|
|
654
613
|
lc_serializable: boolean;
|
|
@@ -657,9 +616,7 @@ RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<Ru
|
|
|
657
616
|
constructor(fields: {
|
|
658
617
|
steps: RunnableMapLike<RunInput, RunOutput>;
|
|
659
618
|
});
|
|
660
|
-
static from<RunInput,
|
|
661
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
662
|
-
RunOutput extends Record<string, any> = Record<string, any>>(steps: RunnableMapLike<RunInput, RunOutput>): RunnableMap<RunInput, RunOutput>;
|
|
619
|
+
static from<RunInput, RunOutput extends Record<string, any> = Record<string, any>>(steps: RunnableMapLike<RunInput, RunOutput>): RunnableMap<RunInput, RunOutput>;
|
|
663
620
|
invoke(input: RunInput, options?: Partial<RunnableConfig>): Promise<RunOutput>;
|
|
664
621
|
_transform(generator: AsyncGenerator<RunInput>, runManager?: CallbackManagerForChainRun, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
|
|
665
622
|
transform(generator: AsyncGenerator<RunInput>, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
|
|
@@ -829,7 +786,6 @@ declare class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable<RunInp
|
|
|
829
786
|
}): Promise<(RunOutput | Error)[]>;
|
|
830
787
|
batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
|
|
831
788
|
}
|
|
832
|
-
// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
|
|
833
789
|
declare function _coerceToRunnable<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig>(coerceable: RunnableLike<RunInput, RunOutput, CallOptions>): Runnable<RunInput, Exclude<RunOutput, Error>, CallOptions>;
|
|
834
790
|
interface RunnableAssignFields<RunInput> {
|
|
835
791
|
mapper: RunnableMap<RunInput>;
|
|
@@ -865,11 +821,7 @@ interface RunnableAssignFields<RunInput> {
|
|
|
865
821
|
* // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } }
|
|
866
822
|
* ```
|
|
867
823
|
*/
|
|
868
|
-
declare class RunnableAssign<
|
|
869
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
870
|
-
RunInput extends Record<string, any> = Record<string, any>,
|
|
871
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
872
|
-
RunOutput extends Record<string, any> = Record<string, any>, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnableAssignFields<RunInput> {
|
|
824
|
+
declare class RunnableAssign<RunInput extends Record<string, any> = Record<string, any>, RunOutput extends Record<string, any> = Record<string, any>, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnableAssignFields<RunInput> {
|
|
873
825
|
static lc_name(): string;
|
|
874
826
|
lc_namespace: string[];
|
|
875
827
|
lc_serializable: boolean;
|
|
@@ -907,11 +859,7 @@ interface RunnablePickFields {
|
|
|
907
859
|
* // { name: 'John', city: 'New York' }
|
|
908
860
|
* ```
|
|
909
861
|
*/
|
|
910
|
-
declare class RunnablePick<
|
|
911
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
912
|
-
RunInput extends Record<string, any> = Record<string, any>,
|
|
913
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
914
|
-
RunOutput extends Record<string, any> | any = Record<string, any> | any, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnablePickFields {
|
|
862
|
+
declare class RunnablePick<RunInput extends Record<string, any> = Record<string, any>, RunOutput extends Record<string, any> | any = Record<string, any> | any, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnablePickFields {
|
|
915
863
|
static lc_name(): string;
|
|
916
864
|
lc_namespace: string[];
|
|
917
865
|
lc_serializable: boolean;
|
package/dist/runnables/base.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Serializable } from "../load/serializable.js";
|
|
2
2
|
import { ToolInputParsingException, _isToolCall } from "../tools/utils.js";
|
|
3
|
+
import { pRetry } from "../node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.js";
|
|
3
4
|
import { AsyncLocalStorageProviderSingleton } from "../singletons/async_local_storage/index.js";
|
|
4
5
|
import "../singletons/index.js";
|
|
5
6
|
import { DEFAULT_RECURSION_LIMIT, ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys } from "./config.js";
|
|
@@ -15,7 +16,6 @@ import { Graph } from "./graph.js";
|
|
|
15
16
|
import { convertToHttpEventStream } from "./wrappers.js";
|
|
16
17
|
import { consumeAsyncIterableInContext, consumeIteratorInContext, isAsyncIterable, isIterableIterator, isIterator } from "./iter.js";
|
|
17
18
|
import { z } from "zod/v3";
|
|
18
|
-
import pRetry from "p-retry";
|
|
19
19
|
import { v4 } from "uuid";
|
|
20
20
|
import { isTraceableFunction } from "langsmith/singletons/traceable";
|
|
21
21
|
|
|
@@ -47,7 +47,6 @@ type BranchLike<RunInput, RunOutput> = [RunnableLike<RunInput, boolean>, Runnabl
|
|
|
47
47
|
* });
|
|
48
48
|
* ```
|
|
49
49
|
*/
|
|
50
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
51
50
|
declare class RunnableBranch<RunInput = any, RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
52
51
|
static lc_name(): string;
|
|
53
52
|
lc_namespace: string[];
|
|
@@ -83,7 +82,6 @@ declare class RunnableBranch<RunInput = any, RunOutput = any> extends Runnable<R
|
|
|
83
82
|
* pairs. The last item is a default runnable which is invoked if no other condition matches.
|
|
84
83
|
* @returns A new RunnableBranch.
|
|
85
84
|
*/
|
|
86
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
87
85
|
static from<RunInput = any, RunOutput = any>(branches: [...BranchLike<RunInput, RunOutput>[], RunnableLike<RunInput, RunOutput>]): RunnableBranch<RunInput, RunOutput>;
|
|
88
86
|
_invoke(input: RunInput, config?: Partial<RunnableConfig>, runManager?: CallbackManagerForChainRun): Promise<RunOutput>;
|
|
89
87
|
invoke(input: RunInput, config?: RunnableConfig): Promise<RunOutput>;
|
|
@@ -48,7 +48,6 @@ type BranchLike<RunInput, RunOutput> = [RunnableLike<RunInput, boolean>, Runnabl
|
|
|
48
48
|
* });
|
|
49
49
|
* ```
|
|
50
50
|
*/
|
|
51
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
52
51
|
declare class RunnableBranch<RunInput = any, RunOutput = any> extends Runnable<RunInput, RunOutput> {
|
|
53
52
|
static lc_name(): string;
|
|
54
53
|
lc_namespace: string[];
|
|
@@ -84,7 +83,6 @@ declare class RunnableBranch<RunInput = any, RunOutput = any> extends Runnable<R
|
|
|
84
83
|
* pairs. The last item is a default runnable which is invoked if no other condition matches.
|
|
85
84
|
* @returns A new RunnableBranch.
|
|
86
85
|
*/
|
|
87
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
88
86
|
static from<RunInput = any, RunOutput = any>(branches: [...BranchLike<RunInput, RunOutput>[], RunnableLike<RunInput, RunOutput>]): RunnableBranch<RunInput, RunOutput>;
|
|
89
87
|
_invoke(input: RunInput, config?: Partial<RunnableConfig>, runManager?: CallbackManagerForChainRun): Promise<RunOutput>;
|
|
90
88
|
invoke(input: RunInput, config?: RunnableConfig): Promise<RunOutput>;
|
|
@@ -19,7 +19,6 @@ declare function patchConfig<CallOptions extends RunnableConfig>(config?: Partia
|
|
|
19
19
|
configurable,
|
|
20
20
|
runId
|
|
21
21
|
}?: RunnableConfig): Partial<CallOptions>;
|
|
22
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
23
22
|
declare function pickRunnableConfigKeys<CallOptions extends Record<string, any>>(config?: CallOptions): Partial<RunnableConfig> | undefined;
|
|
24
23
|
//#endregion
|
|
25
24
|
export { ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys };
|
|
@@ -19,7 +19,6 @@ declare function patchConfig<CallOptions extends RunnableConfig>(config?: Partia
|
|
|
19
19
|
configurable,
|
|
20
20
|
runId
|
|
21
21
|
}?: RunnableConfig): Partial<CallOptions>;
|
|
22
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
23
22
|
declare function pickRunnableConfigKeys<CallOptions extends Record<string, any>>(config?: CallOptions): Partial<RunnableConfig> | undefined;
|
|
24
23
|
//#endregion
|
|
25
24
|
export { ensureConfig, getCallbackManagerForConfig, mergeConfigs, patchConfig, pickRunnableConfigKeys };
|
|
@@ -8,12 +8,8 @@ declare class Graph {
|
|
|
8
8
|
nodes: Record<string, Node>;
|
|
9
9
|
edges: Edge[];
|
|
10
10
|
});
|
|
11
|
-
// Convert the graph to a JSON-serializable format.
|
|
12
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13
11
|
toJSON(): Record<string, any>;
|
|
14
|
-
addNode(data: RunnableInterface | RunnableIOSchema, id?: string,
|
|
15
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
-
metadata?: Record<string, any>): Node;
|
|
12
|
+
addNode(data: RunnableInterface | RunnableIOSchema, id?: string, metadata?: Record<string, any>): Node;
|
|
17
13
|
removeNode(node: Node): void;
|
|
18
14
|
addEdge(source: Node, target: Node, data?: string, conditional?: boolean): Edge;
|
|
19
15
|
firstNode(): Node | undefined;
|
|
@@ -8,12 +8,8 @@ declare class Graph {
|
|
|
8
8
|
nodes: Record<string, Node>;
|
|
9
9
|
edges: Edge[];
|
|
10
10
|
});
|
|
11
|
-
// Convert the graph to a JSON-serializable format.
|
|
12
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13
11
|
toJSON(): Record<string, any>;
|
|
14
|
-
addNode(data: RunnableInterface | RunnableIOSchema, id?: string,
|
|
15
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
-
metadata?: Record<string, any>): Node;
|
|
12
|
+
addNode(data: RunnableInterface | RunnableIOSchema, id?: string, metadata?: Record<string, any>): Node;
|
|
17
13
|
removeNode(node: Node): void;
|
|
18
14
|
addEdge(source: Node, target: Node, data?: string, conditional?: boolean): Edge;
|
|
19
15
|
firstNode(): Node | undefined;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const require_utils = require('./utils.cjs');
|
|
1
2
|
|
|
2
3
|
//#region src/runnables/graph_mermaid.ts
|
|
3
4
|
function _escapeNodeLabel(nodeLabel) {
|
|
@@ -88,7 +89,7 @@ function drawMermaid(nodes, edges, config) {
|
|
|
88
89
|
async function drawMermaidImage(mermaidSyntax, config) {
|
|
89
90
|
let backgroundColor = config?.backgroundColor ?? "white";
|
|
90
91
|
const imageType = config?.imageType ?? "png";
|
|
91
|
-
const mermaidSyntaxEncoded =
|
|
92
|
+
const mermaidSyntaxEncoded = require_utils.toBase64Url(mermaidSyntax);
|
|
92
93
|
if (backgroundColor !== void 0) {
|
|
93
94
|
const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
|
|
94
95
|
if (!hexColorPattern.test(backgroundColor)) backgroundColor = `!${backgroundColor}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph_mermaid.cjs","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n if (seenSubgraphs.has(subgraph)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(subgraph);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n // Recursively add nested subgraphs\n for (const nestedPrefix in edgeGroups) {\n if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n // Use btoa for compatibility, assume ASCII\n const mermaidSyntaxEncoded = btoa(mermaidSyntax);\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;AAEA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS;AACb,MAAK,MAAM,CAAC,WAAW,MAAM,IAAI,OAAO,QAAQ,WAAW,EACzD,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC;AAEjD,QAAO;AACR;;;;AAKD,SAAgB,YACdC,OACAC,OACAC,QAQQ;CACR,MAAM,EACJ,WACA,UACA,YACA,aAAa,MACb,aAAa,UACb,kBAAkB,GACnB,GAAG,UAAU,CAAE;CAEhB,IAAI,eAAe,aACf,CAAC,kCAAkC,EAAE,WAAW,mBAAmB,CAAC,GACpE;AACJ,KAAI,YAAY;EAEd,MAAM,oBAAoB;EAC1B,MAAMC,aAAqC,GAC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AAE,EAAC;AAG/D,QAAO;AACR;;;;;;;;;;;;;;;;;AAkBD,eAAsB,iBACpBC,eACAC,QAQA;CACA,IAAI,kBAAkB,QAAQ,mBAAmB;CACjD,MAAM,YAAY,QAAQ,aAAa;CAGvC,MAAM,uBAAuB,KAAK,cAAc;AAEhD,KAAI,oBAAoB,QAAW;EACjC,MAAM,kBAAkB;AACxB,MAAI,CAAC,gBAAgB,KAAK,gBAAgB,EACxC,kBAAkB,CAAC,CAAC,EAAE,iBAAiB;CAE1C;CACD,MAAM,WAAW,CAAC,wBAAwB,EAAE,qBAAqB,SAAS,EAAE,gBAAgB,MAAM,EAAE,WAAW;CAC/G,MAAM,MAAM,MAAM,MAAM,SAAS;AACjC,KAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR;EACE,CAAC,qDAAqD,CAAC;EACvD,CAAC,aAAa,EAAE,IAAI,QAAQ;EAC5B,CAAC,aAAa,EAAE,IAAI,YAAY;CACjC,EAAC,KAAK,KAAK;CAGhB,MAAM,UAAU,MAAM,IAAI,MAAM;AAChC,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"graph_mermaid.cjs","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }","toBase64Url"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n if (seenSubgraphs.has(subgraph)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(subgraph);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n // Recursively add nested subgraphs\n for (const nestedPrefix in edgeGroups) {\n if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;;AAGA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAA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#region src/runnables/graph_mermaid.ts
|
|
2
4
|
function _escapeNodeLabel(nodeLabel) {
|
|
3
5
|
return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_");
|
|
@@ -87,7 +89,7 @@ function drawMermaid(nodes, edges, config) {
|
|
|
87
89
|
async function drawMermaidImage(mermaidSyntax, config) {
|
|
88
90
|
let backgroundColor = config?.backgroundColor ?? "white";
|
|
89
91
|
const imageType = config?.imageType ?? "png";
|
|
90
|
-
const mermaidSyntaxEncoded =
|
|
92
|
+
const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);
|
|
91
93
|
if (backgroundColor !== void 0) {
|
|
92
94
|
const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
|
|
93
95
|
if (!hexColorPattern.test(backgroundColor)) backgroundColor = `!${backgroundColor}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph_mermaid.js","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n if (seenSubgraphs.has(subgraph)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(subgraph);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n // Recursively add nested subgraphs\n for (const nestedPrefix in edgeGroups) {\n if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n // Use btoa for compatibility, assume ASCII\n const mermaidSyntaxEncoded = btoa(mermaidSyntax);\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";AAEA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS;AACb,MAAK,MAAM,CAAC,WAAW,MAAM,IAAI,OAAO,QAAQ,WAAW,EACzD,UAAU,CAAC,WAAW,EA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Aa,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,iBAAiB,QAC5D,YAAY,WAAW,eAAe,aAAa;AAIvD,MAAI,UAAU,CAAC,UACb,gBAAgB;CAEnB;CAGD,YAAY,WAAW,OAAO,CAAE,GAAE,GAAG;AAGrC,MAAK,MAAM,UAAU,WACnB,KAAI,CAAC,OAAO,SAAS,IAAI,IAAI,WAAW,IACtC,YAAY,WAAW,SAAS,OAAO;AAK3C,KAAI,YACF,gBAAgB,4BAA4B,cAAc,CAAE,EAAC;AAG/D,QAAO;AACR;;;;;;;;;;;;;;;;;AAkBD,eAAsB,iBACpBC,eACAC,QAQA;CACA,IAAI,kBAAkB,QAAQ,mBAAmB;CACjD,MAAM,YAAY,QAAQ,aAAa;CAGvC,MAAM,uBAAuB,KAAK,cAAc;AAEhD,KAAI,oBAAoB,QAAW;EACjC,MAAM,kBAAkB;AACxB,MAAI,CAAC,gBAAgB,KAAK,gBAAgB,EACxC,kBAAkB,CAAC,CAAC,EAAE,iBAAiB;CAE1C;CACD,MAAM,WAAW,CAAC,wBAAwB,EAAE,qBAAqB,SAAS,EAAE,gBAAgB,MAAM,EAAE,WAAW;CAC/G,MAAM,MAAM,MAAM,MAAM,SAAS;AACjC,KAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR;EACE,CAAC,qDAAqD,CAAC;EACvD,CAAC,aAAa,EAAE,IAAI,QAAQ;EAC5B,CAAC,aAAa,EAAE,IAAI,YAAY;CACjC,EAAC,KAAK,KAAK;CAGhB,MAAM,UAAU,MAAM,IAAI,MAAM;AAChC,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"graph_mermaid.js","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n if (seenSubgraphs.has(subgraph)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(subgraph);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\" <br> \");\n }\n edgeLabel = conditional\n ? ` -. ${edgeData} .-> `\n : ` -- ${edgeData} --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n // Recursively add nested subgraphs\n for (const nestedPrefix in edgeGroups) {\n if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;;AAGA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS;AACb,MAAK,MAAM,CAAC,WAAW,MAAM,IAAI,OAAO,QAAQ,WAAW,EACzD,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC;AAEjD,QAAO;AACR;;;;AAKD,SAAgB,YACdC,OACAC,OACAC,QAQQ;CACR,MAAM,EACJ,WACA,UACA,YACA,aAAa,MACb,aAAa,UACb,kBAAkB,GACnB,GAAG,UAAU,CAAE;CAEhB,IAAI,eAAe,aACf,CAAC,kCAAkC,EAAE,WAAW,mBAAmB,CAAC,GACpE;AACJ,KAAI,YAAY;EAEd,MAAM,oBAAoB;EAC1B,MAAMC,aAAqC,GACxC,oBAAoB,WACtB;AACD,MAAI,cAAc,QAChB,WAAW,aAAa;AAE1B,MAAI,aAAa,QACf,WAAW,YAAY;AAIzB,OAAK,MAAM,CAAC,KAAK,KAAK,IAAI,OAAO,QAAQ,MAAM,EAAE;GAC/C,MAAM,WAAW,KAAK,KAAK,MAAM,IAAI,CAAC,KAAK,IAAI;GAC/C,MAAM,QAAQ,uBAAuB,KACnC,CAAC,SAAS,SAAS,WAAW,KAAK,IAAI,SAAS,SAAS,KAAK,CAC/D,GACG,CAAC,GAAG,EAAE,SAAS,IAAI,CAAC,GACpB;GAEJ,IAAI,aAAa;AACjB,OAAI,OAAO,KAAK,KAAK,YAAY,CAAE,EAAC,CAAC,QACnC,cAAc,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KAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR;EACE,CAAC,qDAAqD,CAAC;EACvD,CAAC,aAAa,EAAE,IAAI,QAAQ;EAC5B,CAAC,aAAa,EAAE,IAAI,YAAY;CACjC,EAAC,KAAK,KAAK;CAGhB,MAAM,UAAU,MAAM,IAAI,MAAM;AAChC,QAAO;AACR"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_base = require('../messages/base.cjs');
|
|
2
|
-
const require_ai = require('../messages/ai.cjs');
|
|
3
2
|
const require_human = require('../messages/human.cjs');
|
|
3
|
+
const require_ai = require('../messages/ai.cjs');
|
|
4
4
|
const require_base$1 = require('./base.cjs');
|
|
5
5
|
require('../messages/index.cjs');
|
|
6
6
|
const require_passthrough = require('./passthrough.cjs');
|
|
@@ -5,9 +5,7 @@ import { Runnable, RunnableBinding, RunnableBindingArgs } from "./base.cjs";
|
|
|
5
5
|
import { BaseChatMessageHistory, BaseListChatMessageHistory } from "../chat_history.cjs";
|
|
6
6
|
|
|
7
7
|
//#region src/runnables/history.d.ts
|
|
8
|
-
type GetSessionHistoryCallable = (
|
|
9
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
10
|
-
...args: Array<any>) => Promise<BaseChatMessageHistory | BaseListChatMessageHistory> | BaseChatMessageHistory | BaseListChatMessageHistory;
|
|
8
|
+
type GetSessionHistoryCallable = (...args: Array<any>) => Promise<BaseChatMessageHistory | BaseListChatMessageHistory> | BaseChatMessageHistory | BaseListChatMessageHistory;
|
|
11
9
|
interface RunnableWithMessageHistoryInputs<RunInput, RunOutput> extends Omit<RunnableBindingArgs<RunInput, RunOutput>, "bound" | "config"> {
|
|
12
10
|
runnable: Runnable<RunInput, RunOutput>;
|
|
13
11
|
getMessageHistory: GetSessionHistoryCallable;
|
|
@@ -87,15 +85,9 @@ declare class RunnableWithMessageHistory<RunInput, RunOutput> extends RunnableBi
|
|
|
87
85
|
historyMessagesKey?: string;
|
|
88
86
|
getMessageHistory: GetSessionHistoryCallable;
|
|
89
87
|
constructor(fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>);
|
|
90
|
-
_getInputMessages(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
_getOutputMessages(
|
|
94
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
95
|
-
outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>): Array<BaseMessage>;
|
|
96
|
-
_enterHistory(
|
|
97
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
98
|
-
input: any, kwargs?: RunnableConfig): Promise<BaseMessage[]>;
|
|
88
|
+
_getInputMessages(inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>): Array<BaseMessage>;
|
|
89
|
+
_getOutputMessages(outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>): Array<BaseMessage>;
|
|
90
|
+
_enterHistory(input: any, kwargs?: RunnableConfig): Promise<BaseMessage[]>;
|
|
99
91
|
_exitHistory(run: Run, config: RunnableConfig): Promise<void>;
|
|
100
92
|
_mergeConfig(...configs: Array<RunnableConfig | undefined>): Promise<Partial<RunnableConfig<Record<string, any>>>>;
|
|
101
93
|
}
|