@langchain/core 0.2.18 → 0.2.19

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 (128) hide show
  1. package/dist/callbacks/manager.cjs +94 -19
  2. package/dist/callbacks/manager.d.ts +3 -1
  3. package/dist/callbacks/manager.js +94 -19
  4. package/dist/messages/base.cjs +16 -1
  5. package/dist/messages/base.d.ts +9 -0
  6. package/dist/messages/base.js +14 -0
  7. package/dist/messages/tool.cjs +23 -0
  8. package/dist/messages/tool.d.ts +15 -0
  9. package/dist/messages/tool.js +24 -1
  10. package/dist/messages/utils.cjs +1 -1
  11. package/dist/messages/utils.js +1 -1
  12. package/dist/output_parsers/string.cjs +1 -0
  13. package/dist/output_parsers/string.js +1 -0
  14. package/dist/runnables/base.cjs +1 -3
  15. package/dist/runnables/base.js +1 -3
  16. package/dist/runnables/remote.cjs +3 -1
  17. package/dist/runnables/remote.js +3 -1
  18. package/dist/tools/index.cjs +15 -6
  19. package/dist/tools/index.d.ts +21 -12
  20. package/dist/tools/index.js +15 -6
  21. package/dist/utils/testing/index.cjs +161 -3
  22. package/dist/utils/testing/index.d.ts +94 -3
  23. package/dist/utils/testing/index.js +160 -3
  24. package/package.json +4 -3
  25. package/dist/caches/tests/in_memory_cache.test.d.ts +0 -1
  26. package/dist/caches/tests/in_memory_cache.test.js +0 -33
  27. package/dist/callbacks/tests/callbacks.test.d.ts +0 -1
  28. package/dist/callbacks/tests/callbacks.test.js +0 -495
  29. package/dist/callbacks/tests/manager.int.test.d.ts +0 -1
  30. package/dist/callbacks/tests/manager.int.test.js +0 -29
  31. package/dist/callbacks/tests/run_collector.test.d.ts +0 -1
  32. package/dist/callbacks/tests/run_collector.test.js +0 -58
  33. package/dist/language_models/tests/chat_models.test.d.ts +0 -1
  34. package/dist/language_models/tests/chat_models.test.js +0 -204
  35. package/dist/language_models/tests/count_tokens.test.d.ts +0 -1
  36. package/dist/language_models/tests/count_tokens.test.js +0 -19
  37. package/dist/language_models/tests/llms.test.d.ts +0 -1
  38. package/dist/language_models/tests/llms.test.js +0 -52
  39. package/dist/messages/tests/base_message.test.d.ts +0 -1
  40. package/dist/messages/tests/base_message.test.js +0 -245
  41. package/dist/messages/tests/message_utils.test.d.ts +0 -1
  42. package/dist/messages/tests/message_utils.test.js +0 -434
  43. package/dist/output_parsers/openai_tools/tests/json_output_tools_parser.test.d.ts +0 -1
  44. package/dist/output_parsers/openai_tools/tests/json_output_tools_parser.test.js +0 -81
  45. package/dist/output_parsers/tests/json.test.d.ts +0 -1
  46. package/dist/output_parsers/tests/json.test.js +0 -427
  47. package/dist/output_parsers/tests/output_parser.test.d.ts +0 -1
  48. package/dist/output_parsers/tests/output_parser.test.js +0 -78
  49. package/dist/output_parsers/tests/string.test.d.ts +0 -1
  50. package/dist/output_parsers/tests/string.test.js +0 -68
  51. package/dist/output_parsers/tests/structured.test.d.ts +0 -1
  52. package/dist/output_parsers/tests/structured.test.js +0 -166
  53. package/dist/output_parsers/tests/xml.test.d.ts +0 -1
  54. package/dist/output_parsers/tests/xml.test.js +0 -81
  55. package/dist/prompts/tests/chat.mustache.test.d.ts +0 -1
  56. package/dist/prompts/tests/chat.mustache.test.js +0 -129
  57. package/dist/prompts/tests/chat.test.d.ts +0 -1
  58. package/dist/prompts/tests/chat.test.js +0 -557
  59. package/dist/prompts/tests/few_shot.test.d.ts +0 -1
  60. package/dist/prompts/tests/few_shot.test.js +0 -224
  61. package/dist/prompts/tests/pipeline.test.d.ts +0 -1
  62. package/dist/prompts/tests/pipeline.test.js +0 -101
  63. package/dist/prompts/tests/prompt.mustache.test.d.ts +0 -1
  64. package/dist/prompts/tests/prompt.mustache.test.js +0 -105
  65. package/dist/prompts/tests/prompt.test.d.ts +0 -1
  66. package/dist/prompts/tests/prompt.test.js +0 -78
  67. package/dist/prompts/tests/structured.test.d.ts +0 -1
  68. package/dist/prompts/tests/structured.test.js +0 -37
  69. package/dist/prompts/tests/template.test.d.ts +0 -1
  70. package/dist/prompts/tests/template.test.js +0 -24
  71. package/dist/runnables/tests/runnable.test.d.ts +0 -1
  72. package/dist/runnables/tests/runnable.test.js +0 -491
  73. package/dist/runnables/tests/runnable_binding.test.d.ts +0 -1
  74. package/dist/runnables/tests/runnable_binding.test.js +0 -46
  75. package/dist/runnables/tests/runnable_branch.test.d.ts +0 -1
  76. package/dist/runnables/tests/runnable_branch.test.js +0 -116
  77. package/dist/runnables/tests/runnable_graph.test.d.ts +0 -1
  78. package/dist/runnables/tests/runnable_graph.test.js +0 -100
  79. package/dist/runnables/tests/runnable_history.test.d.ts +0 -1
  80. package/dist/runnables/tests/runnable_history.test.js +0 -177
  81. package/dist/runnables/tests/runnable_interface.test.d.ts +0 -1
  82. package/dist/runnables/tests/runnable_interface.test.js +0 -209
  83. package/dist/runnables/tests/runnable_map.test.d.ts +0 -1
  84. package/dist/runnables/tests/runnable_map.test.js +0 -238
  85. package/dist/runnables/tests/runnable_passthrough.test.d.ts +0 -1
  86. package/dist/runnables/tests/runnable_passthrough.test.js +0 -96
  87. package/dist/runnables/tests/runnable_remote.int.test.d.ts +0 -1
  88. package/dist/runnables/tests/runnable_remote.int.test.js +0 -138
  89. package/dist/runnables/tests/runnable_remote.test.d.ts +0 -1
  90. package/dist/runnables/tests/runnable_remote.test.js +0 -200
  91. package/dist/runnables/tests/runnable_retry.test.d.ts +0 -1
  92. package/dist/runnables/tests/runnable_retry.test.js +0 -125
  93. package/dist/runnables/tests/runnable_stream_events.test.d.ts +0 -1
  94. package/dist/runnables/tests/runnable_stream_events.test.js +0 -1013
  95. package/dist/runnables/tests/runnable_stream_events_v2.test.d.ts +0 -1
  96. package/dist/runnables/tests/runnable_stream_events_v2.test.js +0 -2022
  97. package/dist/runnables/tests/runnable_stream_log.test.d.ts +0 -1
  98. package/dist/runnables/tests/runnable_stream_log.test.js +0 -71
  99. package/dist/runnables/tests/runnable_tools.test.d.ts +0 -1
  100. package/dist/runnables/tests/runnable_tools.test.js +0 -149
  101. package/dist/runnables/tests/runnable_tracing.int.test.d.ts +0 -1
  102. package/dist/runnables/tests/runnable_tracing.int.test.js +0 -37
  103. package/dist/runnables/tests/runnable_with_fallbacks.test.d.ts +0 -1
  104. package/dist/runnables/tests/runnable_with_fallbacks.test.js +0 -36
  105. package/dist/singletons/tests/async_local_storage.test.d.ts +0 -1
  106. package/dist/singletons/tests/async_local_storage.test.js +0 -153
  107. package/dist/structured_query/tests/utils.test.d.ts +0 -1
  108. package/dist/structured_query/tests/utils.test.js +0 -47
  109. package/dist/tools/tests/tools.test.d.ts +0 -1
  110. package/dist/tools/tests/tools.test.js +0 -85
  111. package/dist/tracers/tests/langchain_tracer.int.test.d.ts +0 -1
  112. package/dist/tracers/tests/langchain_tracer.int.test.js +0 -74
  113. package/dist/tracers/tests/langsmith_interop.test.d.ts +0 -1
  114. package/dist/tracers/tests/langsmith_interop.test.js +0 -551
  115. package/dist/tracers/tests/tracer.test.d.ts +0 -1
  116. package/dist/tracers/tests/tracer.test.js +0 -378
  117. package/dist/utils/testing/tests/chatfake.test.d.ts +0 -1
  118. package/dist/utils/testing/tests/chatfake.test.js +0 -112
  119. package/dist/utils/tests/async_caller.test.d.ts +0 -1
  120. package/dist/utils/tests/async_caller.test.js +0 -27
  121. package/dist/utils/tests/enviroment.test.d.ts +0 -1
  122. package/dist/utils/tests/enviroment.test.js +0 -6
  123. package/dist/utils/tests/function_calling.test.d.ts +0 -1
  124. package/dist/utils/tests/function_calling.test.js +0 -107
  125. package/dist/utils/tests/math_utils.test.d.ts +0 -1
  126. package/dist/utils/tests/math_utils.test.js +0 -139
  127. package/dist/utils/tests/polyfill_stream.test.d.ts +0 -1
  128. package/dist/utils/tests/polyfill_stream.test.js +0 -15
