langchain 0.0.138 → 0.0.139

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 (52) hide show
  1. package/dist/agents/initialize.cjs +11 -0
  2. package/dist/agents/initialize.d.ts +4 -0
  3. package/dist/agents/initialize.js +11 -0
  4. package/dist/agents/xml/index.cjs +119 -0
  5. package/dist/agents/xml/index.d.ts +51 -0
  6. package/dist/agents/xml/index.js +114 -0
  7. package/dist/agents/xml/prompt.cjs +23 -0
  8. package/dist/agents/xml/prompt.d.ts +1 -0
  9. package/dist/agents/xml/prompt.js +20 -0
  10. package/dist/callbacks/base.d.ts +12 -4
  11. package/dist/callbacks/handlers/run_collector.cjs +50 -0
  12. package/dist/callbacks/handlers/run_collector.d.ts +26 -0
  13. package/dist/callbacks/handlers/run_collector.js +46 -0
  14. package/dist/callbacks/handlers/tracer.cjs +16 -3
  15. package/dist/callbacks/handlers/tracer.d.ts +6 -2
  16. package/dist/callbacks/handlers/tracer.js +16 -3
  17. package/dist/callbacks/handlers/tracer_langchain.cjs +1 -0
  18. package/dist/callbacks/handlers/tracer_langchain.d.ts +2 -1
  19. package/dist/callbacks/handlers/tracer_langchain.js +1 -0
  20. package/dist/callbacks/index.cjs +3 -1
  21. package/dist/callbacks/index.d.ts +1 -0
  22. package/dist/callbacks/index.js +1 -0
  23. package/dist/callbacks/manager.cjs +4 -4
  24. package/dist/callbacks/manager.d.ts +6 -2
  25. package/dist/callbacks/manager.js +4 -4
  26. package/dist/chains/openai_functions/extraction.cjs +2 -2
  27. package/dist/chains/openai_functions/extraction.d.ts +5 -4
  28. package/dist/chains/openai_functions/extraction.js +2 -2
  29. package/dist/chains/openai_functions/openapi.d.ts +2 -1
  30. package/dist/chains/openai_functions/structured_output.d.ts +4 -3
  31. package/dist/chains/openai_functions/tagging.cjs +2 -2
  32. package/dist/chains/openai_functions/tagging.d.ts +5 -4
  33. package/dist/chains/openai_functions/tagging.js +2 -2
  34. package/dist/chat_models/anthropic.cjs +7 -5
  35. package/dist/chat_models/anthropic.d.ts +17 -12
  36. package/dist/chat_models/anthropic.js +4 -2
  37. package/dist/experimental/chat_models/anthropic_functions.cjs +129 -0
  38. package/dist/experimental/chat_models/anthropic_functions.d.ts +20 -0
  39. package/dist/experimental/chat_models/anthropic_functions.js +125 -0
  40. package/dist/load/import_constants.cjs +1 -0
  41. package/dist/load/import_constants.js +1 -0
  42. package/dist/schema/output_parser.cjs +1 -1
  43. package/dist/schema/output_parser.js +1 -1
  44. package/dist/schema/runnable.cjs +54 -15
  45. package/dist/schema/runnable.d.ts +9 -3
  46. package/dist/schema/runnable.js +55 -16
  47. package/dist/sql_db.cjs +3 -1
  48. package/dist/sql_db.js +3 -1
  49. package/experimental/chat_models/anthropic_functions.cjs +1 -0
  50. package/experimental/chat_models/anthropic_functions.d.ts +1 -0
  51. package/experimental/chat_models/anthropic_functions.js +1 -0
  52. package/package.json +16 -3
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AnthropicFunctions = void 0;
4
+ const fast_xml_parser_1 = require("fast-xml-parser");
5
+ const index_js_1 = require("../../schema/index.cjs");
6
+ const anthropic_js_1 = require("../../chat_models/anthropic.cjs");
7
+ const prompt_js_1 = require("../../prompts/prompt.cjs");
8
+ const convert_to_openai_js_1 = require("../../tools/convert_to_openai.cjs");
9
+ const TOOL_SYSTEM_PROMPT =
10
+ /* #__PURE__ */
11
+ prompt_js_1.PromptTemplate.fromTemplate(`In addition to responding, you can use tools.
12
+ You have access to the following tools.
13
+
14
+ {tools}
15
+
16
+ In order to use a tool, you can use <tool></tool> to specify the name,
17
+ and the <tool_input></tool_input> tags to specify the parameters.
18
+ Each parameter should be passed in as <$param_name>$value</$param_name>,
19
+ Where $param_name is the name of the specific parameter, and $value
20
+ is the value for that parameter.
21
+
22
+ You will then get back a response in the form <observation></observation>
23
+ For example, if you have a tool called 'search' that accepts a single
24
+ parameter 'query' that could run a google search, in order to search
25
+ for the weather in SF you would respond:
26
+
27
+ <tool>search</tool><tool_input><query>weather in SF</query></tool_input>
28
+ <observation>64 degrees</observation>`);
29
+ class AnthropicFunctions extends anthropic_js_1.ChatAnthropic {
30
+ static lc_name() {
31
+ return "AnthropicFunctions";
32
+ }
33
+ constructor(fields) {
34
+ super(fields ?? {});
35
+ }
36
+ async _generate(messages, options, runManager) {
37
+ let promptMessages = messages;
38
+ let forced = false;
39
+ let functionCall;
40
+ if (options.tools) {
41
+ // eslint-disable-next-line no-param-reassign
42
+ options.functions = (options.functions ?? []).concat(options.tools.map(convert_to_openai_js_1.formatToOpenAIFunction));
43
+ }
44
+ if (options.functions !== undefined && options.functions.length > 0) {
45
+ const content = await TOOL_SYSTEM_PROMPT.format({
46
+ tools: JSON.stringify(options.functions, null, 2),
47
+ });
48
+ const systemMessage = new index_js_1.SystemMessage({ content });
49
+ promptMessages = [systemMessage].concat(promptMessages);
50
+ const stopSequences = options?.stop?.concat(anthropic_js_1.DEFAULT_STOP_SEQUENCES) ??
51
+ this.stopSequences ??
52
+ anthropic_js_1.DEFAULT_STOP_SEQUENCES;
53
+ // eslint-disable-next-line no-param-reassign
54
+ options.stop = stopSequences.concat(["</tool_input>"]);
55
+ if (options.function_call) {
56
+ if (typeof options.function_call === "string") {
57
+ functionCall = JSON.parse(options.function_call).name;
58
+ }
59
+ else {
60
+ functionCall = options.function_call.name;
61
+ }
62
+ forced = true;
63
+ const matchingFunction = options.functions.find((tool) => tool.name === functionCall);
64
+ if (!matchingFunction) {
65
+ throw new Error(`No matching function found for passed "function_call"`);
66
+ }
67
+ promptMessages = promptMessages.concat([
68
+ new index_js_1.AIMessage({
69
+ content: `<tool>${functionCall}</tool>`,
70
+ }),
71
+ ]);
72
+ // eslint-disable-next-line no-param-reassign
73
+ delete options.function_call;
74
+ }
75
+ // eslint-disable-next-line no-param-reassign
76
+ delete options.functions;
77
+ }
78
+ else if (options.function_call !== undefined) {
79
+ throw new Error(`If "function_call" is provided, "functions" must also be.`);
80
+ }
81
+ const chatResult = await super._generate(promptMessages, options, runManager);
82
+ const chatGenerationContent = chatResult.generations[0].message.content;
83
+ if (forced) {
84
+ const parser = new fast_xml_parser_1.XMLParser();
85
+ const result = parser.parse(`${chatGenerationContent}</tool_input>`);
86
+ const responseMessageWithFunctions = new index_js_1.AIMessage({
87
+ content: "",
88
+ additional_kwargs: {
89
+ function_call: {
90
+ name: functionCall,
91
+ arguments: result.tool_input
92
+ ? JSON.stringify(result.tool_input)
93
+ : "",
94
+ },
95
+ },
96
+ });
97
+ return {
98
+ generations: [{ message: responseMessageWithFunctions, text: "" }],
99
+ };
100
+ }
101
+ else if (chatGenerationContent.includes("<tool>")) {
102
+ const parser = new fast_xml_parser_1.XMLParser();
103
+ const result = parser.parse(`${chatGenerationContent}</tool_input>`);
104
+ const responseMessageWithFunctions = new index_js_1.AIMessage({
105
+ content: chatGenerationContent.split("<tool>")[0],
106
+ additional_kwargs: {
107
+ function_call: {
108
+ name: result.tool,
109
+ arguments: result.tool_input
110
+ ? JSON.stringify(result.tool_input)
111
+ : "",
112
+ },
113
+ },
114
+ });
115
+ return {
116
+ generations: [{ message: responseMessageWithFunctions, text: "" }],
117
+ };
118
+ }
119
+ return chatResult;
120
+ }
121
+ _llmType() {
122
+ return "anthropic_functions";
123
+ }
124
+ /** @ignore */
125
+ _combineLLMOutput() {
126
+ return [];
127
+ }
128
+ }
129
+ exports.AnthropicFunctions = AnthropicFunctions;
@@ -0,0 +1,20 @@
1
+ import type { ChatCompletionFunctions, CreateChatCompletionRequestFunctionCall } from "openai";
2
+ import { BaseChatModelParams } from "../../chat_models/base.js";
3
+ import { CallbackManagerForLLMRun } from "../../callbacks/manager.js";
4
+ import { BaseMessage, ChatResult } from "../../schema/index.js";
5
+ import { ChatAnthropic, type AnthropicInput } from "../../chat_models/anthropic.js";
6
+ import { BaseLanguageModelCallOptions } from "../../base_language/index.js";
7
+ import { StructuredTool } from "../../tools/base.js";
8
+ export interface ChatAnthropicFunctionsCallOptions extends BaseLanguageModelCallOptions {
9
+ function_call?: CreateChatCompletionRequestFunctionCall;
10
+ functions?: ChatCompletionFunctions[];
11
+ tools?: StructuredTool[];
12
+ }
13
+ export declare class AnthropicFunctions extends ChatAnthropic<ChatAnthropicFunctionsCallOptions> {
14
+ static lc_name(): string;
15
+ constructor(fields?: Partial<AnthropicInput> & BaseChatModelParams);
16
+ _generate(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun | undefined): Promise<ChatResult>;
17
+ _llmType(): string;
18
+ /** @ignore */
19
+ _combineLLMOutput(): never[];
20
+ }
@@ -0,0 +1,125 @@
1
+ import { XMLParser } from "fast-xml-parser";
2
+ import { AIMessage, SystemMessage, } from "../../schema/index.js";
3
+ import { ChatAnthropic, DEFAULT_STOP_SEQUENCES, } from "../../chat_models/anthropic.js";
4
+ import { PromptTemplate } from "../../prompts/prompt.js";
5
+ import { formatToOpenAIFunction } from "../../tools/convert_to_openai.js";
6
+ const TOOL_SYSTEM_PROMPT =
7
+ /* #__PURE__ */
8
+ PromptTemplate.fromTemplate(`In addition to responding, you can use tools.
9
+ You have access to the following tools.
10
+
11
+ {tools}
12
+
13
+ In order to use a tool, you can use <tool></tool> to specify the name,
14
+ and the <tool_input></tool_input> tags to specify the parameters.
15
+ Each parameter should be passed in as <$param_name>$value</$param_name>,
16
+ Where $param_name is the name of the specific parameter, and $value
17
+ is the value for that parameter.
18
+
19
+ You will then get back a response in the form <observation></observation>
20
+ For example, if you have a tool called 'search' that accepts a single
21
+ parameter 'query' that could run a google search, in order to search
22
+ for the weather in SF you would respond:
23
+
24
+ <tool>search</tool><tool_input><query>weather in SF</query></tool_input>
25
+ <observation>64 degrees</observation>`);
26
+ export class AnthropicFunctions extends ChatAnthropic {
27
+ static lc_name() {
28
+ return "AnthropicFunctions";
29
+ }
30
+ constructor(fields) {
31
+ super(fields ?? {});
32
+ }
33
+ async _generate(messages, options, runManager) {
34
+ let promptMessages = messages;
35
+ let forced = false;
36
+ let functionCall;
37
+ if (options.tools) {
38
+ // eslint-disable-next-line no-param-reassign
39
+ options.functions = (options.functions ?? []).concat(options.tools.map(formatToOpenAIFunction));
40
+ }
41
+ if (options.functions !== undefined && options.functions.length > 0) {
42
+ const content = await TOOL_SYSTEM_PROMPT.format({
43
+ tools: JSON.stringify(options.functions, null, 2),
44
+ });
45
+ const systemMessage = new SystemMessage({ content });
46
+ promptMessages = [systemMessage].concat(promptMessages);
47
+ const stopSequences = options?.stop?.concat(DEFAULT_STOP_SEQUENCES) ??
48
+ this.stopSequences ??
49
+ DEFAULT_STOP_SEQUENCES;
50
+ // eslint-disable-next-line no-param-reassign
51
+ options.stop = stopSequences.concat(["</tool_input>"]);
52
+ if (options.function_call) {
53
+ if (typeof options.function_call === "string") {
54
+ functionCall = JSON.parse(options.function_call).name;
55
+ }
56
+ else {
57
+ functionCall = options.function_call.name;
58
+ }
59
+ forced = true;
60
+ const matchingFunction = options.functions.find((tool) => tool.name === functionCall);
61
+ if (!matchingFunction) {
62
+ throw new Error(`No matching function found for passed "function_call"`);
63
+ }
64
+ promptMessages = promptMessages.concat([
65
+ new AIMessage({
66
+ content: `<tool>${functionCall}</tool>`,
67
+ }),
68
+ ]);
69
+ // eslint-disable-next-line no-param-reassign
70
+ delete options.function_call;
71
+ }
72
+ // eslint-disable-next-line no-param-reassign
73
+ delete options.functions;
74
+ }
75
+ else if (options.function_call !== undefined) {
76
+ throw new Error(`If "function_call" is provided, "functions" must also be.`);
77
+ }
78
+ const chatResult = await super._generate(promptMessages, options, runManager);
79
+ const chatGenerationContent = chatResult.generations[0].message.content;
80
+ if (forced) {
81
+ const parser = new XMLParser();
82
+ const result = parser.parse(`${chatGenerationContent}</tool_input>`);
83
+ const responseMessageWithFunctions = new AIMessage({
84
+ content: "",
85
+ additional_kwargs: {
86
+ function_call: {
87
+ name: functionCall,
88
+ arguments: result.tool_input
89
+ ? JSON.stringify(result.tool_input)
90
+ : "",
91
+ },
92
+ },
93
+ });
94
+ return {
95
+ generations: [{ message: responseMessageWithFunctions, text: "" }],
96
+ };
97
+ }
98
+ else if (chatGenerationContent.includes("<tool>")) {
99
+ const parser = new XMLParser();
100
+ const result = parser.parse(`${chatGenerationContent}</tool_input>`);
101
+ const responseMessageWithFunctions = new AIMessage({
102
+ content: chatGenerationContent.split("<tool>")[0],
103
+ additional_kwargs: {
104
+ function_call: {
105
+ name: result.tool,
106
+ arguments: result.tool_input
107
+ ? JSON.stringify(result.tool_input)
108
+ : "",
109
+ },
110
+ },
111
+ });
112
+ return {
113
+ generations: [{ message: responseMessageWithFunctions, text: "" }],
114
+ };
115
+ }
116
+ return chatResult;
117
+ }
118
+ _llmType() {
119
+ return "anthropic_functions";
120
+ }
121
+ /** @ignore */
122
+ _combineLLMOutput() {
123
+ return [];
124
+ }
125
+ }
@@ -121,4 +121,5 @@ exports.optionalImportEntrypoints = [
121
121
  "langchain/storage/ioredis",
122
122
  "langchain/hub",
123
123
  "langchain/experimental/multimodal_embeddings/googlevertexai",
124
+ "langchain/experimental/chat_models/anthropic_functions",
124
125
  ];
