@langchain/core 1.2.6 → 1.2.8
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 +23 -0
- package/dist/errors/index.cjs +39 -1
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.d.cts +19 -1
- package/dist/errors/index.d.cts.map +1 -1
- package/dist/errors/index.d.ts +19 -1
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +38 -2
- package/dist/errors/index.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.d.cts +4 -0
- package/dist/language_models/base.d.cts.map +1 -1
- package/dist/language_models/base.d.ts +4 -0
- package/dist/language_models/base.d.ts.map +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/utils/async_caller.cjs +16 -8
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.d.cts +2 -0
- package/dist/utils/async_caller.d.cts.map +1 -1
- package/dist/utils/async_caller.d.ts +2 -0
- package/dist/utils/async_caller.d.ts.map +1 -1
- package/dist/utils/async_caller.js +16 -8
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/gateway.cjs +5 -1
- package/dist/utils/gateway.cjs.map +1 -1
- package/dist/utils/gateway.d.cts +2 -1
- package/dist/utils/gateway.d.cts.map +1 -1
- package/dist/utils/gateway.d.ts +2 -1
- package/dist/utils/gateway.d.ts.map +1 -1
- package/dist/utils/gateway.js +5 -2
- package/dist/utils/gateway.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @langchain/core
|
|
2
2
|
|
|
3
|
+
## 1.2.8
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#11369](https://github.com/langchain-ai/langchainjs/pull/11369) [`d6ad973`](https://github.com/langchain-ai/langchainjs/commit/d6ad9735640a6c729f81ef79361acc5e83c526f1) Thanks [@hntrl](https://github.com/hntrl)! - fix(langchain): use unified endpoint for gateway
|
|
8
|
+
|
|
9
|
+
- [#11342](https://github.com/langchain-ai/langchainjs/pull/11342) [`3b0e4c4`](https://github.com/langchain-ai/langchainjs/commit/3b0e4c48a31811031a460c4d95519a7c1163dc41) Thanks [@thushanth-bengre-langchain](https://github.com/thushanth-bengre-langchain)! - feat(core): mark errors as retryable or not, and stop retrying the ones that aren't
|
|
10
|
+
|
|
11
|
+
Retry middleware retried every failure up to `maxRetries`, including deterministic ones like a bad API key or an unknown model. Retries also nest, so a single such failure could cost dozens of API calls.
|
|
12
|
+
|
|
13
|
+
`@langchain/core/errors` adds `stampRetryable(error, retryable)` and `getRetryable(error)`. Marking an error leaves its class and shape untouched, so a provider SDK error can be classified without breaking `instanceof`. `getRetryable` returns `undefined` for errors nobody classified, and both are exported so tool authors can mark their own failures.
|
|
14
|
+
|
|
15
|
+
`modelRetryMiddleware` and `toolRetryMiddleware` now respect the mark by default, and retries stop as soon as one is found rather than each layer spending its own budget. Aborted calls, context overflow, and oversized payloads are marked non-retryable out of the box.
|
|
16
|
+
Models accept a per-call `maxRetries` so a surrounding retry loop can take over.
|
|
17
|
+
|
|
18
|
+
**Behavior change:** errors marked non-retryable now fail on the first attempt. Unclassified errors — including any from third-party integrations or custom tools — retry exactly as before. Pass `retryOn: () => true` to restore the old default. A custom `onFailedAttempt` replaces the built-in handler and opts out of marking.
|
|
19
|
+
|
|
20
|
+
## 1.2.7
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- [#11366](https://github.com/langchain-ai/langchainjs/pull/11366) [`c068bbf`](https://github.com/langchain-ai/langchainjs/commit/c068bbf8c113132bf16ac7a8add44e486a147b41) Thanks [@hntrl](https://github.com/hntrl)! - fix(core,langchain): patch and release core, update peer dependencies
|
|
25
|
+
|
|
3
26
|
## 1.2.6
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/dist/errors/index.cjs
CHANGED
|
@@ -7,7 +7,9 @@ var errors_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
|
7
7
|
LangChainError: () => LangChainError,
|
|
8
8
|
ModelAbortError: () => ModelAbortError,
|
|
9
9
|
addLangChainErrorFields: () => addLangChainErrorFields,
|
|
10
|
-
|
|
10
|
+
getRetryable: () => getRetryable,
|
|
11
|
+
ns: () => ns,
|
|
12
|
+
stampRetryable: () => stampRetryable
|
|
11
13
|
});
|
|
12
14
|
/** @deprecated Subclass LangChainError instead */
|
|
13
15
|
function addLangChainErrorFields(error, lc_error_code) {
|
|
@@ -17,6 +19,38 @@ function addLangChainErrorFields(error, lc_error_code) {
|
|
|
17
19
|
}
|
|
18
20
|
/** The error namespace for all LangChain errors */
|
|
19
21
|
const ns = require_namespace.ns.sub("error");
|
|
22
|
+
/** Registered globally so duplicate copies of core in one dependency tree agree. */
|
|
23
|
+
const retryableSymbol = Symbol.for("langchain.errors.retryable");
|
|
24
|
+
/**
|
|
25
|
+
* Mark an error as safe or unsafe to retry.
|
|
26
|
+
*
|
|
27
|
+
* Sets a non-enumerable symbol on the error itself, leaving its class and
|
|
28
|
+
* shape untouched, so it is safe to apply to a provider SDK's own error.
|
|
29
|
+
*
|
|
30
|
+
* @param error - The error to mark. Non-objects are returned untouched.
|
|
31
|
+
* @param retryable - `true` if retrying may succeed.
|
|
32
|
+
* @returns The same error instance, for chaining.
|
|
33
|
+
*/
|
|
34
|
+
function stampRetryable(error, retryable) {
|
|
35
|
+
if (typeof error !== "object" || error === null) return error;
|
|
36
|
+
try {
|
|
37
|
+
Object.defineProperty(error, retryableSymbol, {
|
|
38
|
+
value: retryable,
|
|
39
|
+
configurable: true
|
|
40
|
+
});
|
|
41
|
+
} catch {}
|
|
42
|
+
return error;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Read an error's retryability mark.
|
|
46
|
+
*
|
|
47
|
+
* @returns `true`/`false` when marked, `undefined` when unclassified —
|
|
48
|
+
* supply your own default, e.g. `getRetryable(error) ?? true`.
|
|
49
|
+
*/
|
|
50
|
+
function getRetryable(error) {
|
|
51
|
+
if (typeof error !== "object" || error === null) return;
|
|
52
|
+
return Object.getOwnPropertyDescriptor(error, retryableSymbol)?.value;
|
|
53
|
+
}
|
|
20
54
|
/**
|
|
21
55
|
* Base error class for all LangChain errors.
|
|
22
56
|
*
|
|
@@ -87,6 +121,7 @@ var ModelAbortError = class extends ns.brand(LangChainError, "model-abort") {
|
|
|
87
121
|
constructor(message, partialOutput) {
|
|
88
122
|
super(message);
|
|
89
123
|
this.partialOutput = partialOutput;
|
|
124
|
+
stampRetryable(this, false);
|
|
90
125
|
}
|
|
91
126
|
};
|
|
92
127
|
/**
|
|
@@ -132,6 +167,7 @@ var ContextOverflowError = class ContextOverflowError extends ns.brand(LangChain
|
|
|
132
167
|
cause;
|
|
133
168
|
constructor(message) {
|
|
134
169
|
super(message ?? "Input exceeded the model's context window.");
|
|
170
|
+
stampRetryable(this, false);
|
|
135
171
|
}
|
|
136
172
|
/**
|
|
137
173
|
* Creates a new {@link ContextOverflowError} instance from an existing error.
|
|
@@ -169,6 +205,8 @@ Object.defineProperty(exports, "errors_exports", {
|
|
|
169
205
|
return errors_exports;
|
|
170
206
|
}
|
|
171
207
|
});
|
|
208
|
+
exports.getRetryable = getRetryable;
|
|
172
209
|
exports.ns = ns;
|
|
210
|
+
exports.stampRetryable = stampRetryable;
|
|
173
211
|
|
|
174
212
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["baseNs"],"sources":["../../src/errors/index.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AIMessageChunk } from \"../messages/ai.js\";\nimport { ns as baseNs } from \"../utils/namespace.js\";\n\nexport type LangChainErrorCodes =\n | \"CONTEXT_OVERFLOW\"\n | \"INVALID_PROMPT_INPUT\"\n | \"INVALID_TOOL_RESULTS\"\n | \"MESSAGE_COERCION_FAILURE\"\n | \"MODEL_AUTHENTICATION\"\n | \"MODEL_NOT_FOUND\"\n | \"MODEL_RATE_LIMIT\"\n | \"OUTPUT_PARSING_FAILURE\"\n | \"MODEL_ABORTED\";\n\n/** @deprecated Subclass LangChainError instead */\nexport function addLangChainErrorFields(\n error: any,\n lc_error_code: LangChainErrorCodes\n) {\n (error as any).lc_error_code = lc_error_code;\n error.message = `${error.message}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\\n`;\n return error;\n}\n\n/** The error namespace for all LangChain errors */\nexport const ns = baseNs.sub(\"error\");\n\n/**\n * Base error class for all LangChain errors.\n *\n * All LangChain error classes should extend this class (directly or\n * indirectly). Use `LangChainError.isInstance(obj)` to check if an\n * object is any LangChain error.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(\"hello\");\n * } catch (error) {\n * if (LangChainError.isInstance(error)) {\n * console.log(\"Got a LangChain error:\", error.message);\n * }\n * }\n * ```\n */\nexport class LangChainError extends ns.brand(Error) {\n readonly name: string = \"LangChainError\";\n\n constructor(message?: string) {\n super(message);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error class representing an aborted model operation in LangChain.\n *\n * This error is thrown when a model operation (such as invocation, streaming, or batching)\n * is cancelled before it completes, commonly due to a user-initiated abort signal\n * (e.g., via an AbortController) or an upstream cancellation event.\n *\n * The ModelAbortError provides access to any partial output the model may have produced\n * before the operation was interrupted, which can be useful for resuming work, debugging,\n * or presenting incomplete results to users.\n *\n * @remarks\n * - The `partialOutput` field includes message content that was generated prior to the abort,\n * such as a partial AIMessageChunk.\n * - This error extends the {@link LangChainError} base class with the marker `\"model-abort\"`.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input, { signal: abortController.signal });\n * } catch (err) {\n * if (ModelAbortError.isInstance(err)) {\n * // Handle user cancellation, check err.partialOutput if needed\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ModelAbortError extends ns.brand(LangChainError, \"model-abort\") {\n readonly name = \"ModelAbortError\";\n\n /**\n * The partial message output that was produced before the operation was aborted.\n * This is typically an AIMessageChunk, or could be undefined if no output was available.\n */\n readonly partialOutput?: AIMessageChunk;\n\n /**\n * Constructs a new ModelAbortError instance.\n *\n * @param message - A human-readable message describing the abort event.\n * @param partialOutput - Any partial model output generated before the abort (optional).\n */\n constructor(message: string, partialOutput?: AIMessageChunk) {\n super(message);\n this.partialOutput = partialOutput;\n }\n}\n\n/**\n * Error class representing a context window overflow in a language model operation.\n *\n * This error is thrown when the combined input to a language model (such as prompt tokens,\n * historical messages, and/or instructions) exceeds the maximum context window or token limit\n * that the model can process in a single request. Most models have defined upper limits for the number of\n * tokens or characters allowed in a context, and exceeding this limit will prevent\n * the operation from proceeding.\n *\n * The {@link ContextOverflowError} extends the {@link LangChainError} base class with\n * the marker `\"context-overflow\"`.\n *\n * @remarks\n * - Use this error to programmatically identify cases where a user request, prompt, or input\n * sequence is too long to be handled by the target model.\n * - Model providers and framework integrations should throw this error if they detect\n * a request cannot be processed due to its size.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(veryLongInput);\n * } catch (err) {\n * if (ContextOverflowError.isInstance(err)) {\n * // Handle overflow, e.g., prompt user to shorten input or truncate text\n * console.warn(\"Model context overflow:\", err.message);\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ContextOverflowError extends ns.brand(\n LangChainError,\n \"context-overflow\"\n) {\n readonly name = \"ContextOverflowError\";\n\n /**\n * The underlying error that caused this {@link ContextOverflowError}, if any.\n *\n * This property is optionally set when wrapping a lower-level error using {@link ContextOverflowError.fromError}.\n * It allows error handlers to access or inspect the original error that led to the context overflow.\n */\n cause?: Error;\n\n constructor(message?: string) {\n super(message ?? \"Input exceeded the model's context window.\");\n }\n\n /**\n * Creates a new {@link ContextOverflowError} instance from an existing error.\n *\n * This static utility copies the message from the provided error and\n * attaches the original error as the {@link ContextOverflowError.cause} property,\n * enabling error handlers to inspect or propagate the original failure.\n *\n * @param obj - The original error object causing the context overflow.\n * @returns A new {@link ContextOverflowError} instance with the original error set as its cause.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input);\n * } catch (err) {\n * throw ContextOverflowError.fromError(err);\n * }\n * ```\n */\n static fromError(obj: Error): ContextOverflowError {\n const error = new ContextOverflowError(obj.message);\n error.cause = obj;\n return error;\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["baseNs"],"sources":["../../src/errors/index.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AIMessageChunk } from \"../messages/ai.js\";\nimport { ns as baseNs } from \"../utils/namespace.js\";\n\nexport type LangChainErrorCodes =\n | \"CONTEXT_OVERFLOW\"\n | \"INVALID_PROMPT_INPUT\"\n | \"INVALID_TOOL_RESULTS\"\n | \"MESSAGE_COERCION_FAILURE\"\n | \"MODEL_AUTHENTICATION\"\n | \"MODEL_NOT_FOUND\"\n | \"MODEL_RATE_LIMIT\"\n | \"OUTPUT_PARSING_FAILURE\"\n | \"MODEL_ABORTED\";\n\n/** @deprecated Subclass LangChainError instead */\nexport function addLangChainErrorFields(\n error: any,\n lc_error_code: LangChainErrorCodes\n) {\n (error as any).lc_error_code = lc_error_code;\n error.message = `${error.message}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\\n`;\n return error;\n}\n\n/** The error namespace for all LangChain errors */\nexport const ns = baseNs.sub(\"error\");\n\n/** Registered globally so duplicate copies of core in one dependency tree agree. */\nconst retryableSymbol = Symbol.for(\"langchain.errors.retryable\");\n\n/**\n * Mark an error as safe or unsafe to retry.\n *\n * Sets a non-enumerable symbol on the error itself, leaving its class and\n * shape untouched, so it is safe to apply to a provider SDK's own error.\n *\n * @param error - The error to mark. Non-objects are returned untouched.\n * @param retryable - `true` if retrying may succeed.\n * @returns The same error instance, for chaining.\n */\nexport function stampRetryable<T>(error: T, retryable: boolean): T {\n if (typeof error !== \"object\" || error === null) {\n return error;\n }\n try {\n Object.defineProperty(error, retryableSymbol, {\n value: retryable,\n configurable: true,\n });\n } catch {\n // Frozen or sealed error object; leave it unmarked rather than throwing.\n }\n return error;\n}\n\n/**\n * Read an error's retryability mark.\n *\n * @returns `true`/`false` when marked, `undefined` when unclassified —\n * supply your own default, e.g. `getRetryable(error) ?? true`.\n */\nexport function getRetryable(error: unknown): boolean | undefined {\n if (typeof error !== \"object\" || error === null) {\n return undefined;\n }\n return Object.getOwnPropertyDescriptor(error, retryableSymbol)?.value as\n | boolean\n | undefined;\n}\n\n/**\n * Base error class for all LangChain errors.\n *\n * All LangChain error classes should extend this class (directly or\n * indirectly). Use `LangChainError.isInstance(obj)` to check if an\n * object is any LangChain error.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(\"hello\");\n * } catch (error) {\n * if (LangChainError.isInstance(error)) {\n * console.log(\"Got a LangChain error:\", error.message);\n * }\n * }\n * ```\n */\nexport class LangChainError extends ns.brand(Error) {\n readonly name: string = \"LangChainError\";\n\n constructor(message?: string) {\n super(message);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error class representing an aborted model operation in LangChain.\n *\n * This error is thrown when a model operation (such as invocation, streaming, or batching)\n * is cancelled before it completes, commonly due to a user-initiated abort signal\n * (e.g., via an AbortController) or an upstream cancellation event.\n *\n * The ModelAbortError provides access to any partial output the model may have produced\n * before the operation was interrupted, which can be useful for resuming work, debugging,\n * or presenting incomplete results to users.\n *\n * @remarks\n * - The `partialOutput` field includes message content that was generated prior to the abort,\n * such as a partial AIMessageChunk.\n * - This error extends the {@link LangChainError} base class with the marker `\"model-abort\"`.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input, { signal: abortController.signal });\n * } catch (err) {\n * if (ModelAbortError.isInstance(err)) {\n * // Handle user cancellation, check err.partialOutput if needed\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ModelAbortError extends ns.brand(LangChainError, \"model-abort\") {\n readonly name = \"ModelAbortError\";\n\n /**\n * The partial message output that was produced before the operation was aborted.\n * This is typically an AIMessageChunk, or could be undefined if no output was available.\n */\n readonly partialOutput?: AIMessageChunk;\n\n /**\n * Constructs a new ModelAbortError instance.\n *\n * @param message - A human-readable message describing the abort event.\n * @param partialOutput - Any partial model output generated before the abort (optional).\n */\n constructor(message: string, partialOutput?: AIMessageChunk) {\n super(message);\n this.partialOutput = partialOutput;\n // Retrying would mean ignoring the caller's explicit abort signal.\n stampRetryable(this, false);\n }\n}\n\n/**\n * Error class representing a context window overflow in a language model operation.\n *\n * This error is thrown when the combined input to a language model (such as prompt tokens,\n * historical messages, and/or instructions) exceeds the maximum context window or token limit\n * that the model can process in a single request. Most models have defined upper limits for the number of\n * tokens or characters allowed in a context, and exceeding this limit will prevent\n * the operation from proceeding.\n *\n * The {@link ContextOverflowError} extends the {@link LangChainError} base class with\n * the marker `\"context-overflow\"`.\n *\n * @remarks\n * - Use this error to programmatically identify cases where a user request, prompt, or input\n * sequence is too long to be handled by the target model.\n * - Model providers and framework integrations should throw this error if they detect\n * a request cannot be processed due to its size.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(veryLongInput);\n * } catch (err) {\n * if (ContextOverflowError.isInstance(err)) {\n * // Handle overflow, e.g., prompt user to shorten input or truncate text\n * console.warn(\"Model context overflow:\", err.message);\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ContextOverflowError extends ns.brand(\n LangChainError,\n \"context-overflow\"\n) {\n readonly name = \"ContextOverflowError\";\n\n /**\n * The underlying error that caused this {@link ContextOverflowError}, if any.\n *\n * This property is optionally set when wrapping a lower-level error using {@link ContextOverflowError.fromError}.\n * It allows error handlers to access or inspect the original error that led to the context overflow.\n */\n cause?: Error;\n\n constructor(message?: string) {\n super(message ?? \"Input exceeded the model's context window.\");\n // The same oversized input fails identically; it needs trimming, not another attempt.\n stampRetryable(this, false);\n }\n\n /**\n * Creates a new {@link ContextOverflowError} instance from an existing error.\n *\n * This static utility copies the message from the provided error and\n * attaches the original error as the {@link ContextOverflowError.cause} property,\n * enabling error handlers to inspect or propagate the original failure.\n *\n * @param obj - The original error object causing the context overflow.\n * @returns A new {@link ContextOverflowError} instance with the original error set as its cause.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input);\n * } catch (err) {\n * throw ContextOverflowError.fromError(err);\n * }\n * ```\n */\n static fromError(obj: Error): ContextOverflowError {\n const error = new ContextOverflowError(obj.message);\n error.cause = obj;\n return error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,SAAgB,wBACd,OACA,eACA;CACA,MAAe,gBAAgB;CAC/B,MAAM,UAAU,GAAG,MAAM,QAAQ,sFAAsF,cAAc;CACrI,OAAO;AACT;;AAGA,MAAa,KAAKA,kBAAAA,GAAO,IAAI,OAAO;;AAGpC,MAAM,kBAAkB,OAAO,IAAI,4BAA4B;;;;;;;;;;;AAY/D,SAAgB,eAAkB,OAAU,WAAuB;CACjE,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,IAAI;EACF,OAAO,eAAe,OAAO,iBAAiB;GAC5C,OAAO;GACP,cAAc;EAChB,CAAC;CACH,QAAQ,CAER;CACA,OAAO;AACT;;;;;;;AAQA,SAAgB,aAAa,OAAqC;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC;CAEF,OAAO,OAAO,yBAAyB,OAAO,eAAe,CAAC,EAAE;AAGlE;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,iBAAb,cAAoC,GAAG,MAAM,KAAK,CAAC,CAAC;CAClD,OAAwB;CAExB,YAAY,SAAkB;EAC5B,MAAM,OAAO;EACb,IAAI,MAAM,mBACR,MAAM,kBAAkB,MAAM,KAAK,WAAW;CAElD;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,kBAAb,cAAqC,GAAG,MAAM,gBAAgB,aAAa,CAAC,CAAC;CAC3E,OAAgB;;;;;CAMhB;;;;;;;CAQA,YAAY,SAAiB,eAAgC;EAC3D,MAAM,OAAO;EACb,KAAK,gBAAgB;EAErB,eAAe,MAAM,KAAK;CAC5B;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,uBAAb,MAAa,6BAA6B,GAAG,MAC3C,gBACA,kBACF,CAAC,CAAC;CACA,OAAgB;;;;;;;CAQhB;CAEA,YAAY,SAAkB;EAC5B,MAAM,WAAW,4CAA4C;EAE7D,eAAe,MAAM,KAAK;CAC5B;;;;;;;;;;;;;;;;;;;;CAqBA,OAAO,UAAU,KAAkC;EACjD,MAAM,QAAQ,IAAI,qBAAqB,IAAI,OAAO;EAClD,MAAM,QAAQ;EACd,OAAO;CACT;AACF"}
|
package/dist/errors/index.d.cts
CHANGED
|
@@ -6,6 +6,24 @@ type LangChainErrorCodes = "CONTEXT_OVERFLOW" | "INVALID_PROMPT_INPUT" | "INVALI
|
|
|
6
6
|
declare function addLangChainErrorFields(error: any, lc_error_code: LangChainErrorCodes): any;
|
|
7
7
|
/** The error namespace for all LangChain errors */
|
|
8
8
|
declare const ns: Namespace;
|
|
9
|
+
/**
|
|
10
|
+
* Mark an error as safe or unsafe to retry.
|
|
11
|
+
*
|
|
12
|
+
* Sets a non-enumerable symbol on the error itself, leaving its class and
|
|
13
|
+
* shape untouched, so it is safe to apply to a provider SDK's own error.
|
|
14
|
+
*
|
|
15
|
+
* @param error - The error to mark. Non-objects are returned untouched.
|
|
16
|
+
* @param retryable - `true` if retrying may succeed.
|
|
17
|
+
* @returns The same error instance, for chaining.
|
|
18
|
+
*/
|
|
19
|
+
declare function stampRetryable<T>(error: T, retryable: boolean): T;
|
|
20
|
+
/**
|
|
21
|
+
* Read an error's retryability mark.
|
|
22
|
+
*
|
|
23
|
+
* @returns `true`/`false` when marked, `undefined` when unclassified —
|
|
24
|
+
* supply your own default, e.g. `getRetryable(error) ?? true`.
|
|
25
|
+
*/
|
|
26
|
+
declare function getRetryable(error: unknown): boolean | undefined;
|
|
9
27
|
declare const LangChainError_base: ErrorConstructor & {
|
|
10
28
|
isInstance: <T extends abstract new (...args: any[]) => any>(this: T, obj: unknown) => obj is InstanceType<T>;
|
|
11
29
|
};
|
|
@@ -145,5 +163,5 @@ declare class ContextOverflowError extends ContextOverflowError_base {
|
|
|
145
163
|
static fromError(obj: Error): ContextOverflowError;
|
|
146
164
|
}
|
|
147
165
|
//#endregion
|
|
148
|
-
export { ContextOverflowError, LangChainError, LangChainErrorCodes, ModelAbortError, addLangChainErrorFields, ns };
|
|
166
|
+
export { ContextOverflowError, LangChainError, LangChainErrorCodes, ModelAbortError, addLangChainErrorFields, getRetryable, ns, stampRetryable };
|
|
149
167
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/errors/index.ts"],"mappings":";;;KAKY;;iBAYI,wBACd,YACA,eAAe;;cAQJ,IAAA;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/errors/index.ts"],"mappings":";;;KAKY;;iBAYI,wBACd,YACA,eAAe;;cAQJ,IAAA;;;;;;;;;;;iBAeG,eAAe,GAAG,OAAO,GAAG,qBAAqB;;;;;;;iBAqBjD,aAAa;;;;;;;;;;;;;;;;;;;;;;cA2BhB,uBAAuB;WACzB;EAET,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCD,wBAAwB;WAC1B;;;;;WAMA,gBAAgB;;;;;;;EAQzB,YAAY,iBAAiB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAwClC,6BAA6B;WAI/B;;;;;;;EAQT,QAAQ;EAER,YAAY;;;;;;;;;;;;;;;;;;;;SAyBL,UAAU,KAAK,QAAQ"}
|
package/dist/errors/index.d.ts
CHANGED
|
@@ -6,6 +6,24 @@ type LangChainErrorCodes = "CONTEXT_OVERFLOW" | "INVALID_PROMPT_INPUT" | "INVALI
|
|
|
6
6
|
declare function addLangChainErrorFields(error: any, lc_error_code: LangChainErrorCodes): any;
|
|
7
7
|
/** The error namespace for all LangChain errors */
|
|
8
8
|
declare const ns: Namespace;
|
|
9
|
+
/**
|
|
10
|
+
* Mark an error as safe or unsafe to retry.
|
|
11
|
+
*
|
|
12
|
+
* Sets a non-enumerable symbol on the error itself, leaving its class and
|
|
13
|
+
* shape untouched, so it is safe to apply to a provider SDK's own error.
|
|
14
|
+
*
|
|
15
|
+
* @param error - The error to mark. Non-objects are returned untouched.
|
|
16
|
+
* @param retryable - `true` if retrying may succeed.
|
|
17
|
+
* @returns The same error instance, for chaining.
|
|
18
|
+
*/
|
|
19
|
+
declare function stampRetryable<T>(error: T, retryable: boolean): T;
|
|
20
|
+
/**
|
|
21
|
+
* Read an error's retryability mark.
|
|
22
|
+
*
|
|
23
|
+
* @returns `true`/`false` when marked, `undefined` when unclassified —
|
|
24
|
+
* supply your own default, e.g. `getRetryable(error) ?? true`.
|
|
25
|
+
*/
|
|
26
|
+
declare function getRetryable(error: unknown): boolean | undefined;
|
|
9
27
|
declare const LangChainError_base: ErrorConstructor & {
|
|
10
28
|
isInstance: <T extends abstract new (...args: any[]) => any>(this: T, obj: unknown) => obj is InstanceType<T>;
|
|
11
29
|
};
|
|
@@ -145,5 +163,5 @@ declare class ContextOverflowError extends ContextOverflowError_base {
|
|
|
145
163
|
static fromError(obj: Error): ContextOverflowError;
|
|
146
164
|
}
|
|
147
165
|
//#endregion
|
|
148
|
-
export { ContextOverflowError, LangChainError, LangChainErrorCodes, ModelAbortError, addLangChainErrorFields, ns };
|
|
166
|
+
export { ContextOverflowError, LangChainError, LangChainErrorCodes, ModelAbortError, addLangChainErrorFields, getRetryable, ns, stampRetryable };
|
|
149
167
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/errors/index.ts"],"mappings":";;;KAKY;;iBAYI,wBACd,YACA,eAAe;;cAQJ,IAAA;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/errors/index.ts"],"mappings":";;;KAKY;;iBAYI,wBACd,YACA,eAAe;;cAQJ,IAAA;;;;;;;;;;;iBAeG,eAAe,GAAG,OAAO,GAAG,qBAAqB;;;;;;;iBAqBjD,aAAa;;;;;;;;;;;;;;;;;;;;;;cA2BhB,uBAAuB;WACzB;EAET,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCD,wBAAwB;WAC1B;;;;;WAMA,gBAAgB;;;;;;;EAQzB,YAAY,iBAAiB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAwClC,6BAA6B;WAI/B;;;;;;;EAQT,QAAQ;EAER,YAAY;;;;;;;;;;;;;;;;;;;;SAyBL,UAAU,KAAK,QAAQ"}
|
package/dist/errors/index.js
CHANGED
|
@@ -6,7 +6,9 @@ var errors_exports = /* @__PURE__ */ __exportAll({
|
|
|
6
6
|
LangChainError: () => LangChainError,
|
|
7
7
|
ModelAbortError: () => ModelAbortError,
|
|
8
8
|
addLangChainErrorFields: () => addLangChainErrorFields,
|
|
9
|
-
|
|
9
|
+
getRetryable: () => getRetryable,
|
|
10
|
+
ns: () => ns,
|
|
11
|
+
stampRetryable: () => stampRetryable
|
|
10
12
|
});
|
|
11
13
|
/** @deprecated Subclass LangChainError instead */
|
|
12
14
|
function addLangChainErrorFields(error, lc_error_code) {
|
|
@@ -16,6 +18,38 @@ function addLangChainErrorFields(error, lc_error_code) {
|
|
|
16
18
|
}
|
|
17
19
|
/** The error namespace for all LangChain errors */
|
|
18
20
|
const ns = ns$1.sub("error");
|
|
21
|
+
/** Registered globally so duplicate copies of core in one dependency tree agree. */
|
|
22
|
+
const retryableSymbol = Symbol.for("langchain.errors.retryable");
|
|
23
|
+
/**
|
|
24
|
+
* Mark an error as safe or unsafe to retry.
|
|
25
|
+
*
|
|
26
|
+
* Sets a non-enumerable symbol on the error itself, leaving its class and
|
|
27
|
+
* shape untouched, so it is safe to apply to a provider SDK's own error.
|
|
28
|
+
*
|
|
29
|
+
* @param error - The error to mark. Non-objects are returned untouched.
|
|
30
|
+
* @param retryable - `true` if retrying may succeed.
|
|
31
|
+
* @returns The same error instance, for chaining.
|
|
32
|
+
*/
|
|
33
|
+
function stampRetryable(error, retryable) {
|
|
34
|
+
if (typeof error !== "object" || error === null) return error;
|
|
35
|
+
try {
|
|
36
|
+
Object.defineProperty(error, retryableSymbol, {
|
|
37
|
+
value: retryable,
|
|
38
|
+
configurable: true
|
|
39
|
+
});
|
|
40
|
+
} catch {}
|
|
41
|
+
return error;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Read an error's retryability mark.
|
|
45
|
+
*
|
|
46
|
+
* @returns `true`/`false` when marked, `undefined` when unclassified —
|
|
47
|
+
* supply your own default, e.g. `getRetryable(error) ?? true`.
|
|
48
|
+
*/
|
|
49
|
+
function getRetryable(error) {
|
|
50
|
+
if (typeof error !== "object" || error === null) return;
|
|
51
|
+
return Object.getOwnPropertyDescriptor(error, retryableSymbol)?.value;
|
|
52
|
+
}
|
|
19
53
|
/**
|
|
20
54
|
* Base error class for all LangChain errors.
|
|
21
55
|
*
|
|
@@ -86,6 +120,7 @@ var ModelAbortError = class extends ns.brand(LangChainError, "model-abort") {
|
|
|
86
120
|
constructor(message, partialOutput) {
|
|
87
121
|
super(message);
|
|
88
122
|
this.partialOutput = partialOutput;
|
|
123
|
+
stampRetryable(this, false);
|
|
89
124
|
}
|
|
90
125
|
};
|
|
91
126
|
/**
|
|
@@ -131,6 +166,7 @@ var ContextOverflowError = class ContextOverflowError extends ns.brand(LangChain
|
|
|
131
166
|
cause;
|
|
132
167
|
constructor(message) {
|
|
133
168
|
super(message ?? "Input exceeded the model's context window.");
|
|
169
|
+
stampRetryable(this, false);
|
|
134
170
|
}
|
|
135
171
|
/**
|
|
136
172
|
* Creates a new {@link ContextOverflowError} instance from an existing error.
|
|
@@ -158,6 +194,6 @@ var ContextOverflowError = class ContextOverflowError extends ns.brand(LangChain
|
|
|
158
194
|
}
|
|
159
195
|
};
|
|
160
196
|
//#endregion
|
|
161
|
-
export { ContextOverflowError, LangChainError, ModelAbortError, addLangChainErrorFields, errors_exports, ns };
|
|
197
|
+
export { ContextOverflowError, LangChainError, ModelAbortError, addLangChainErrorFields, errors_exports, getRetryable, ns, stampRetryable };
|
|
162
198
|
|
|
163
199
|
//# sourceMappingURL=index.js.map
|
package/dist/errors/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["baseNs"],"sources":["../../src/errors/index.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AIMessageChunk } from \"../messages/ai.js\";\nimport { ns as baseNs } from \"../utils/namespace.js\";\n\nexport type LangChainErrorCodes =\n | \"CONTEXT_OVERFLOW\"\n | \"INVALID_PROMPT_INPUT\"\n | \"INVALID_TOOL_RESULTS\"\n | \"MESSAGE_COERCION_FAILURE\"\n | \"MODEL_AUTHENTICATION\"\n | \"MODEL_NOT_FOUND\"\n | \"MODEL_RATE_LIMIT\"\n | \"OUTPUT_PARSING_FAILURE\"\n | \"MODEL_ABORTED\";\n\n/** @deprecated Subclass LangChainError instead */\nexport function addLangChainErrorFields(\n error: any,\n lc_error_code: LangChainErrorCodes\n) {\n (error as any).lc_error_code = lc_error_code;\n error.message = `${error.message}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\\n`;\n return error;\n}\n\n/** The error namespace for all LangChain errors */\nexport const ns = baseNs.sub(\"error\");\n\n/**\n * Base error class for all LangChain errors.\n *\n * All LangChain error classes should extend this class (directly or\n * indirectly). Use `LangChainError.isInstance(obj)` to check if an\n * object is any LangChain error.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(\"hello\");\n * } catch (error) {\n * if (LangChainError.isInstance(error)) {\n * console.log(\"Got a LangChain error:\", error.message);\n * }\n * }\n * ```\n */\nexport class LangChainError extends ns.brand(Error) {\n readonly name: string = \"LangChainError\";\n\n constructor(message?: string) {\n super(message);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error class representing an aborted model operation in LangChain.\n *\n * This error is thrown when a model operation (such as invocation, streaming, or batching)\n * is cancelled before it completes, commonly due to a user-initiated abort signal\n * (e.g., via an AbortController) or an upstream cancellation event.\n *\n * The ModelAbortError provides access to any partial output the model may have produced\n * before the operation was interrupted, which can be useful for resuming work, debugging,\n * or presenting incomplete results to users.\n *\n * @remarks\n * - The `partialOutput` field includes message content that was generated prior to the abort,\n * such as a partial AIMessageChunk.\n * - This error extends the {@link LangChainError} base class with the marker `\"model-abort\"`.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input, { signal: abortController.signal });\n * } catch (err) {\n * if (ModelAbortError.isInstance(err)) {\n * // Handle user cancellation, check err.partialOutput if needed\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ModelAbortError extends ns.brand(LangChainError, \"model-abort\") {\n readonly name = \"ModelAbortError\";\n\n /**\n * The partial message output that was produced before the operation was aborted.\n * This is typically an AIMessageChunk, or could be undefined if no output was available.\n */\n readonly partialOutput?: AIMessageChunk;\n\n /**\n * Constructs a new ModelAbortError instance.\n *\n * @param message - A human-readable message describing the abort event.\n * @param partialOutput - Any partial model output generated before the abort (optional).\n */\n constructor(message: string, partialOutput?: AIMessageChunk) {\n super(message);\n this.partialOutput = partialOutput;\n }\n}\n\n/**\n * Error class representing a context window overflow in a language model operation.\n *\n * This error is thrown when the combined input to a language model (such as prompt tokens,\n * historical messages, and/or instructions) exceeds the maximum context window or token limit\n * that the model can process in a single request. Most models have defined upper limits for the number of\n * tokens or characters allowed in a context, and exceeding this limit will prevent\n * the operation from proceeding.\n *\n * The {@link ContextOverflowError} extends the {@link LangChainError} base class with\n * the marker `\"context-overflow\"`.\n *\n * @remarks\n * - Use this error to programmatically identify cases where a user request, prompt, or input\n * sequence is too long to be handled by the target model.\n * - Model providers and framework integrations should throw this error if they detect\n * a request cannot be processed due to its size.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(veryLongInput);\n * } catch (err) {\n * if (ContextOverflowError.isInstance(err)) {\n * // Handle overflow, e.g., prompt user to shorten input or truncate text\n * console.warn(\"Model context overflow:\", err.message);\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ContextOverflowError extends ns.brand(\n LangChainError,\n \"context-overflow\"\n) {\n readonly name = \"ContextOverflowError\";\n\n /**\n * The underlying error that caused this {@link ContextOverflowError}, if any.\n *\n * This property is optionally set when wrapping a lower-level error using {@link ContextOverflowError.fromError}.\n * It allows error handlers to access or inspect the original error that led to the context overflow.\n */\n cause?: Error;\n\n constructor(message?: string) {\n super(message ?? \"Input exceeded the model's context window.\");\n }\n\n /**\n * Creates a new {@link ContextOverflowError} instance from an existing error.\n *\n * This static utility copies the message from the provided error and\n * attaches the original error as the {@link ContextOverflowError.cause} property,\n * enabling error handlers to inspect or propagate the original failure.\n *\n * @param obj - The original error object causing the context overflow.\n * @returns A new {@link ContextOverflowError} instance with the original error set as its cause.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input);\n * } catch (err) {\n * throw ContextOverflowError.fromError(err);\n * }\n * ```\n */\n static fromError(obj: Error): ContextOverflowError {\n const error = new ContextOverflowError(obj.message);\n error.cause = obj;\n return error;\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["baseNs"],"sources":["../../src/errors/index.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AIMessageChunk } from \"../messages/ai.js\";\nimport { ns as baseNs } from \"../utils/namespace.js\";\n\nexport type LangChainErrorCodes =\n | \"CONTEXT_OVERFLOW\"\n | \"INVALID_PROMPT_INPUT\"\n | \"INVALID_TOOL_RESULTS\"\n | \"MESSAGE_COERCION_FAILURE\"\n | \"MODEL_AUTHENTICATION\"\n | \"MODEL_NOT_FOUND\"\n | \"MODEL_RATE_LIMIT\"\n | \"OUTPUT_PARSING_FAILURE\"\n | \"MODEL_ABORTED\";\n\n/** @deprecated Subclass LangChainError instead */\nexport function addLangChainErrorFields(\n error: any,\n lc_error_code: LangChainErrorCodes\n) {\n (error as any).lc_error_code = lc_error_code;\n error.message = `${error.message}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\\n`;\n return error;\n}\n\n/** The error namespace for all LangChain errors */\nexport const ns = baseNs.sub(\"error\");\n\n/** Registered globally so duplicate copies of core in one dependency tree agree. */\nconst retryableSymbol = Symbol.for(\"langchain.errors.retryable\");\n\n/**\n * Mark an error as safe or unsafe to retry.\n *\n * Sets a non-enumerable symbol on the error itself, leaving its class and\n * shape untouched, so it is safe to apply to a provider SDK's own error.\n *\n * @param error - The error to mark. Non-objects are returned untouched.\n * @param retryable - `true` if retrying may succeed.\n * @returns The same error instance, for chaining.\n */\nexport function stampRetryable<T>(error: T, retryable: boolean): T {\n if (typeof error !== \"object\" || error === null) {\n return error;\n }\n try {\n Object.defineProperty(error, retryableSymbol, {\n value: retryable,\n configurable: true,\n });\n } catch {\n // Frozen or sealed error object; leave it unmarked rather than throwing.\n }\n return error;\n}\n\n/**\n * Read an error's retryability mark.\n *\n * @returns `true`/`false` when marked, `undefined` when unclassified —\n * supply your own default, e.g. `getRetryable(error) ?? true`.\n */\nexport function getRetryable(error: unknown): boolean | undefined {\n if (typeof error !== \"object\" || error === null) {\n return undefined;\n }\n return Object.getOwnPropertyDescriptor(error, retryableSymbol)?.value as\n | boolean\n | undefined;\n}\n\n/**\n * Base error class for all LangChain errors.\n *\n * All LangChain error classes should extend this class (directly or\n * indirectly). Use `LangChainError.isInstance(obj)` to check if an\n * object is any LangChain error.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(\"hello\");\n * } catch (error) {\n * if (LangChainError.isInstance(error)) {\n * console.log(\"Got a LangChain error:\", error.message);\n * }\n * }\n * ```\n */\nexport class LangChainError extends ns.brand(Error) {\n readonly name: string = \"LangChainError\";\n\n constructor(message?: string) {\n super(message);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error class representing an aborted model operation in LangChain.\n *\n * This error is thrown when a model operation (such as invocation, streaming, or batching)\n * is cancelled before it completes, commonly due to a user-initiated abort signal\n * (e.g., via an AbortController) or an upstream cancellation event.\n *\n * The ModelAbortError provides access to any partial output the model may have produced\n * before the operation was interrupted, which can be useful for resuming work, debugging,\n * or presenting incomplete results to users.\n *\n * @remarks\n * - The `partialOutput` field includes message content that was generated prior to the abort,\n * such as a partial AIMessageChunk.\n * - This error extends the {@link LangChainError} base class with the marker `\"model-abort\"`.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input, { signal: abortController.signal });\n * } catch (err) {\n * if (ModelAbortError.isInstance(err)) {\n * // Handle user cancellation, check err.partialOutput if needed\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ModelAbortError extends ns.brand(LangChainError, \"model-abort\") {\n readonly name = \"ModelAbortError\";\n\n /**\n * The partial message output that was produced before the operation was aborted.\n * This is typically an AIMessageChunk, or could be undefined if no output was available.\n */\n readonly partialOutput?: AIMessageChunk;\n\n /**\n * Constructs a new ModelAbortError instance.\n *\n * @param message - A human-readable message describing the abort event.\n * @param partialOutput - Any partial model output generated before the abort (optional).\n */\n constructor(message: string, partialOutput?: AIMessageChunk) {\n super(message);\n this.partialOutput = partialOutput;\n // Retrying would mean ignoring the caller's explicit abort signal.\n stampRetryable(this, false);\n }\n}\n\n/**\n * Error class representing a context window overflow in a language model operation.\n *\n * This error is thrown when the combined input to a language model (such as prompt tokens,\n * historical messages, and/or instructions) exceeds the maximum context window or token limit\n * that the model can process in a single request. Most models have defined upper limits for the number of\n * tokens or characters allowed in a context, and exceeding this limit will prevent\n * the operation from proceeding.\n *\n * The {@link ContextOverflowError} extends the {@link LangChainError} base class with\n * the marker `\"context-overflow\"`.\n *\n * @remarks\n * - Use this error to programmatically identify cases where a user request, prompt, or input\n * sequence is too long to be handled by the target model.\n * - Model providers and framework integrations should throw this error if they detect\n * a request cannot be processed due to its size.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(veryLongInput);\n * } catch (err) {\n * if (ContextOverflowError.isInstance(err)) {\n * // Handle overflow, e.g., prompt user to shorten input or truncate text\n * console.warn(\"Model context overflow:\", err.message);\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ContextOverflowError extends ns.brand(\n LangChainError,\n \"context-overflow\"\n) {\n readonly name = \"ContextOverflowError\";\n\n /**\n * The underlying error that caused this {@link ContextOverflowError}, if any.\n *\n * This property is optionally set when wrapping a lower-level error using {@link ContextOverflowError.fromError}.\n * It allows error handlers to access or inspect the original error that led to the context overflow.\n */\n cause?: Error;\n\n constructor(message?: string) {\n super(message ?? \"Input exceeded the model's context window.\");\n // The same oversized input fails identically; it needs trimming, not another attempt.\n stampRetryable(this, false);\n }\n\n /**\n * Creates a new {@link ContextOverflowError} instance from an existing error.\n *\n * This static utility copies the message from the provided error and\n * attaches the original error as the {@link ContextOverflowError.cause} property,\n * enabling error handlers to inspect or propagate the original failure.\n *\n * @param obj - The original error object causing the context overflow.\n * @returns A new {@link ContextOverflowError} instance with the original error set as its cause.\n *\n * @example\n * ```typescript\n * try {\n * await model.invoke(input);\n * } catch (err) {\n * throw ContextOverflowError.fromError(err);\n * }\n * ```\n */\n static fromError(obj: Error): ContextOverflowError {\n const error = new ContextOverflowError(obj.message);\n error.cause = obj;\n return error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,SAAgB,wBACd,OACA,eACA;CACA,MAAe,gBAAgB;CAC/B,MAAM,UAAU,GAAG,MAAM,QAAQ,sFAAsF,cAAc;CACrI,OAAO;AACT;;AAGA,MAAa,KAAKA,KAAO,IAAI,OAAO;;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
this.callbacks = params.callbacks;
|
|
140
140
|
this.tags = params.tags ?? [];
|
|
141
141
|
this.metadata = params.metadata ?? {};
|
|
142
|
-
this._addVersion("@langchain/core", "1.2.
|
|
142
|
+
this._addVersion("@langchain/core", "1.2.8");
|
|
143
143
|
}
|
|
144
144
|
_addVersion(pkg, version) {
|
|
145
145
|
const existing = this.metadata?.versions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["encodingForModel","Runnable","InMemoryCache","AsyncCaller","StringPromptValue","ChatPromptValue","coerceMessageLikeToMessage"],"sources":["../../src/language_models/base.ts"],"sourcesContent":["import type { Tiktoken, TiktokenModel } from \"js-tiktoken/lite\";\nimport type { ZodV3Like, ZodV4Like } from \"../utils/types/zod.js\";\n\nimport { type BaseCache, InMemoryCache } from \"../caches/index.js\";\nimport {\n type BasePromptValueInterface,\n StringPromptValue,\n ChatPromptValue,\n} from \"../prompt_values.js\";\nimport {\n type BaseMessage,\n type BaseMessageLike,\n type MessageContent,\n} from \"../messages/base.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { type LLMResult } from \"../outputs.js\";\nimport { CallbackManager, Callbacks } from \"../callbacks/manager.js\";\nimport { AsyncCaller, AsyncCallerParams } from \"../utils/async_caller.js\";\nimport { encodingForModel } from \"../utils/tiktoken.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport {\n InferInteropZodOutput,\n InteropZodObject,\n InteropZodType,\n} from \"../utils/types/zod.js\";\nimport { ModelProfile } from \"./profile.js\";\nimport { type SerializableSchema } from \"../utils/standard_schema.js\";\n\n// https://www.npmjs.com/package/js-tiktoken\n\nexport const getModelNameForTiktoken = (modelName: string): TiktokenModel => {\n if (modelName.startsWith(\"gpt-5\")) {\n return \"gpt-5\" as TiktokenModel;\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-16k\")) {\n return \"gpt-3.5-turbo-16k\";\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-\")) {\n return \"gpt-3.5-turbo\";\n }\n\n if (modelName.startsWith(\"gpt-4-32k\")) {\n return \"gpt-4-32k\";\n }\n\n if (modelName.startsWith(\"gpt-4-\")) {\n return \"gpt-4\";\n }\n\n if (modelName.startsWith(\"gpt-4o\")) {\n return \"gpt-4o\";\n }\n\n return modelName as TiktokenModel;\n};\n\nexport const getEmbeddingContextSize = (modelName?: string): number => {\n switch (modelName) {\n case \"text-embedding-ada-002\":\n return 8191;\n default:\n return 2046;\n }\n};\n\n/**\n * Get the context window size (max input tokens) for a given model.\n *\n * Context window sizes are sourced from official model documentation:\n * - OpenAI: https://platform.openai.com/docs/models\n * - Anthropic: https://docs.anthropic.com/claude/docs/models-overview\n * - Google: https://ai.google.dev/gemini/docs/models/gemini\n *\n * @param modelName - The name of the model\n * @returns The context window size in tokens\n */\nexport const getModelContextSize = (modelName: string): number => {\n const normalizedName = getModelNameForTiktoken(modelName) as string;\n\n switch (normalizedName) {\n // GPT-5 series\n case \"gpt-5\":\n case \"gpt-5-turbo\":\n case \"gpt-5-turbo-preview\":\n return 400000;\n\n // GPT-4o series\n case \"gpt-4o\":\n case \"gpt-4o-mini\":\n case \"gpt-4o-2024-05-13\":\n case \"gpt-4o-2024-08-06\":\n return 128000;\n\n // GPT-4 Turbo series\n case \"gpt-4-turbo\":\n case \"gpt-4-turbo-preview\":\n case \"gpt-4-turbo-2024-04-09\":\n case \"gpt-4-0125-preview\":\n case \"gpt-4-1106-preview\":\n return 128000;\n\n // GPT-4 series\n case \"gpt-4-32k\":\n case \"gpt-4-32k-0314\":\n case \"gpt-4-32k-0613\":\n return 32768;\n case \"gpt-4\":\n case \"gpt-4-0314\":\n case \"gpt-4-0613\":\n return 8192;\n\n // GPT-3.5 Turbo series\n case \"gpt-3.5-turbo-16k\":\n case \"gpt-3.5-turbo-16k-0613\":\n return 16384;\n case \"gpt-3.5-turbo\":\n case \"gpt-3.5-turbo-0301\":\n case \"gpt-3.5-turbo-0613\":\n case \"gpt-3.5-turbo-1106\":\n case \"gpt-3.5-turbo-0125\":\n return 4096;\n\n // Legacy GPT-3 models\n case \"text-davinci-003\":\n case \"text-davinci-002\":\n return 4097;\n case \"text-davinci-001\":\n return 2049;\n case \"text-curie-001\":\n case \"text-babbage-001\":\n case \"text-ada-001\":\n return 2048;\n\n // Code models\n case \"code-davinci-002\":\n case \"code-davinci-001\":\n return 8000;\n case \"code-cushman-001\":\n return 2048;\n\n // Claude models (Anthropic)\n case \"claude-3-5-sonnet-20241022\":\n case \"claude-3-5-sonnet-20240620\":\n case \"claude-3-opus-20240229\":\n case \"claude-3-sonnet-20240229\":\n case \"claude-3-haiku-20240307\":\n case \"claude-2.1\":\n return 200000;\n case \"claude-2.0\":\n case \"claude-instant-1.2\":\n return 100000;\n\n // Gemini models (Google)\n case \"gemini-1.5-pro\":\n case \"gemini-1.5-pro-latest\":\n case \"gemini-1.5-flash\":\n case \"gemini-1.5-flash-latest\":\n return 1000000; // 1M tokens\n case \"gemini-pro\":\n case \"gemini-pro-vision\":\n return 32768;\n\n default:\n return 4097;\n }\n};\n\n/**\n * Whether or not the input matches the OpenAI tool definition.\n * @param {unknown} tool The input to check.\n * @returns {boolean} Whether the input is an OpenAI tool definition.\n */\nexport function isOpenAITool(tool: unknown): tool is ToolDefinition {\n if (typeof tool !== \"object\" || !tool) return false;\n if (\n \"type\" in tool &&\n tool.type === \"function\" &&\n \"function\" in tool &&\n typeof tool.function === \"object\" &&\n tool.function &&\n \"name\" in tool.function &&\n \"parameters\" in tool.function\n ) {\n return true;\n }\n return false;\n}\n\ninterface CalculateMaxTokenProps {\n prompt: string;\n modelName: TiktokenModel;\n}\n\nexport const calculateMaxTokens = async ({\n prompt,\n modelName,\n}: CalculateMaxTokenProps) => {\n let numTokens;\n\n try {\n numTokens = (\n await encodingForModel(getModelNameForTiktoken(modelName))\n ).encode(prompt).length;\n } catch {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\"\n );\n\n // fallback to approximate calculation if tiktoken is not available\n // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them#\n numTokens = Math.ceil(prompt.length / 4);\n }\n\n const maxTokens = getModelContextSize(modelName);\n return maxTokens - numTokens;\n};\n\nconst getVerbosity = () => false;\n\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n} & Record<string, any>;\n\nexport interface BaseLangChainParams {\n verbose?: boolean;\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Base class for language models, chains, tools.\n */\nexport abstract class BaseLangChain<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Runnable<RunInput, RunOutput, CallOptions>\n implements BaseLangChainParams\n{\n /**\n * Whether to print out response text.\n */\n verbose: boolean;\n\n callbacks?: Callbacks;\n\n tags?: string[];\n\n metadata?: Record<string, unknown>;\n\n get lc_attributes(): { [key: string]: undefined } | undefined {\n return {\n callbacks: undefined,\n verbose: undefined,\n };\n }\n\n constructor(params: BaseLangChainParams) {\n super(params);\n this.verbose = params.verbose ?? getVerbosity();\n this.callbacks = params.callbacks;\n this.tags = params.tags ?? [];\n this.metadata = params.metadata ?? {};\n this._addVersion(\"@langchain/core\", __PKG_VERSION__);\n }\n\n protected _addVersion(pkg: string, version: string) {\n const existing = this.metadata?.versions;\n this.metadata = {\n ...this.metadata,\n versions: {\n ...(typeof existing === \"object\" && existing !== null ? existing : {}),\n [pkg]: version,\n },\n };\n }\n}\n\n/**\n * Base interface for language model parameters.\n * A subclass of {@link BaseLanguageModel} should have a constructor that\n * takes in a parameter that extends this interface.\n */\nexport interface BaseLanguageModelParams\n extends AsyncCallerParams, BaseLangChainParams {\n /**\n * @deprecated Use `callbacks` instead\n */\n callbackManager?: CallbackManager;\n\n cache?: BaseCache | boolean;\n}\n\nexport interface BaseLanguageModelTracingCallOptions {\n /**\n * Describes the format of structured outputs.\n * This should be provided if an output is considered to be structured\n */\n ls_structured_output_format?: {\n /**\n * An object containing the method used for structured output (e.g., \"jsonMode\").\n */\n kwargs: { method: string };\n /**\n * The JSON schema describing the expected output structure.\n */\n schema?: JSONSchema;\n };\n}\n\nexport interface BaseLanguageModelCallOptions\n extends RunnableConfig, BaseLanguageModelTracingCallOptions {\n /**\n * Stop tokens to use for this call.\n * If not provided, the default stop tokens for the model will be used.\n */\n stop?: string[];\n}\n\nexport interface FunctionDefinition {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](https://platform.openai.com/docs/guides/gpt/function-calling) for\n * examples, and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * To describe a function that accepts no parameters, provide the value\n * `{\"type\": \"object\", \"properties\": {}}`.\n */\n parameters: Record<string, unknown> | JSONSchema;\n\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: FunctionDefinition;\n}\n\nexport type FunctionCallOption = {\n name: string;\n};\n\nexport interface BaseFunctionCallOptions extends BaseLanguageModelCallOptions {\n function_call?: FunctionCallOption;\n functions?: FunctionDefinition[];\n}\n\nexport type BaseLanguageModelInput =\n | BasePromptValueInterface\n | string\n | BaseMessageLike[];\n\nexport type StructuredOutputType = InferInteropZodOutput<InteropZodObject>;\n\nexport type StructuredOutputMethodOptions<IncludeRaw extends boolean = false> =\n {\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\" | \"jsonSchema\" | string;\n includeRaw?: IncludeRaw;\n /** Whether to use strict mode. Currently only supported by OpenAI models. */\n strict?: boolean;\n };\n\n/** @deprecated Use StructuredOutputMethodOptions instead */\nexport type StructuredOutputMethodParams<\n RunOutput,\n IncludeRaw extends boolean = false,\n> = {\n /** @deprecated Pass schema in as the first argument */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n schema: InteropZodType<RunOutput> | Record<string, any>;\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\";\n includeRaw?: IncludeRaw;\n};\n\nexport interface BaseLanguageModelInterface<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n> extends RunnableInterface<BaseLanguageModelInput, RunOutput, CallOptions> {\n get callKeys(): string[];\n\n generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | Partial<CallOptions>,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n _modelType(): string;\n\n _llmType(): string;\n\n getNumTokens(content: MessageContent): Promise<number>;\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any>;\n\n serialize(): SerializedLLM;\n}\n\nexport type LanguageModelOutput = BaseMessage | string;\n\nexport type LanguageModelLike = RunnableInterface<\n BaseLanguageModelInput,\n LanguageModelOutput\n>;\n\n/**\n * Base class for language models.\n */\nexport abstract class BaseLanguageModel<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n>\n extends BaseLangChain<BaseLanguageModelInput, RunOutput, CallOptions>\n implements\n BaseLanguageModelParams,\n BaseLanguageModelInterface<RunOutput, CallOptions>\n{\n /**\n * Keys that the language model accepts as call options.\n */\n get callKeys(): string[] {\n return [\"stop\", \"timeout\", \"signal\", \"tags\", \"metadata\", \"callbacks\"];\n }\n\n /**\n * The async caller should be used by subclasses to make any async calls,\n * which will thus benefit from the concurrency and retry logic.\n */\n caller: AsyncCaller;\n\n cache?: BaseCache;\n\n constructor({\n callbacks,\n callbackManager,\n ...params\n }: BaseLanguageModelParams) {\n const { cache, ...rest } = params;\n super({\n callbacks: callbacks ?? callbackManager,\n ...rest,\n });\n if (typeof cache === \"object\") {\n this.cache = cache;\n } else if (cache) {\n this.cache = InMemoryCache.global();\n } else {\n this.cache = undefined;\n }\n this.caller = new AsyncCaller(params ?? {});\n }\n\n abstract generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | CallOptions,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n abstract _modelType(): string;\n\n abstract _llmType(): string;\n\n private _encoding?: Tiktoken;\n\n /**\n * Get the number of tokens in the content.\n * @param content The content to get the number of tokens for.\n * @returns The number of tokens in the content.\n */\n async getNumTokens(content: MessageContent) {\n // Extract text content from MessageContent\n let textContent: string;\n if (typeof content === \"string\") {\n textContent = content;\n } else {\n /**\n * Content is an array of ContentBlock\n *\n * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content.\n * We need to find a better way to do this.\n * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116\n */\n textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n }\n\n // fallback to approximate calculation if tiktoken is not available\n let numTokens = Math.ceil(textContent.length / 4);\n\n if (!this._encoding) {\n try {\n this._encoding = await encodingForModel(\n \"modelName\" in this\n ? getModelNameForTiktoken(this.modelName as string)\n : \"gpt2\"\n );\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n if (this._encoding) {\n try {\n numTokens = this._encoding.encode(textContent).length;\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n return numTokens;\n }\n\n protected static _convertInputToPromptValue(\n input: BaseLanguageModelInput\n ): BasePromptValueInterface {\n if (typeof input === \"string\") {\n return new StringPromptValue(input);\n } else if (Array.isArray(input)) {\n return new ChatPromptValue(input.map(coerceMessageLikeToMessage));\n } else {\n return input;\n }\n }\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any> {\n return {};\n }\n\n /**\n * Create a unique cache key for a specific call to a specific language model.\n * @param callOptions Call options for the model\n * @returns A unique cache key.\n */\n _getSerializedCacheKeyParametersForCall(\n // TODO: Fix when we remove the RunnableLambda backwards compatibility shim.\n {\n config,\n ...callOptions\n }: CallOptions & { config?: RunnableConfig }\n ): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const params: Record<string, any> = {\n ...this._identifyingParams(),\n ...callOptions,\n _type: this._llmType(),\n _model: this._modelType(),\n };\n const filteredEntries = Object.entries(params).filter(\n ([_, value]) => value !== undefined\n );\n const serializedEntries = filteredEntries\n .map(([key, value]) => `${key}:${JSON.stringify(value)}`)\n .sort()\n .join(\",\");\n return serializedEntries;\n }\n\n /**\n * @deprecated\n * Return a json-like object representing this LLM.\n */\n serialize(): SerializedLLM {\n return {\n ...this._identifyingParams(),\n _type: this._llmType(),\n _model: this._modelType(),\n };\n }\n\n /**\n * @deprecated\n * Load an LLM from a json-like object describing it.\n */\n static async deserialize(_data: SerializedLLM): Promise<BaseLanguageModel> {\n throw new Error(\"Use .toJSON() instead\");\n }\n\n /**\n * Return profiling information for the model.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return {};\n }\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Model wrapper that returns outputs formatted to match the given schema.\n *\n * @template {BaseLanguageModelInput} RunInput The input type for the Runnable, expected to be the same input for the LLM.\n * @template {Record<string, any>} RunOutput The output type for the Runnable, expected to be a Zod schema object for structured output validation.\n *\n * @param {InteropZodType<RunOutput>} schema The schema for the structured output. Either as a Zod schema or a valid JSON schema object.\n * If a Zod schema is passed, the returned attributes will be validated, whereas with JSON schema they will not be.\n * @param {string} name The name of the function to call.\n * @param {\"functionCalling\" | \"jsonMode\"} [method=functionCalling] The method to use for getting the structured output. Defaults to \"functionCalling\".\n * @param {boolean | undefined} [includeRaw=false] Whether to include the raw output in the result. Defaults to false.\n * @returns {Runnable<RunInput, RunOutput> | Runnable<RunInput, { raw: BaseMessage; parsed: RunOutput }>} A new runnable that calls the LLM with structured output.\n */\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | InteropZodType<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n {\n raw: BaseMessage;\n parsed: RunOutput;\n }\n >;\n\n /**\n * Filter out large/inappropriate fields from invocation params for tracing metadata.\n * Removes fields like tools, functions, messages, response_format that can be large.\n */\n protected _filterInvocationParamsForTracing(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n params: Record<string, any>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): Record<string, any> {\n const { tools, functions, messages, response_format, ...rest } = params;\n return rest;\n }\n}\n\n/**\n * Shared interface for token usage\n * return type from LLM calls.\n */\nexport interface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,MAAa,2BAA2B,cAAqC;CAC3E,IAAI,UAAU,WAAW,OAAO,GAC9B,OAAO;CAGT,IAAI,UAAU,WAAW,mBAAmB,GAC1C,OAAO;CAGT,IAAI,UAAU,WAAW,gBAAgB,GACvC,OAAO;CAGT,IAAI,UAAU,WAAW,WAAW,GAClC,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,GAC/B,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,GAC/B,OAAO;CAGT,OAAO;AACT;AAEA,MAAa,2BAA2B,cAA+B;CACrE,QAAQ,WAAR;EACE,KAAK,0BACH,OAAO;EAC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K,SAAS;GACrB,QAAQ,KAAK,WAAW;EAC1B;CACF;;;;;CAMA,aAAa,YAAY,OAAkD;EACzE,MAAM,IAAI,MAAM,uBAAuB;CACzC;;;;;;CAOA,IAAI,UAAwB;EAC1B,OAAO,CAAC;CACV;;;;;CAkGA,kCAEE,QAEqB;EACrB,MAAM,EAAE,OAAO,WAAW,UAAU,iBAAiB,GAAG,SAAS;EACjE,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"base.cjs","names":["encodingForModel","Runnable","InMemoryCache","AsyncCaller","StringPromptValue","ChatPromptValue","coerceMessageLikeToMessage"],"sources":["../../src/language_models/base.ts"],"sourcesContent":["import type { Tiktoken, TiktokenModel } from \"js-tiktoken/lite\";\nimport type { ZodV3Like, ZodV4Like } from \"../utils/types/zod.js\";\n\nimport { type BaseCache, InMemoryCache } from \"../caches/index.js\";\nimport {\n type BasePromptValueInterface,\n StringPromptValue,\n ChatPromptValue,\n} from \"../prompt_values.js\";\nimport {\n type BaseMessage,\n type BaseMessageLike,\n type MessageContent,\n} from \"../messages/base.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { type LLMResult } from \"../outputs.js\";\nimport { CallbackManager, Callbacks } from \"../callbacks/manager.js\";\nimport { AsyncCaller, AsyncCallerParams } from \"../utils/async_caller.js\";\nimport { encodingForModel } from \"../utils/tiktoken.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport {\n InferInteropZodOutput,\n InteropZodObject,\n InteropZodType,\n} from \"../utils/types/zod.js\";\nimport { ModelProfile } from \"./profile.js\";\nimport { type SerializableSchema } from \"../utils/standard_schema.js\";\n\n// https://www.npmjs.com/package/js-tiktoken\n\nexport const getModelNameForTiktoken = (modelName: string): TiktokenModel => {\n if (modelName.startsWith(\"gpt-5\")) {\n return \"gpt-5\" as TiktokenModel;\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-16k\")) {\n return \"gpt-3.5-turbo-16k\";\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-\")) {\n return \"gpt-3.5-turbo\";\n }\n\n if (modelName.startsWith(\"gpt-4-32k\")) {\n return \"gpt-4-32k\";\n }\n\n if (modelName.startsWith(\"gpt-4-\")) {\n return \"gpt-4\";\n }\n\n if (modelName.startsWith(\"gpt-4o\")) {\n return \"gpt-4o\";\n }\n\n return modelName as TiktokenModel;\n};\n\nexport const getEmbeddingContextSize = (modelName?: string): number => {\n switch (modelName) {\n case \"text-embedding-ada-002\":\n return 8191;\n default:\n return 2046;\n }\n};\n\n/**\n * Get the context window size (max input tokens) for a given model.\n *\n * Context window sizes are sourced from official model documentation:\n * - OpenAI: https://platform.openai.com/docs/models\n * - Anthropic: https://docs.anthropic.com/claude/docs/models-overview\n * - Google: https://ai.google.dev/gemini/docs/models/gemini\n *\n * @param modelName - The name of the model\n * @returns The context window size in tokens\n */\nexport const getModelContextSize = (modelName: string): number => {\n const normalizedName = getModelNameForTiktoken(modelName) as string;\n\n switch (normalizedName) {\n // GPT-5 series\n case \"gpt-5\":\n case \"gpt-5-turbo\":\n case \"gpt-5-turbo-preview\":\n return 400000;\n\n // GPT-4o series\n case \"gpt-4o\":\n case \"gpt-4o-mini\":\n case \"gpt-4o-2024-05-13\":\n case \"gpt-4o-2024-08-06\":\n return 128000;\n\n // GPT-4 Turbo series\n case \"gpt-4-turbo\":\n case \"gpt-4-turbo-preview\":\n case \"gpt-4-turbo-2024-04-09\":\n case \"gpt-4-0125-preview\":\n case \"gpt-4-1106-preview\":\n return 128000;\n\n // GPT-4 series\n case \"gpt-4-32k\":\n case \"gpt-4-32k-0314\":\n case \"gpt-4-32k-0613\":\n return 32768;\n case \"gpt-4\":\n case \"gpt-4-0314\":\n case \"gpt-4-0613\":\n return 8192;\n\n // GPT-3.5 Turbo series\n case \"gpt-3.5-turbo-16k\":\n case \"gpt-3.5-turbo-16k-0613\":\n return 16384;\n case \"gpt-3.5-turbo\":\n case \"gpt-3.5-turbo-0301\":\n case \"gpt-3.5-turbo-0613\":\n case \"gpt-3.5-turbo-1106\":\n case \"gpt-3.5-turbo-0125\":\n return 4096;\n\n // Legacy GPT-3 models\n case \"text-davinci-003\":\n case \"text-davinci-002\":\n return 4097;\n case \"text-davinci-001\":\n return 2049;\n case \"text-curie-001\":\n case \"text-babbage-001\":\n case \"text-ada-001\":\n return 2048;\n\n // Code models\n case \"code-davinci-002\":\n case \"code-davinci-001\":\n return 8000;\n case \"code-cushman-001\":\n return 2048;\n\n // Claude models (Anthropic)\n case \"claude-3-5-sonnet-20241022\":\n case \"claude-3-5-sonnet-20240620\":\n case \"claude-3-opus-20240229\":\n case \"claude-3-sonnet-20240229\":\n case \"claude-3-haiku-20240307\":\n case \"claude-2.1\":\n return 200000;\n case \"claude-2.0\":\n case \"claude-instant-1.2\":\n return 100000;\n\n // Gemini models (Google)\n case \"gemini-1.5-pro\":\n case \"gemini-1.5-pro-latest\":\n case \"gemini-1.5-flash\":\n case \"gemini-1.5-flash-latest\":\n return 1000000; // 1M tokens\n case \"gemini-pro\":\n case \"gemini-pro-vision\":\n return 32768;\n\n default:\n return 4097;\n }\n};\n\n/**\n * Whether or not the input matches the OpenAI tool definition.\n * @param {unknown} tool The input to check.\n * @returns {boolean} Whether the input is an OpenAI tool definition.\n */\nexport function isOpenAITool(tool: unknown): tool is ToolDefinition {\n if (typeof tool !== \"object\" || !tool) return false;\n if (\n \"type\" in tool &&\n tool.type === \"function\" &&\n \"function\" in tool &&\n typeof tool.function === \"object\" &&\n tool.function &&\n \"name\" in tool.function &&\n \"parameters\" in tool.function\n ) {\n return true;\n }\n return false;\n}\n\ninterface CalculateMaxTokenProps {\n prompt: string;\n modelName: TiktokenModel;\n}\n\nexport const calculateMaxTokens = async ({\n prompt,\n modelName,\n}: CalculateMaxTokenProps) => {\n let numTokens;\n\n try {\n numTokens = (\n await encodingForModel(getModelNameForTiktoken(modelName))\n ).encode(prompt).length;\n } catch {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\"\n );\n\n // fallback to approximate calculation if tiktoken is not available\n // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them#\n numTokens = Math.ceil(prompt.length / 4);\n }\n\n const maxTokens = getModelContextSize(modelName);\n return maxTokens - numTokens;\n};\n\nconst getVerbosity = () => false;\n\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n} & Record<string, any>;\n\nexport interface BaseLangChainParams {\n verbose?: boolean;\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Base class for language models, chains, tools.\n */\nexport abstract class BaseLangChain<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Runnable<RunInput, RunOutput, CallOptions>\n implements BaseLangChainParams\n{\n /**\n * Whether to print out response text.\n */\n verbose: boolean;\n\n callbacks?: Callbacks;\n\n tags?: string[];\n\n metadata?: Record<string, unknown>;\n\n get lc_attributes(): { [key: string]: undefined } | undefined {\n return {\n callbacks: undefined,\n verbose: undefined,\n };\n }\n\n constructor(params: BaseLangChainParams) {\n super(params);\n this.verbose = params.verbose ?? getVerbosity();\n this.callbacks = params.callbacks;\n this.tags = params.tags ?? [];\n this.metadata = params.metadata ?? {};\n this._addVersion(\"@langchain/core\", __PKG_VERSION__);\n }\n\n protected _addVersion(pkg: string, version: string) {\n const existing = this.metadata?.versions;\n this.metadata = {\n ...this.metadata,\n versions: {\n ...(typeof existing === \"object\" && existing !== null ? existing : {}),\n [pkg]: version,\n },\n };\n }\n}\n\n/**\n * Base interface for language model parameters.\n * A subclass of {@link BaseLanguageModel} should have a constructor that\n * takes in a parameter that extends this interface.\n */\nexport interface BaseLanguageModelParams\n extends AsyncCallerParams, BaseLangChainParams {\n /**\n * @deprecated Use `callbacks` instead\n */\n callbackManager?: CallbackManager;\n\n cache?: BaseCache | boolean;\n}\n\nexport interface BaseLanguageModelTracingCallOptions {\n /**\n * Describes the format of structured outputs.\n * This should be provided if an output is considered to be structured\n */\n ls_structured_output_format?: {\n /**\n * An object containing the method used for structured output (e.g., \"jsonMode\").\n */\n kwargs: { method: string };\n /**\n * The JSON schema describing the expected output structure.\n */\n schema?: JSONSchema;\n };\n}\n\nexport interface BaseLanguageModelCallOptions\n extends RunnableConfig, BaseLanguageModelTracingCallOptions {\n /**\n * Stop tokens to use for this call.\n * If not provided, the default stop tokens for the model will be used.\n */\n stop?: string[];\n /**\n * Overrides the model's configured `maxRetries` for this call only.\n */\n maxRetries?: number;\n}\n\nexport interface FunctionDefinition {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](https://platform.openai.com/docs/guides/gpt/function-calling) for\n * examples, and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * To describe a function that accepts no parameters, provide the value\n * `{\"type\": \"object\", \"properties\": {}}`.\n */\n parameters: Record<string, unknown> | JSONSchema;\n\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: FunctionDefinition;\n}\n\nexport type FunctionCallOption = {\n name: string;\n};\n\nexport interface BaseFunctionCallOptions extends BaseLanguageModelCallOptions {\n function_call?: FunctionCallOption;\n functions?: FunctionDefinition[];\n}\n\nexport type BaseLanguageModelInput =\n | BasePromptValueInterface\n | string\n | BaseMessageLike[];\n\nexport type StructuredOutputType = InferInteropZodOutput<InteropZodObject>;\n\nexport type StructuredOutputMethodOptions<IncludeRaw extends boolean = false> =\n {\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\" | \"jsonSchema\" | string;\n includeRaw?: IncludeRaw;\n /** Whether to use strict mode. Currently only supported by OpenAI models. */\n strict?: boolean;\n };\n\n/** @deprecated Use StructuredOutputMethodOptions instead */\nexport type StructuredOutputMethodParams<\n RunOutput,\n IncludeRaw extends boolean = false,\n> = {\n /** @deprecated Pass schema in as the first argument */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n schema: InteropZodType<RunOutput> | Record<string, any>;\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\";\n includeRaw?: IncludeRaw;\n};\n\nexport interface BaseLanguageModelInterface<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n> extends RunnableInterface<BaseLanguageModelInput, RunOutput, CallOptions> {\n get callKeys(): string[];\n\n generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | Partial<CallOptions>,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n _modelType(): string;\n\n _llmType(): string;\n\n getNumTokens(content: MessageContent): Promise<number>;\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any>;\n\n serialize(): SerializedLLM;\n}\n\nexport type LanguageModelOutput = BaseMessage | string;\n\nexport type LanguageModelLike = RunnableInterface<\n BaseLanguageModelInput,\n LanguageModelOutput\n>;\n\n/**\n * Base class for language models.\n */\nexport abstract class BaseLanguageModel<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n>\n extends BaseLangChain<BaseLanguageModelInput, RunOutput, CallOptions>\n implements\n BaseLanguageModelParams,\n BaseLanguageModelInterface<RunOutput, CallOptions>\n{\n /**\n * Keys that the language model accepts as call options.\n */\n get callKeys(): string[] {\n return [\"stop\", \"timeout\", \"signal\", \"tags\", \"metadata\", \"callbacks\"];\n }\n\n /**\n * The async caller should be used by subclasses to make any async calls,\n * which will thus benefit from the concurrency and retry logic.\n */\n caller: AsyncCaller;\n\n cache?: BaseCache;\n\n constructor({\n callbacks,\n callbackManager,\n ...params\n }: BaseLanguageModelParams) {\n const { cache, ...rest } = params;\n super({\n callbacks: callbacks ?? callbackManager,\n ...rest,\n });\n if (typeof cache === \"object\") {\n this.cache = cache;\n } else if (cache) {\n this.cache = InMemoryCache.global();\n } else {\n this.cache = undefined;\n }\n this.caller = new AsyncCaller(params ?? {});\n }\n\n abstract generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | CallOptions,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n abstract _modelType(): string;\n\n abstract _llmType(): string;\n\n private _encoding?: Tiktoken;\n\n /**\n * Get the number of tokens in the content.\n * @param content The content to get the number of tokens for.\n * @returns The number of tokens in the content.\n */\n async getNumTokens(content: MessageContent) {\n // Extract text content from MessageContent\n let textContent: string;\n if (typeof content === \"string\") {\n textContent = content;\n } else {\n /**\n * Content is an array of ContentBlock\n *\n * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content.\n * We need to find a better way to do this.\n * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116\n */\n textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n }\n\n // fallback to approximate calculation if tiktoken is not available\n let numTokens = Math.ceil(textContent.length / 4);\n\n if (!this._encoding) {\n try {\n this._encoding = await encodingForModel(\n \"modelName\" in this\n ? getModelNameForTiktoken(this.modelName as string)\n : \"gpt2\"\n );\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n if (this._encoding) {\n try {\n numTokens = this._encoding.encode(textContent).length;\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n return numTokens;\n }\n\n protected static _convertInputToPromptValue(\n input: BaseLanguageModelInput\n ): BasePromptValueInterface {\n if (typeof input === \"string\") {\n return new StringPromptValue(input);\n } else if (Array.isArray(input)) {\n return new ChatPromptValue(input.map(coerceMessageLikeToMessage));\n } else {\n return input;\n }\n }\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any> {\n return {};\n }\n\n /**\n * Create a unique cache key for a specific call to a specific language model.\n * @param callOptions Call options for the model\n * @returns A unique cache key.\n */\n _getSerializedCacheKeyParametersForCall(\n // TODO: Fix when we remove the RunnableLambda backwards compatibility shim.\n {\n config,\n ...callOptions\n }: CallOptions & { config?: RunnableConfig }\n ): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const params: Record<string, any> = {\n ...this._identifyingParams(),\n ...callOptions,\n _type: this._llmType(),\n _model: this._modelType(),\n };\n const filteredEntries = Object.entries(params).filter(\n ([_, value]) => value !== undefined\n );\n const serializedEntries = filteredEntries\n .map(([key, value]) => `${key}:${JSON.stringify(value)}`)\n .sort()\n .join(\",\");\n return serializedEntries;\n }\n\n /**\n * @deprecated\n * Return a json-like object representing this LLM.\n */\n serialize(): SerializedLLM {\n return {\n ...this._identifyingParams(),\n _type: this._llmType(),\n _model: this._modelType(),\n };\n }\n\n /**\n * @deprecated\n * Load an LLM from a json-like object describing it.\n */\n static async deserialize(_data: SerializedLLM): Promise<BaseLanguageModel> {\n throw new Error(\"Use .toJSON() instead\");\n }\n\n /**\n * Return profiling information for the model.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return {};\n }\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Model wrapper that returns outputs formatted to match the given schema.\n *\n * @template {BaseLanguageModelInput} RunInput The input type for the Runnable, expected to be the same input for the LLM.\n * @template {Record<string, any>} RunOutput The output type for the Runnable, expected to be a Zod schema object for structured output validation.\n *\n * @param {InteropZodType<RunOutput>} schema The schema for the structured output. Either as a Zod schema or a valid JSON schema object.\n * If a Zod schema is passed, the returned attributes will be validated, whereas with JSON schema they will not be.\n * @param {string} name The name of the function to call.\n * @param {\"functionCalling\" | \"jsonMode\"} [method=functionCalling] The method to use for getting the structured output. Defaults to \"functionCalling\".\n * @param {boolean | undefined} [includeRaw=false] Whether to include the raw output in the result. Defaults to false.\n * @returns {Runnable<RunInput, RunOutput> | Runnable<RunInput, { raw: BaseMessage; parsed: RunOutput }>} A new runnable that calls the LLM with structured output.\n */\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | InteropZodType<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n {\n raw: BaseMessage;\n parsed: RunOutput;\n }\n >;\n\n /**\n * Filter out large/inappropriate fields from invocation params for tracing metadata.\n * Removes fields like tools, functions, messages, response_format that can be large.\n */\n protected _filterInvocationParamsForTracing(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n params: Record<string, any>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): Record<string, any> {\n const { tools, functions, messages, response_format, ...rest } = params;\n return rest;\n }\n}\n\n/**\n * Shared interface for token usage\n * return type from LLM calls.\n */\nexport interface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,MAAa,2BAA2B,cAAqC;CAC3E,IAAI,UAAU,WAAW,OAAO,GAC9B,OAAO;CAGT,IAAI,UAAU,WAAW,mBAAmB,GAC1C,OAAO;CAGT,IAAI,UAAU,WAAW,gBAAgB,GACvC,OAAO;CAGT,IAAI,UAAU,WAAW,WAAW,GAClC,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,GAC/B,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,GAC/B,OAAO;CAGT,OAAO;AACT;AA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;;CAMA,YAA2B;EACzB,OAAO;GACL,GAAG,KAAK,mBAAmB;GAC3B,OAAO,KAAK,SAAS;GACrB,QAAQ,KAAK,WAAW;EAC1B;CACF;;;;;CAMA,aAAa,YAAY,OAAkD;EACzE,MAAM,IAAI,MAAM,uBAAuB;CACzC;;;;;;CAOA,IAAI,UAAwB;EAC1B,OAAO,CAAC;CACV;;;;;CAkGA,kCAEE,QAEqB;EACrB,MAAM,EAAE,OAAO,WAAW,UAAU,iBAAiB,GAAG,SAAS;EACjE,OAAO;CACT;AACF"}
|
|
@@ -102,6 +102,10 @@ interface BaseLanguageModelCallOptions extends RunnableConfig, BaseLanguageModel
|
|
|
102
102
|
* If not provided, the default stop tokens for the model will be used.
|
|
103
103
|
*/
|
|
104
104
|
stop?: string[];
|
|
105
|
+
/**
|
|
106
|
+
* Overrides the model's configured `maxRetries` for this call only.
|
|
107
|
+
*/
|
|
108
|
+
maxRetries?: number;
|
|
105
109
|
}
|
|
106
110
|
interface FunctionDefinition {
|
|
107
111
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.cts","names":[],"sources":["../../src/language_models/base.ts"],"mappings":";;;;;;;;;;;;;;;;cAgCa,0BAAuB,sBAAwB;cA4B/C,0BAAuB;;;;;;;;;;;;cAoBvB,sBAAmB;;;;;;iBAgGhB,aAAa,gBAAgB,QAAQ;UAgB3C;EACR;EACA,WAAW;;cAGA,uBAAkB,QAAA,aAG5B,2BAAsB;KAuBb;EACV;EACA;IAEE;UAEa;EACf;EACA,YAAY;EACZ;EACA,WAAW;;;;;uBAMS,cACpB,UACA,WACA,oBAAoB,iBAAiB,wBAE7B,SAAS,UAAU,WAAW,wBAC3B;;;;EAKX;EAEA,YAAY;EAEZ;EAEA,WAAW;MAEP;KAAoB;;EAOxB,YAAY,QAAQ;YASV,YAAY,aAAa;;;;;;;UAiBpB,gCACP,mBAAmB;;;;EAI3B,kBAAkB;EAElB,QAAQ;;UAGO;;;;;EAKf;;;;I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qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,uCACR,SAAS,wBAAwB;EAEpC,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,sCACR,SAAS;IAA0B,KAAK;IAAa,QAAQ;;EAEhE,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,uCACR,SAAS,wBAAwB;EAEpC,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,sCACR,SAAS;IAA0B,KAAK;IAAa,QAAQ;;;;;;;;;;;;;;;EAehE,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,eAAe,aAEf,qBACJ,SAAS,yCAEP,SAAS,wBAAwB,aACjC,SACE;IAEE,KAAK;IACL,QAAQ;;;;;;YAQN,kCAER,QAAQ,sBAEP;;;;;;UAUY;EACf;EACA;EACA"}
|
|
@@ -102,6 +102,10 @@ interface BaseLanguageModelCallOptions extends RunnableConfig, BaseLanguageModel
|
|
|
102
102
|
* If not provided, the default stop tokens for the model will be used.
|
|
103
103
|
*/
|
|
104
104
|
stop?: string[];
|
|
105
|
+
/**
|
|
106
|
+
* Overrides the model's configured `maxRetries` for this call only.
|
|
107
|
+
*/
|
|
108
|
+
maxRetries?: number;
|
|
105
109
|
}
|
|
106
110
|
interface FunctionDefinition {
|
|
107
111
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/language_models/base.ts"],"mappings":";;;;;;;;;;;;;;;;cAgCa,0BAAuB,sBAAwB;cA4B/C,0BAAuB;;;;;;;;;;;;cAoBvB,sBAAmB;;;;;;iBAgGhB,aAAa,gBAAgB,QAAQ;UAgB3C;EACR;EACA,WAAW;;cAGA,uBAAkB,QAAA,aAG5B,2BAAsB;KAuBb;EACV;EACA;IAEE;UAEa;EACf;EACA,YAAY;EACZ;EACA,WAAW;;;;;uBAMS,cACpB,UACA,WACA,oBAAo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AIf,sBAEE,kBAAkB,sBAAsB,qBAExC,QAAQ,mBAAmB,YAC3B,SAAS,uCACR,SAAS,wBAAwB;EAEpC,sBAEE,kBAAkB,sBAAsB,qBAExC,QAAQ,mBAAmB,YAC3B,SAAS,sCACR,SAAS;IAA0B,KAAK;IAAa,QAAQ;;EAEhE,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,uCACR,SAAS,wBAAwB;EAEpC,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,sCACR,SAAS;IAA0B,KAAK;IAAa,QAAQ;;EAEhE,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,uCACR,SAAS,wBAAwB;EAEpC,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,UAAU,aAEV,qBACJ,SAAS,sCACR,SAAS;IAA0B,KAAK;IAAa,QAAQ;;;;;;;;;;;;;;;EAehE,sBAEE,kBAAkB,sBAAsB,qBAExC,QACI,eAAe,aAEf,qBACJ,SAAS,yCAEP,SAAS,wBAAwB,aACjC,SACE;IAEE,KAAK;IACL,QAAQ;;;;;;YAQN,kCAER,QAAQ,sBAEP;;;;;;UAUY;EACf;EACA;EACA"}
|
|
@@ -138,7 +138,7 @@ var BaseLangChain = class extends Runnable {
|
|
|
138
138
|
this.callbacks = params.callbacks;
|
|
139
139
|
this.tags = params.tags ?? [];
|
|
140
140
|
this.metadata = params.metadata ?? {};
|
|
141
|
-
this._addVersion("@langchain/core", "1.2.
|
|
141
|
+
this._addVersion("@langchain/core", "1.2.8");
|
|
142
142
|
}
|
|
143
143
|
_addVersion(pkg, version) {
|
|
144
144
|
const existing = this.metadata?.versions;
|