@@ -1 +0,0 @@
1
- export {};
@@ -1,71 +0,0 @@
1
- /* eslint-disable no-promise-executor-return */
2
- /* eslint-disable @typescript-eslint/no-explicit-any */
3
- import { test } from "@jest/globals";
4
- import { ChatPromptTemplate, HumanMessagePromptTemplate, PromptTemplate, SystemMessagePromptTemplate, } from "../../prompts/index.js";
5
- import { Document } from "../../documents/document.js";
6
- import { RunnableSequence, RunnableMap } from "../base.js";
7
- import { FakeLLM, FakeChatModel, FakeRetriever, } from "../../utils/testing/index.js";
8
- test("Runnable streamLog method", async () => {
9
- const promptTemplate = PromptTemplate.fromTemplate("{input}");
10
- const llm = new FakeLLM({});
11
- const runnable = promptTemplate.pipe(llm);
12
- const result = await runnable.streamLog({ input: "Hello world!" });
13
- let finalState;
14
- for await (const chunk of result) {
15
- if (finalState === undefined) {
16
- finalState = chunk;
17
- }
18
- else {
19
- finalState = finalState.concat(chunk);
20
- }
21
- }
22
- expect(finalState.state.final_output).toEqual({
23
- output: "Hello world!",
24
- });
25
- });
26
- test("Runnable streamLog method with a more complicated sequence", async () => {
27
- const promptTemplate = ChatPromptTemplate.fromMessages([
28
- SystemMessagePromptTemplate.fromTemplate(`You are a nice assistant.`),
29
- HumanMessagePromptTemplate.fromTemplate(`Context:\n{documents}\n\nQuestion:\n{question}`),
30
- ]);
31
- const llm = new FakeChatModel({});
32
- const retrieverOutputDocs = [
33
- new Document({ pageContent: "foo" }),
34
- new Document({ pageContent: "bar" }),
35
- ];
36
- const inputs = {
37
- question: (input) => input,
38
- documents: RunnableSequence.from([
39
- new FakeRetriever({
40
- output: retrieverOutputDocs,
41
- }),
42
- (docs) => JSON.stringify(docs),
43
- ]).withConfig({ runName: "CUSTOM_NAME" }),
44
- extraField: new FakeLLM({
45
- response: "testing",
46
- }).withConfig({ tags: ["only_one"] }),
47
- };
48
- const runnable = new RunnableMap({
49
- steps: inputs,
50
- })
51
- .pipe(promptTemplate)
52
- .pipe(llm);
53
- const stream = await runnable.streamLog("Do you know the Muffin Man?", {}, {
54
- includeTags: ["only_one"],
55
- includeNames: ["CUSTOM_NAME"],
56
- });
57
- let finalState;
58
- for await (const chunk of stream) {
59
- if (finalState === undefined) {
60
- finalState = chunk;
61
- }
62
- else {
63
- finalState = finalState.concat(chunk);
64
- }
65
- }
66
- expect(finalState.state.logs.FakeLLM).toBeDefined();
67
- expect(finalState.state.logs.FakeLLM.final_output.generations[0][0]
68
- .text).toEqual("testing");
69
- expect(finalState.state.logs.CUSTOM_NAME).toBeDefined();
70
- expect(finalState.state.logs.CUSTOM_NAME.final_output.output).toEqual(JSON.stringify(retrieverOutputDocs));
71
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,149 +0,0 @@
1
- import { z } from "zod";
2
- import { RunnableLambda, RunnableToolLike } from "../base.js";
3
- import { FakeRetriever } from "../../utils/testing/index.js";
4
- import { Document } from "../../documents/document.js";
5
- test("Runnable asTool works", async () => {
6
- const schema = z.object({
7
- foo: z.string(),
8
- });
9
- const runnable = RunnableLambda.from((input, config) => {
10
- return `${input.foo}${config?.configurable.foo}`;
11
- });
12
- const tool = runnable.asTool({
13
- schema,
14
- });
15
- expect(tool).toBeInstanceOf(RunnableToolLike);
16
- expect(tool.schema).toBe(schema);
17
- expect(tool.name).toBe(runnable.getName());
18
- });
19
- test("Runnable asTool works with all populated fields", async () => {
20
- const schema = z.object({
21
- foo: z.string(),
22
- });
23
- const runnable = RunnableLambda.from((input, config) => {
24
- return `${input.foo}${config?.configurable.foo}`;
25
- });
26
- const tool = runnable.asTool({
27
- schema,
28
- name: "test",
29
- description: "test",
30
- });
31
- expect(tool).toBeInstanceOf(RunnableToolLike);
32
- expect(tool.schema).toBe(schema);
33
- expect(tool.description).toBe("test");
34
- expect(tool.name).toBe("test");
35
- });
36
- test("Runnable asTool can invoke", async () => {
37
- const schema = z.object({
38
- foo: z.string(),
39
- });
40
- const runnable = RunnableLambda.from((input, config) => {
41
- return `${input.foo}${config?.configurable.foo}`;
42
- });
43
- const tool = runnable.asTool({
44
- schema,
45
- });
46
- const toolResponse = await tool.invoke({
47
- foo: "bar",
48
- }, {
49
- configurable: {
50
- foo: "bar",
51
- },
52
- });
53
- expect(toolResponse).toBe("barbar");
54
- });
55
- test("asTool should type error with mismatched schema", async () => {
56
- // asTool infers the type of the Zod schema from the existing runnable's RunInput generic.
57
- // If the Zod schema does not match the RunInput, it should throw a type error.
58
- const schema = z.object({
59
- foo: z.string(),
60
- });
61
- const runnable = RunnableLambda.from((input, config) => {
62
- return `${input.bar}${config?.configurable.foo}`;
63
- });
64
- runnable.asTool({
65
- // @ts-expect-error - Should error. If this does not give a type error, the generics/typing of `asTool` is broken.
66
- schema,
67
- });
68
- });
69
- test("Create a runnable tool directly from RunnableToolLike", async () => {
70
- const schema = z.object({
71
- foo: z.string(),
72
- });
73
- const adderFunc = (_) => {
74
- return Promise.resolve(true);
75
- };
76
- const tool = new RunnableToolLike({
77
- schema,
78
- name: "test",
79
- description: "test",
80
- bound: RunnableLambda.from(adderFunc),
81
- });
82
- const result = await tool.invoke({ foo: "bar" });
83
- expect(result).toBe(true);
84
- });
85
- test("asTool can take a single string input", async () => {
86
- const firstRunnable = RunnableLambda.from((input) => {
87
- return `${input}a`;
88
- });
89
- const secondRunnable = RunnableLambda.from((input) => {
90
- return `${input}z`;
91
- });
92
- const runnable = firstRunnable.pipe(secondRunnable);
93
- const asTool = runnable.asTool({
94
- schema: z.string(),
95
- });
96
- const result = await asTool.invoke("b");
97
- expect(result).toBe("baz");
98
- });
99
- test("Runnable asTool uses Zod schema description if not provided", async () => {
100
- const description = "Test schema";
101
- const schema = z
102
- .object({
103
- foo: z.string(),
104
- })
105
- .describe(description);
106
- const runnable = RunnableLambda.from((input, config) => {
107
- return `${input.foo}${config?.configurable.foo}`;
108
- });
109
- const tool = runnable.asTool({
110
- schema,
111
- });
112
- expect(tool.description).toBe(description);
113
- });
114
- test("Runnable asTool can accept a string zod schema", async () => {
115
- const lambda = RunnableLambda.from((input) => {
116
- return `${input}a`;
117
- }).asTool({
118
- name: "string_tool",
119
- description: "A tool that appends 'a' to the input string",
120
- schema: z.string(),
121
- });
122
- const result = await lambda.invoke("b");
123
- expect(result).toBe("ba");
124
- });
125
- test("Runnables which dont accept ToolCalls as inputs can accept ToolCalls", async () => {
126
- const pageContent = "Dogs are pretty cool, man!";
127
- const retriever = new FakeRetriever({
128
- output: [
129
- new Document({
130
- pageContent,
131
- }),
132
- ],
133
- });
134
- const tool = retriever.asTool({
135
- name: "pet_info_retriever",
136
- description: "Get information about pets.",
137
- schema: z.string(),
138
- });
139
- const result = await tool.invoke({
140
- type: "tool_call",
141
- name: "pet_info_retriever",
142
- args: {
143
- input: "dogs",
144
- },
145
- id: "string",
146
- });
147
- expect(result).toHaveLength(1);
148
- expect(result[0].pageContent).toBe(pageContent);
149
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,37 +0,0 @@
1
- import { Client } from "langsmith";
2
- import { LangChainTracer } from "../../tracers/tracer_langchain.js";
3
- import { BaseOutputParser, } from "../../output_parsers/base.js";
4
- import { FakeChatModel } from "../../utils/testing/index.js";
5
- import { getEnvironmentVariable } from "../../utils/env.js";
6
- class FakeDateOutputParser extends BaseOutputParser {
7
- constructor() {
8
- super(...arguments);
9
- Object.defineProperty(this, "lc_namespace", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: ["langchain_core", "output_parsers", "testing"]
14
- });
15
- }
16
- async parse(_text) {
17
- return new Date();
18
- }
19
- getFormatInstructions(_options) {
20
- return "";
21
- }
22
- }
23
- test("Should handle tracing with a date output", async () => {
24
- const client = new Client({
25
- apiUrl: getEnvironmentVariable("LANGCHAIN_ENDPOINT"),
26
- apiKey: getEnvironmentVariable("LANGCHAIN_API_KEY"),
27
- });
28
- const tracer = new LangChainTracer({
29
- projectName: getEnvironmentVariable("LANGCHAIN_SESSION"),
30
- client,
31
- });
32
- const model = new FakeChatModel({});
33
- const parser = new FakeDateOutputParser();
34
- const chain = model.pipe(parser);
35
- const result = await chain.invoke("test", { callbacks: [tracer] });
36
- console.log(result);
37
- });
@@ -1,36 +0,0 @@
1
- /* eslint-disable no-promise-executor-return */
2
- /* eslint-disable @typescript-eslint/no-explicit-any */
3
- import { test } from "@jest/globals";
4
- import { FakeLLM } from "../../utils/testing/index.js";
5
- test("RunnableWithFallbacks", async () => {
6
- const llm = new FakeLLM({
7
- thrownErrorString: "Bad error!",
8
- });
9
- await expect(async () => {
10
- const result1 = await llm.invoke("What up");
11
- console.log(result1);
12
- }).rejects.toThrow();
13
- const llmWithFallbacks = llm.withFallbacks({
14
- fallbacks: [new FakeLLM({})],
15
- });
16
- const result2 = await llmWithFallbacks.invoke("What up");
17
- expect(result2).toEqual("What up");
18
- });
19
- test("RunnableWithFallbacks batch", async () => {
20
- const llm = new FakeLLM({
21
- thrownErrorString: "Bad error!",
22
- });
23
- await expect(async () => {
24
- const result1 = await llm.batch(["What up"]);
25
- console.log(result1);
26
- }).rejects.toThrow();
27
- const llmWithFallbacks = llm.withFallbacks({
28
- fallbacks: [new FakeLLM({})],
29
- });
30
- const result2 = await llmWithFallbacks.batch([
31
- "What up 1",
32
- "What up 2",
33
- "What up 3",
34
- ]);
35
- expect(result2).toEqual(["What up 1", "What up 2", "What up 3"]);
36
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,153 +0,0 @@
1
- import { test, expect } from "@jest/globals";
2
- import { v4 } from "uuid";
3
- import { AsyncLocalStorage } from "node:async_hooks";
4
- import { AsyncLocalStorageProviderSingleton } from "../index.js";
5
- import { RunnableLambda } from "../../runnables/base.js";
6
- import { FakeListChatModel } from "../../utils/testing/index.js";
7
- import { getCallbackManagerForConfig } from "../../runnables/config.js";
8
- import { BaseCallbackHandler } from "../../callbacks/base.js";
9
- class FakeCallbackHandler extends BaseCallbackHandler {
10
- constructor() {
11
- super(...arguments);
12
- Object.defineProperty(this, "name", {
13
- enumerable: true,
14
- configurable: true,
15
- writable: true,
16
- value: `fake-${v4()}`
17
- });
18
- }
19
- }
20
- test("Config should be automatically populated after setting global async local storage", async () => {
21
- const inner = RunnableLambda.from((_, config) => config);
22
- const outer = RunnableLambda.from(async (input) => {
23
- const res = await inner.invoke(input);
24
- return res;
25
- });
26
- const res1 = await outer.invoke({ hi: true }, {
27
- configurable: {
28
- sampleKey: "sampleValue",
29
- },
30
- tags: ["tester"],
31
- });
32
- expect(res1?.tags).toEqual([]);
33
- AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorage());
34
- const res2 = await outer.invoke({ hi: true }, {
35
- configurable: {
36
- sampleKey: "sampleValue",
37
- },
38
- tags: ["tester"],
39
- });
40
- expect(res2?.tags).toEqual(["tester"]);
41
- const stream = await outer.stream({ hi2: true }, {
42
- configurable: {
43
- sampleKey: "sampleValue",
44
- },
45
- tags: ["stream_tester"],
46
- });
47
- const chunks = [];
48
- for await (const chunk of stream) {
49
- chunks.push(chunk);
50
- }
51
- expect(chunks.length).toEqual(1);
52
- expect(chunks[0]).toEqual(expect.objectContaining({
53
- configurable: {
54
- sampleKey: "sampleValue",
55
- },
56
- tags: ["stream_tester"],
57
- }));
58
- const outer2 = RunnableLambda.from(async () => inner);
59
- const res3 = await outer2.invoke({}, {
60
- configurable: {
61
- sampleKey: "sampleValue",
62
- },
63
- tags: ["test_recursive"],
64
- });
65
- expect(res3?.tags).toEqual(["test_recursive"]);
66
- const stream2 = await outer2.stream({}, {
67
- configurable: {
68
- sampleKey: "sampleValue",
69
- },
70
- tags: ["stream_test_recursive"],
71
- });
72
- const chunks2 = [];
73
- for await (const chunk of stream2) {
74
- chunks2.push(chunk);
75
- }
76
- expect(chunks2.length).toEqual(1);
77
- expect(chunks2[0]).toEqual(expect.objectContaining({
78
- configurable: {
79
- sampleKey: "sampleValue",
80
- },
81
- tags: ["stream_test_recursive"],
82
- }));
83
- const inner2 = RunnableLambda.from((_, config) => config).withConfig({
84
- runName: "inner_test_run",
85
- });
86
- const outer3 = RunnableLambda.from(async (input) => {
87
- const res = await inner2.invoke(input);
88
- return res;
89
- });
90
- const res4 = await outer3.invoke({ hi: true }, {
91
- configurable: {
92
- sampleKey: "sampleValue",
93
- },
94
- tags: ["tester_with_config"],
95
- });
96
- expect(res4?.tags).toEqual(["tester_with_config"]);
97
- const chatModel = new FakeListChatModel({ responses: ["test"] });
98
- const outer4 = RunnableLambda.from(async () => {
99
- const res = await chatModel.invoke("hey");
100
- return res;
101
- });
102
- const eventStream = await outer4.streamEvents({ hi: true }, { version: "v1" });
103
- const events = [];
104
- for await (const event of eventStream) {
105
- events.push(event);
106
- }
107
- expect(events.filter((event) => event.event === "on_llm_start").length).toEqual(1);
108
- });
109
- test("Runnable streamEvents method with streaming nested in a RunnableLambda", async () => {
110
- AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorage());
111
- const chat = new FakeListChatModel({
112
- responses: ["Hello"],
113
- });
114
- const outerRunId = v4();
115
- const innerRunId = v4();
116
- const innerRunId2 = v4();
117
- const dummyHandler = new FakeCallbackHandler();
118
- const myFunc = async (input) => {
119
- const outerCallbackManager = await getCallbackManagerForConfig(AsyncLocalStorageProviderSingleton.getRunnableConfig());
120
- expect(outerCallbackManager?.getParentRunId()).toEqual(outerRunId);
121
- const nestedLambdaWithOverriddenCallbacks = RunnableLambda.from(async (_, config) => {
122
- expect(config?.callbacks?.handlers).toEqual([]);
123
- });
124
- await nestedLambdaWithOverriddenCallbacks.invoke(input, {
125
- runId: innerRunId,
126
- callbacks: [],
127
- });
128
- const nestedLambdaWithoutOverriddenCallbacks = RunnableLambda.from(async (_, config) => {
129
- const innerCallbackManager = await getCallbackManagerForConfig(AsyncLocalStorageProviderSingleton.getRunnableConfig());
130
- expect(innerCallbackManager?.getParentRunId()).toEqual(innerRunId2);
131
- expect(config?.callbacks?.handlers).toContain(dummyHandler);
132
- });
133
- await nestedLambdaWithoutOverriddenCallbacks.invoke(input, {
134
- runId: innerRunId2,
135
- });
136
- for await (const _ of await chat.stream(input)) {
137
- // no-op
138
- }
139
- };
140
- const myNestedLambda = RunnableLambda.from(myFunc);
141
- const events = [];
142
- for await (const event of myNestedLambda.streamEvents("hello", {
143
- version: "v1",
144
- runId: outerRunId,
145
- callbacks: [dummyHandler],
146
- })) {
147
- events.push(event);
148
- }
149
- const chatModelStreamEvent = events.find((event) => {
150
- return event.event === "on_llm_stream";
151
- });
152
- expect(chatModelStreamEvent).toBeDefined();
153
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,47 +0,0 @@
1
- /* eslint-disable no-process-env */
2
- import { test } from "@jest/globals";
3
- import { castValue, isFloat, isInt, isString } from "../utils.js";
4
- test("Casting values correctly", () => {
5
- const stringString = [
6
- "string",
7
- "test",
8
- "this is a string",
9
- " ",
10
- "\n\n\n\n\n\n",
11
- `asdf
12
- zxcv`,
13
- ];
14
- const intString = [
15
- "1a",
16
- "2b",
17
- "3c",
18
- "a4",
19
- `123
20
- asdf`,
21
- ];
22
- const floatString = ["1.1a", "2.2b", "3.3c", "c4.4"];
23
- const intInt = ["1", 2, 3];
24
- const floatFloat = ["1.1", 2.2, 3.3];
25
- stringString.map(castValue).forEach((value) => {
26
- expect(typeof value).toBe("string");
27
- expect(isString(value)).toBe(true);
28
- });
29
- intString.map(castValue).forEach((value) => {
30
- expect(typeof value).toBe("string");
31
- expect(isString(value)).toBe(true);
32
- expect(isInt(value)).toBe(false);
33
- });
34
- floatString.map(castValue).forEach((value) => {
35
- expect(typeof value).toBe("string");
36
- expect(isString(value)).toBe(true);
37
- expect(isFloat(value)).toBe(false);
38
- });
39
- intInt.map(castValue).forEach((value) => {
40
- expect(typeof value).toBe("number");
41
- expect(isInt(value)).toBe(true);
42
- });
43
- floatFloat.map(castValue).forEach((value) => {
44
- expect(typeof value).toBe("number");
45
- expect(isFloat(value)).toBe(true);
46
- });
47
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,85 +0,0 @@
1
- import { test, expect } from "@jest/globals";
2
- import { z } from "zod";
3
- import { tool } from "../index.js";
4
- import { ToolMessage } from "../../messages/tool.js";
5
- test("Tool should error if responseFormat is content_and_artifact but the function doesn't return a tuple", async () => {
6
- const weatherSchema = z.object({
7
- location: z.string(),
8
- });
9
- const weatherTool = tool((_) => {
10
- return "str";
11
- }, {
12
- name: "weather",
13
- schema: weatherSchema,
14
- responseFormat: "content_and_artifact",
15
- });
16
- await expect(async () => {
17
- await weatherTool.invoke({ location: "San Francisco" });
18
- }).rejects.toThrow();
19
- });
20
- test("Tool works if responseFormat is content_and_artifact and returns a tuple", async () => {
21
- const weatherSchema = z.object({
22
- location: z.string(),
23
- });
24
- const weatherTool = tool((input) => {
25
- return ["msg_content", input];
26
- }, {
27
- name: "weather",
28
- schema: weatherSchema,
29
- responseFormat: "content_and_artifact",
30
- });
31
- const toolResult = await weatherTool.invoke({ location: "San Francisco" });
32
- expect(toolResult).not.toBeInstanceOf(ToolMessage);
33
- expect(toolResult).toBe("msg_content");
34
- });
35
- test("Does not return tool message if responseFormat is content_and_artifact and returns a tuple and a tool call with no id is passed in", async () => {
36
- const weatherSchema = z.object({
37
- location: z.string(),
38
- });
39
- const weatherTool = tool((input) => {
40
- return ["msg_content", input];
41
- }, {
42
- name: "weather",
43
- schema: weatherSchema,
44
- responseFormat: "content_and_artifact",
45
- });
46
- const toolResult = await weatherTool.invoke({
47
- args: { location: "San Francisco" },
48
- name: "weather",
49
- type: "tool_call",
50
- });
51
- expect(toolResult).toBe("msg_content");
52
- });
53
- test("Returns tool message if responseFormat is content_and_artifact and returns a tuple and a tool call with id is passed in", async () => {
54
- const weatherSchema = z.object({
55
- location: z.string(),
56
- });
57
- const weatherTool = tool((input) => {
58
- return ["msg_content", input];
59
- }, {
60
- name: "weather",
61
- schema: weatherSchema,
62
- responseFormat: "content_and_artifact",
63
- });
64
- const toolResult = await weatherTool.invoke({
65
- id: "testid",
66
- args: { location: "San Francisco" },
67
- name: "weather",
68
- type: "tool_call",
69
- });
70
- expect(toolResult).toBeInstanceOf(ToolMessage);
71
- expect(toolResult.content).toBe("msg_content");
72
- expect(toolResult.artifact).toEqual({ location: "San Francisco" });
73
- expect(toolResult.name).toBe("weather");
74
- });
75
- test("Tool can accept single string input", async () => {
76
- const stringTool = tool((input) => {
77
- return `${input}a`;
78
- }, {
79
- name: "string_tool",
80
- description: "A tool that appends 'a' to the input string",
81
- schema: z.string(),
82
- });
83
- const result = await stringTool.invoke("b");
84
- expect(result).toBe("ba");
85
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,74 +0,0 @@
1
- /* eslint-disable no-process-env */
2
- import * as uuid from "uuid";
3
- import { test } from "@jest/globals";
4
- import { LangChainTracer } from "../tracer_langchain.js";
5
- import { HumanMessage } from "../../messages/index.js";
6
- const serialized = {
7
- lc: 1,
8
- type: "constructor",
9
- id: ["test"],
10
- kwargs: {},
11
- };
12
- test("LangChain V2 tracer does not throw errors for its methods", async () => {
13
- const tracer = new LangChainTracer({
14
- projectName: `JS Int Test - ${uuid.v4()}`,
15
- });
16
- const chainRunId = uuid.v4();
17
- const toolRunId = uuid.v4();
18
- const llmRunId = uuid.v4();
19
- const chatRunId = uuid.v4();
20
- await tracer.handleChainStart(serialized, { foo: "bar" }, chainRunId);
21
- await tracer.handleToolStart(serialized, "test", toolRunId, chainRunId);
22
- await tracer.handleLLMStart(serialized, ["test"], llmRunId, toolRunId);
23
- await tracer.handleLLMEnd({ generations: [[]] }, llmRunId);
24
- await tracer.handleChatModelStart(serialized, [[new HumanMessage("I'm a human.")]], chatRunId);
25
- await tracer.handleLLMEnd({ generations: [[]] }, chatRunId);
26
- await tracer.handleToolEnd("output", toolRunId);
27
- const llmRunId2 = uuid.v4();
28
- await tracer.handleLLMStart(serialized, ["test"], llmRunId2, chainRunId);
29
- await tracer.handleLLMEnd({ generations: [[]] }, llmRunId2);
30
- await tracer.handleChainEnd({ foo: "bar" }, chainRunId);
31
- const llmRunId3 = uuid.v4();
32
- await tracer.handleLLMStart(serialized, ["test"], llmRunId3);
33
- await tracer.handleLLMEnd({ generations: [[]] }, llmRunId3);
34
- });
35
- class FakeTracer extends LangChainTracer {
36
- constructor() {
37
- super(...arguments);
38
- Object.defineProperty(this, "createOperations", {
39
- enumerable: true,
40
- configurable: true,
41
- writable: true,
42
- value: {}
43
- });
44
- Object.defineProperty(this, "updateOperations", {
45
- enumerable: true,
46
- configurable: true,
47
- writable: true,
48
- value: {}
49
- });
50
- }
51
- async onRunCreate(run) {
52
- this.createOperations[run.id] = run;
53
- }
54
- async onRunUpdate(run) {
55
- this.updateOperations[run.id] = run;
56
- }
57
- }
58
- test("LangChain V2 tracer creates and updates runs with trace_id and dotted_order", async () => {
59
- const tracer = new FakeTracer({
60
- projectName: `JS Int Test - ${uuid.v4()}`,
61
- });
62
- const chainRunId = uuid.v4();
63
- const llmRunId = uuid.v4();
64
- await tracer.handleChainStart(serialized, { foo: "bar" }, chainRunId);
65
- await tracer.handleLLMStart(serialized, ["test"], llmRunId, chainRunId);
66
- await tracer.handleLLMEnd({ generations: [[]] }, llmRunId);
67
- await tracer.handleChainEnd({ foo: "bar" }, chainRunId);
68
- expect(tracer.createOperations[chainRunId].trace_id).toBeDefined();
69
- expect(tracer.createOperations[chainRunId].trace_id).toEqual(chainRunId);
70
- expect(tracer.createOperations[chainRunId].dotted_order).toBeDefined();
71
- expect(tracer.updateOperations[llmRunId].trace_id).toBeDefined();
72
- expect(tracer.updateOperations[llmRunId].trace_id).toEqual(chainRunId);
73
- expect(tracer.updateOperations[llmRunId].dotted_order).toBeDefined();
74
- });
@@ -1 +0,0 @@
1
- export {};