@@ -118,4 +118,5 @@ export const optionalImportEntrypoints = [
118
118
  "langchain/storage/ioredis",
119
119
  "langchain/hub",
120
120
  "langchain/experimental/multimodal_embeddings/googlevertexai",
121
+ "langchain/experimental/chat_models/anthropic_functions",
121
122
  ];
@@ -79,7 +79,7 @@ class BaseTransformOutputParser extends BaseOutputParser {
79
79
  * @returns An asynchronous generator of parsed output.
80
80
  */
81
81
  async *transform(inputGenerator, options) {
82
- yield* this._streamWithConfig(this._transform(inputGenerator), {
82
+ yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), {
83
83
  ...options,
84
84
  runType: "parser",
85
85
  });
@@ -74,7 +74,7 @@ export class BaseTransformOutputParser extends BaseOutputParser {
74
74
  * @returns An asynchronous generator of parsed output.
75
75
  */
76
76
  async *transform(inputGenerator, options) {
77
- yield* this._streamWithConfig(this._transform(inputGenerator), {
77
+ yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), {
78
78
  ...options,
79
79
  runType: "parser",
80
80
  });
@@ -122,37 +122,73 @@ class Runnable extends serializable_js_1.Serializable {
122
122
  await runManager?.handleChainEnd(_coerceToDict(output, "output"));
123
123
  return output;
124
124
  }
125
- async *_streamWithConfig(generator, options) {
125
+ /**
126
+ * Helper method to transform an Iterator of Input values into an Iterator of
127
+ * Output values, with callbacks.
128
+ * Use this to implement `stream()` or `transform()` in Runnable subclasses.
129
+ */
130
+ async *_transformStreamWithConfig(inputGenerator, transformer, options) {
131
+ let finalInput;
132
+ let finalInputSupported = true;
133
+ let finalOutput;
134
+ let finalOutputSupported = true;
126
135
  const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
127
- // TODO: Find a way to pass the entire streamed value into the callback.
128
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict("<streamed value>", "input"), undefined, options?.runType);
129
- let output;
130
- let concatSupported = true;
136
+ let runManager;
137
+ const serializedRepresentation = this.toJSON();
138
+ async function* wrapInputForTracing() {
139
+ for await (const chunk of inputGenerator) {
140
+ if (!runManager) {
141
+ // Start the run manager AFTER the iterator starts to preserve
142
+ // tracing order
143
+ runManager = await callbackManager_?.handleChainStart(serializedRepresentation, { input: "" }, undefined, options?.runType);
144
+ }
145
+ if (finalInputSupported) {
146
+ if (finalInput === undefined) {
147
+ finalInput = chunk;
148
+ }
149
+ else {
150
+ try {
151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
+ finalInput = finalInput.concat(chunk);
153
+ }
154
+ catch {
155
+ finalInput = undefined;
156
+ finalInputSupported = false;
157
+ }
158
+ }
159
+ }
160
+ yield chunk;
161
+ }
162
+ }
163
+ const wrappedInputGenerator = wrapInputForTracing();
131
164
  try {
132
- for await (const chunk of generator) {
165
+ const outputIterator = transformer(wrappedInputGenerator, runManager, options);
166
+ for await (const chunk of outputIterator) {
133
167
  yield chunk;
134
- if (concatSupported) {
135
- if (output === undefined) {
136
- output = chunk;
168
+ if (finalOutputSupported) {
169
+ if (finalOutput === undefined) {
170
+ finalOutput = chunk;
137
171
  }
138
172
  else {
139
173
  try {
140
174
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
141
- output = output.concat(chunk);
175
+ finalOutput = finalOutput.concat(chunk);
142
176
  }
143
- catch (e) {
144
- output = undefined;
145
- concatSupported = false;
177
+ catch {
178
+ finalOutput = undefined;
179
+ finalOutputSupported = false;
146
180
  }
147
181
  }
148
182
  }
149
183
  }
150
184
  }
151
185
  catch (e) {
152
- await runManager?.handleChainError(e);
186
+ await runManager?.handleChainError(e, undefined, undefined, undefined, {
187
+ inputs: _coerceToDict(finalInput, "input"),
188
+ });
153
189
  throw e;
154
190
  }
155
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
191
+ await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") });
156
192
  }
157
193
  _patchConfig(config = {}, callbackManager = undefined) {
158
194
  return { ...config, callbacks: callbackManager };
@@ -411,6 +447,9 @@ exports.RunnableMap = RunnableMap;
411
447
  * A runnable that runs a callable.
412
448
  */
413
449
  class RunnableLambda extends Runnable {
450
+ static lc_name() {
451
+ return "RunnableLambda";
452
+ }
414
453
  constructor(fields) {
415
454
  super(fields);
416
455
  Object.defineProperty(this, "lc_namespace", {
@@ -1,4 +1,4 @@
1
- import { BaseCallbackConfig, CallbackManager } from "../callbacks/manager.js";
1
+ import { BaseCallbackConfig, CallbackManager, CallbackManagerForChainRun } from "../callbacks/manager.js";
2
2
  import { Serializable } from "../load/serializable.js";
3
3
  import { IterableReadableStream } from "../util/stream.js";
4
4
  export type RunnableConfig = BaseCallbackConfig;
@@ -58,9 +58,14 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
58
58
  protected _callWithConfig<T extends RunInput>(func: (input: T) => Promise<RunOutput>, input: T, options?: RunnableConfig & {
59
59
  runType?: string;
60
60
  }): Promise<RunOutput>;
61
- protected _streamWithConfig<T extends RunOutput>(generator: AsyncGenerator<T>, options?: RunnableConfig & {
61
+ /**
62
+ * Helper method to transform an Iterator of Input values into an Iterator of
63
+ * Output values, with callbacks.
64
+ * Use this to implement `stream()` or `transform()` in Runnable subclasses.
65
+ */
66
+ protected _transformStreamWithConfig<I extends RunInput, O extends RunOutput>(inputGenerator: AsyncGenerator<I>, transformer: (generator: AsyncGenerator<I>, runManager?: CallbackManagerForChainRun, options?: Partial<RunnableConfig>) => AsyncGenerator<O>, options?: RunnableConfig & {
62
67
  runType?: string;
63
- }): AsyncGenerator<Awaited<T>, void, unknown>;
68
+ }): AsyncGenerator<O>;
64
69
  _patchConfig(config?: Partial<CallOptions>, callbackManager?: CallbackManager | undefined): Partial<CallOptions>;
65
70
  /**
66
71
  * Create a new runnable sequence that runs each individual runnable in series,
@@ -126,6 +131,7 @@ export declare class RunnableMap<RunInput> extends Runnable<RunInput, Record<str
126
131
  * A runnable that runs a callable.
127
132
  */
128
133
  export declare class RunnableLambda<RunInput, RunOutput> extends Runnable<RunInput, RunOutput> {
134
+ static lc_name(): string;
129
135
  lc_namespace: string[];
130
136
  protected func: RunnableFunc<RunInput, RunOutput>;
131
137
  constructor(fields: {
@@ -1,4 +1,4 @@
1
- import { CallbackManager } from "../callbacks/manager.js";
1
+ import { CallbackManager, } from "../callbacks/manager.js";
2
2
  import { Serializable } from "../load/serializable.js";
3
3
  import { IterableReadableStream } from "../util/stream.js";
4
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -119,37 +119,73 @@ export class Runnable extends Serializable {
119
119
  await runManager?.handleChainEnd(_coerceToDict(output, "output"));
120
120
  return output;
121
121
  }
122
- async *_streamWithConfig(generator, options) {
122
+ /**
123
+ * Helper method to transform an Iterator of Input values into an Iterator of
124
+ * Output values, with callbacks.
125
+ * Use this to implement `stream()` or `transform()` in Runnable subclasses.
126
+ */
127
+ async *_transformStreamWithConfig(inputGenerator, transformer, options) {
128
+ let finalInput;
129
+ let finalInputSupported = true;
130
+ let finalOutput;
131
+ let finalOutputSupported = true;
123
132
  const callbackManager_ = await CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
124
- // TODO: Find a way to pass the entire streamed value into the callback.
125
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict("<streamed value>", "input"), undefined, options?.runType);
126
- let output;
127
- let concatSupported = true;
133
+ let runManager;
134
+ const serializedRepresentation = this.toJSON();
135
+ async function* wrapInputForTracing() {
136
+ for await (const chunk of inputGenerator) {
137
+ if (!runManager) {
138
+ // Start the run manager AFTER the iterator starts to preserve
139
+ // tracing order
140
+ runManager = await callbackManager_?.handleChainStart(serializedRepresentation, { input: "" }, undefined, options?.runType);
141
+ }
142
+ if (finalInputSupported) {
143
+ if (finalInput === undefined) {
144
+ finalInput = chunk;
145
+ }
146
+ else {
147
+ try {
148
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
149
+ finalInput = finalInput.concat(chunk);
150
+ }
151
+ catch {
152
+ finalInput = undefined;
153
+ finalInputSupported = false;
154
+ }
155
+ }
156
+ }
157
+ yield chunk;
158
+ }
159
+ }
160
+ const wrappedInputGenerator = wrapInputForTracing();
128
161
  try {
129
- for await (const chunk of generator) {
162
+ const outputIterator = transformer(wrappedInputGenerator, runManager, options);
163
+ for await (const chunk of outputIterator) {
130
164
  yield chunk;
131
- if (concatSupported) {
132
- if (output === undefined) {
133
- output = chunk;
165
+ if (finalOutputSupported) {
166
+ if (finalOutput === undefined) {
167
+ finalOutput = chunk;
134
168
  }
135
169
  else {
136
170
  try {
137
171
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
138
- output = output.concat(chunk);
172
+ finalOutput = finalOutput.concat(chunk);
139
173
  }
140
- catch (e) {
141
- output = undefined;
142
- concatSupported = false;
174
+ catch {
175
+ finalOutput = undefined;
176
+ finalOutputSupported = false;
143
177
  }
144
178
  }
145
179
  }
146
180
  }
147
181
  }
148
182
  catch (e) {
149
- await runManager?.handleChainError(e);
183
+ await runManager?.handleChainError(e, undefined, undefined, undefined, {
184
+ inputs: _coerceToDict(finalInput, "input"),
185
+ });
150
186
  throw e;
151
187
  }
152
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
188
+ await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") });
153
189
  }
154
190
  _patchConfig(config = {}, callbackManager = undefined) {
155
191
  return { ...config, callbacks: callbackManager };
@@ -405,6 +441,9 @@ export class RunnableMap extends Runnable {
405
441
  * A runnable that runs a callable.
406
442
  */
407
443
  export class RunnableLambda extends Runnable {
444
+ static lc_name() {
445
+ return "RunnableLambda";
446
+ }
408
447
  constructor(fields) {
409
448
  super(fields);
410
449
  Object.defineProperty(this, "lc_namespace", {
package/dist/sql_db.cjs CHANGED
@@ -66,7 +66,6 @@ class SqlDatabase extends serializable_js_1.Serializable {
66
66
  this.ignoreTables = fields?.ignoreTables ?? [];
67
67
  this.sampleRowsInTableInfo =
68
68
  fields?.sampleRowsInTableInfo ?? this.sampleRowsInTableInfo;
69
- this.customDescription = Object.fromEntries(Object.entries(fields?.customDescription ?? {}).filter(([key, _]) => this.allTables.map((table) => table.tableName).includes(key)));
70
69
  }
71
70
  static async fromDataSourceParams(fields) {
72
71
  const sqlDatabase = new SqlDatabase(fields);
@@ -74,6 +73,9 @@ class SqlDatabase extends serializable_js_1.Serializable {
74
73
  await sqlDatabase.appDataSource.initialize();
75
74
  }
76
75
  sqlDatabase.allTables = await (0, sql_utils_js_1.getTableAndColumnsName)(sqlDatabase.appDataSource);
76
+ sqlDatabase.customDescription = Object.fromEntries(Object.entries(fields?.customDescription ?? {}).filter(([key, _]) => sqlDatabase.allTables
77
+ .map((table) => table.tableName)
78
+ .includes(key)));
77
79
  (0, sql_utils_js_1.verifyIncludeTablesExistInDatabase)(sqlDatabase.allTables, sqlDatabase.includesTables);
78
80
  (0, sql_utils_js_1.verifyIgnoreTablesExistInDatabase)(sqlDatabase.allTables, sqlDatabase.ignoreTables);
79
81
  return sqlDatabase;
package/dist/sql_db.js CHANGED
@@ -63,7 +63,6 @@ export class SqlDatabase extends Serializable {
63
63
  this.ignoreTables = fields?.ignoreTables ?? [];
64
64
  this.sampleRowsInTableInfo =
65
65
  fields?.sampleRowsInTableInfo ?? this.sampleRowsInTableInfo;
66
- this.customDescription = Object.fromEntries(Object.entries(fields?.customDescription ?? {}).filter(([key, _]) => this.allTables.map((table) => table.tableName).includes(key)));
67
66
  }
68
67
  static async fromDataSourceParams(fields) {
69
68
  const sqlDatabase = new SqlDatabase(fields);
@@ -71,6 +70,9 @@ export class SqlDatabase extends Serializable {
71
70
  await sqlDatabase.appDataSource.initialize();
72
71
  }
73
72
  sqlDatabase.allTables = await getTableAndColumnsName(sqlDatabase.appDataSource);
73
+ sqlDatabase.customDescription = Object.fromEntries(Object.entries(fields?.customDescription ?? {}).filter(([key, _]) => sqlDatabase.allTables
74
+ .map((table) => table.tableName)
75
+ .includes(key)));
74
76
  verifyIncludeTablesExistInDatabase(sqlDatabase.allTables, sqlDatabase.includesTables);
75
77
  verifyIgnoreTablesExistInDatabase(sqlDatabase.allTables, sqlDatabase.ignoreTables);
76
78
  return sqlDatabase;
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/experimental/chat_models/anthropic_functions.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/experimental/chat_models/anthropic_functions.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/experimental/chat_models/anthropic_functions.js'