@langchain/core 1.3.6 → 1.3.7
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 +8 -0
- package/dist/errors/index.cjs +56 -0
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.d.cts +48 -0
- package/dist/errors/index.d.cts.map +1 -1
- package/dist/errors/index.d.ts +48 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +56 -1
- package/dist/errors/index.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/messages/block_translators/anthropic.cjs +18 -0
- package/dist/messages/block_translators/anthropic.cjs.map +1 -1
- package/dist/messages/block_translators/anthropic.js +18 -0
- package/dist/messages/block_translators/anthropic.js.map +1 -1
- package/dist/messages/block_translators/google.cjs +27 -1
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js +27 -1
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/messages/block_translators/openai.cjs +25 -0
- package/dist/messages/block_translators/openai.cjs.map +1 -1
- package/dist/messages/block_translators/openai.js +25 -0
- package/dist/messages/block_translators/openai.js.map +1 -1
- package/dist/messages/content/index.cjs +1 -0
- package/dist/messages/content/index.cjs.map +1 -1
- package/dist/messages/content/index.d.cts +23 -1
- package/dist/messages/content/index.d.cts.map +1 -1
- package/dist/messages/content/index.d.ts +23 -1
- package/dist/messages/content/index.d.ts.map +1 -1
- package/dist/messages/content/index.js +1 -0
- package/dist/messages/content/index.js.map +1 -1
- package/dist/output_parsers/json.cjs +8 -0
- package/dist/output_parsers/json.cjs.map +1 -1
- package/dist/output_parsers/json.d.cts +5 -0
- package/dist/output_parsers/json.d.cts.map +1 -1
- package/dist/output_parsers/json.d.ts +5 -0
- package/dist/output_parsers/json.d.ts.map +1 -1
- package/dist/output_parsers/json.js +8 -0
- package/dist/output_parsers/json.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +3 -0
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +3 -0
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/refusal.cjs +23 -0
- package/dist/output_parsers/refusal.cjs.map +1 -0
- package/dist/output_parsers/refusal.js +23 -0
- package/dist/output_parsers/refusal.js.map +1 -0
- package/dist/output_parsers/standard_schema.cjs +8 -0
- package/dist/output_parsers/standard_schema.cjs.map +1 -1
- package/dist/output_parsers/standard_schema.d.cts +6 -0
- package/dist/output_parsers/standard_schema.d.cts.map +1 -1
- package/dist/output_parsers/standard_schema.d.ts +6 -0
- package/dist/output_parsers/standard_schema.d.ts.map +1 -1
- package/dist/output_parsers/standard_schema.js +8 -0
- package/dist/output_parsers/standard_schema.js.map +1 -1
- package/dist/output_parsers/structured.cjs +8 -0
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.d.cts +6 -0
- package/dist/output_parsers/structured.d.cts.map +1 -1
- package/dist/output_parsers/structured.d.ts +6 -0
- package/dist/output_parsers/structured.d.ts.map +1 -1
- package/dist/output_parsers/structured.js +8 -0
- package/dist/output_parsers/structured.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# @langchain/core
|
|
2
2
|
|
|
3
|
+
## 1.3.7
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#12120](https://github.com/langchain-ai/langchainjs/pull/12120) [`a4fb396`](https://github.com/langchain-ai/langchainjs/commit/a4fb396d7b323b9f3f8c7e45875376ec5fb88d72) Thanks [@thushanth-bengre-langchain](https://github.com/thushanth-bengre-langchain)! - feat(core): add a standard `refusal` content block and `ModelRefusalError`
|
|
8
|
+
|
|
9
|
+
Model refusals from OpenAI, Anthropic, and Gemini now appear as a `refusal` content block in `message.contentBlocks`. JSON, tool-call, and structured output parsers throw `ModelRefusalError` (from `@langchain/core/errors`) when the model refuses, instead of a generic parsing error.
|
|
10
|
+
|
|
3
11
|
## 1.3.6
|
|
4
12
|
|
|
5
13
|
### Patch Changes
|
package/dist/errors/index.cjs
CHANGED
|
@@ -6,6 +6,7 @@ var errors_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
|
6
6
|
ContextOverflowError: () => ContextOverflowError,
|
|
7
7
|
LangChainError: () => LangChainError,
|
|
8
8
|
ModelAbortError: () => ModelAbortError,
|
|
9
|
+
ModelRefusalError: () => ModelRefusalError,
|
|
9
10
|
addLangChainErrorFields: () => addLangChainErrorFields,
|
|
10
11
|
getRetryable: () => getRetryable,
|
|
11
12
|
ns: () => ns,
|
|
@@ -194,9 +195,64 @@ var ContextOverflowError = class ContextOverflowError extends ns.brand(LangChain
|
|
|
194
195
|
return error;
|
|
195
196
|
}
|
|
196
197
|
};
|
|
198
|
+
const DEFAULT_REFUSAL_MESSAGE = "Model refused to produce the requested output";
|
|
199
|
+
/**
|
|
200
|
+
* Error class representing a model refusal.
|
|
201
|
+
*
|
|
202
|
+
* Providers report a refusal, such as a safety-policy refusal, as a successful
|
|
203
|
+
* response rather than an error. LangChain raises this error where a refusal
|
|
204
|
+
* cannot be treated as an answer, for example when structured output has
|
|
205
|
+
* nothing to parse, or when an agent uses refusal middleware.
|
|
206
|
+
*
|
|
207
|
+
* The {@link ModelRefusalError} extends the {@link LangChainError} base class with
|
|
208
|
+
* the marker `"model-refusal"`. Retrying the same request is unlikely to succeed,
|
|
209
|
+
* so the error is marked as not retryable.
|
|
210
|
+
*
|
|
211
|
+
* @example
|
|
212
|
+
* ```typescript
|
|
213
|
+
* try {
|
|
214
|
+
* await model.withStructuredOutput(schema).invoke(input);
|
|
215
|
+
* } catch (err) {
|
|
216
|
+
* if (ModelRefusalError.isInstance(err)) {
|
|
217
|
+
* console.warn("Model refused:", err.message, err.rawMessage);
|
|
218
|
+
* } else {
|
|
219
|
+
* throw err;
|
|
220
|
+
* }
|
|
221
|
+
* }
|
|
222
|
+
* ```
|
|
223
|
+
*/
|
|
224
|
+
var ModelRefusalError = class ModelRefusalError extends ns.brand(LangChainError, "model-refusal") {
|
|
225
|
+
name = "ModelRefusalError";
|
|
226
|
+
/**
|
|
227
|
+
* The refused model response, if available.
|
|
228
|
+
*/
|
|
229
|
+
rawMessage;
|
|
230
|
+
constructor(message, fields) {
|
|
231
|
+
super(message ?? DEFAULT_REFUSAL_MESSAGE);
|
|
232
|
+
this.rawMessage = fields?.rawMessage;
|
|
233
|
+
stampRetryable(this, false);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Creates a {@link ModelRefusalError} from a refusal content block.
|
|
237
|
+
*
|
|
238
|
+
* The message includes the provider's refusal `category`, when present, and
|
|
239
|
+
* the refusal text.
|
|
240
|
+
*
|
|
241
|
+
* @param refusal - The refusal content block from the model response.
|
|
242
|
+
* @param rawMessage - The refused model response.
|
|
243
|
+
*/
|
|
244
|
+
static fromRefusal(refusal, rawMessage) {
|
|
245
|
+
let message = DEFAULT_REFUSAL_MESSAGE;
|
|
246
|
+
const category = refusal.extras?.category;
|
|
247
|
+
if (category) message += ` (category='${String(category)}')`;
|
|
248
|
+
if (refusal.refusal) message += `: ${refusal.refusal}`;
|
|
249
|
+
return new ModelRefusalError(message, { rawMessage });
|
|
250
|
+
}
|
|
251
|
+
};
|
|
197
252
|
exports.ContextOverflowError = ContextOverflowError;
|
|
198
253
|
exports.LangChainError = LangChainError;
|
|
199
254
|
exports.ModelAbortError = ModelAbortError;
|
|
255
|
+
exports.ModelRefusalError = ModelRefusalError;
|
|
200
256
|
exports.addLangChainErrorFields = addLangChainErrorFields;
|
|
201
257
|
Object.defineProperty(exports, "errors_exports", {
|
|
202
258
|
enumerable: true,
|
|
@@ -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 { BrandedClass } 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":";;;;;;;;;;;;;;AAmBA,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"}
|
|
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 type { BaseMessage } from \"../messages/base.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport { ns as baseNs } from \"../utils/namespace.js\";\n\nexport type { BrandedClass } 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\nconst DEFAULT_REFUSAL_MESSAGE = \"Model refused to produce the requested output\";\n\n/**\n * Error class representing a model refusal.\n *\n * Providers report a refusal, such as a safety-policy refusal, as a successful\n * response rather than an error. LangChain raises this error where a refusal\n * cannot be treated as an answer, for example when structured output has\n * nothing to parse, or when an agent uses refusal middleware.\n *\n * The {@link ModelRefusalError} extends the {@link LangChainError} base class with\n * the marker `\"model-refusal\"`. Retrying the same request is unlikely to succeed,\n * so the error is marked as not retryable.\n *\n * @example\n * ```typescript\n * try {\n * await model.withStructuredOutput(schema).invoke(input);\n * } catch (err) {\n * if (ModelRefusalError.isInstance(err)) {\n * console.warn(\"Model refused:\", err.message, err.rawMessage);\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ModelRefusalError extends ns.brand(\n LangChainError,\n \"model-refusal\"\n) {\n readonly name = \"ModelRefusalError\";\n\n /**\n * The refused model response, if available.\n */\n rawMessage?: BaseMessage;\n\n constructor(message?: string, fields?: { rawMessage?: BaseMessage }) {\n super(message ?? DEFAULT_REFUSAL_MESSAGE);\n this.rawMessage = fields?.rawMessage;\n stampRetryable(this, false);\n }\n\n /**\n * Creates a {@link ModelRefusalError} from a refusal content block.\n *\n * The message includes the provider's refusal `category`, when present, and\n * the refusal text.\n *\n * @param refusal - The refusal content block from the model response.\n * @param rawMessage - The refused model response.\n */\n static fromRefusal(\n refusal: ContentBlock.Refusal,\n rawMessage?: BaseMessage\n ): ModelRefusalError {\n let message = DEFAULT_REFUSAL_MESSAGE;\n const category = refusal.extras?.category;\n if (category) {\n message += ` (category='${String(category)}')`;\n }\n if (refusal.refusal) {\n message += `: ${refusal.refusal}`;\n }\n return new ModelRefusalError(message, { rawMessage });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,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;AAEA,MAAM,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BhC,IAAa,oBAAb,MAAa,0BAA0B,GAAG,MACxC,gBACA,eACF,CAAC,CAAC;CACA,OAAgB;;;;CAKhB;CAEA,YAAY,SAAkB,QAAuC;EACnE,MAAM,WAAW,uBAAuB;EACxC,KAAK,aAAa,QAAQ;EAC1B,eAAe,MAAM,KAAK;CAC5B;;;;;;;;;;CAWA,OAAO,YACL,SACA,YACmB;EACnB,IAAI,UAAU;EACd,MAAM,WAAW,QAAQ,QAAQ;EACjC,IAAI,UACF,WAAW,eAAe,OAAO,QAAQ,EAAE;EAE7C,IAAI,QAAQ,SACV,WAAW,KAAK,QAAQ;EAE1B,OAAO,IAAI,kBAAkB,SAAS,EAAE,WAAW,CAAC;CACtD;AACF"}
|
package/dist/errors/index.d.cts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { BrandedClass, Namespace } from "../utils/namespace.cjs";
|
|
2
2
|
import { AIMessageChunk } from "../messages/ai.cjs";
|
|
3
|
+
import { BaseMessage } from "../messages/base.cjs";
|
|
4
|
+
import { ContentBlock } from "../messages/content/index.cjs";
|
|
3
5
|
export type LangChainErrorCodes = "CONTEXT_OVERFLOW" | "INVALID_PROMPT_INPUT" | "INVALID_TOOL_RESULTS" | "MESSAGE_COERCION_FAILURE" | "MODEL_AUTHENTICATION" | "MODEL_NOT_FOUND" | "MODEL_RATE_LIMIT" | "OUTPUT_PARSING_FAILURE" | "MODEL_ABORTED";
|
|
4
6
|
/** @deprecated Subclass LangChainError instead */
|
|
5
7
|
export declare function addLangChainErrorFields(error: any, lc_error_code: LangChainErrorCodes): any;
|
|
@@ -155,5 +157,51 @@ export declare class ContextOverflowError extends ContextOverflowError_base {
|
|
|
155
157
|
*/
|
|
156
158
|
static fromError(obj: Error): ContextOverflowError;
|
|
157
159
|
}
|
|
160
|
+
declare const ModelRefusalError_base: BrandedClass<typeof LangChainError>;
|
|
161
|
+
/**
|
|
162
|
+
* Error class representing a model refusal.
|
|
163
|
+
*
|
|
164
|
+
* Providers report a refusal, such as a safety-policy refusal, as a successful
|
|
165
|
+
* response rather than an error. LangChain raises this error where a refusal
|
|
166
|
+
* cannot be treated as an answer, for example when structured output has
|
|
167
|
+
* nothing to parse, or when an agent uses refusal middleware.
|
|
168
|
+
*
|
|
169
|
+
* The {@link ModelRefusalError} extends the {@link LangChainError} base class with
|
|
170
|
+
* the marker `"model-refusal"`. Retrying the same request is unlikely to succeed,
|
|
171
|
+
* so the error is marked as not retryable.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```typescript
|
|
175
|
+
* try {
|
|
176
|
+
* await model.withStructuredOutput(schema).invoke(input);
|
|
177
|
+
* } catch (err) {
|
|
178
|
+
* if (ModelRefusalError.isInstance(err)) {
|
|
179
|
+
* console.warn("Model refused:", err.message, err.rawMessage);
|
|
180
|
+
* } else {
|
|
181
|
+
* throw err;
|
|
182
|
+
* }
|
|
183
|
+
* }
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
export declare class ModelRefusalError extends ModelRefusalError_base {
|
|
187
|
+
readonly name = "ModelRefusalError";
|
|
188
|
+
/**
|
|
189
|
+
* The refused model response, if available.
|
|
190
|
+
*/
|
|
191
|
+
rawMessage?: BaseMessage;
|
|
192
|
+
constructor(message?: string, fields?: {
|
|
193
|
+
rawMessage?: BaseMessage;
|
|
194
|
+
});
|
|
195
|
+
/**
|
|
196
|
+
* Creates a {@link ModelRefusalError} from a refusal content block.
|
|
197
|
+
*
|
|
198
|
+
* The message includes the provider's refusal `category`, when present, and
|
|
199
|
+
* the refusal text.
|
|
200
|
+
*
|
|
201
|
+
* @param refusal - The refusal content block from the model response.
|
|
202
|
+
* @param rawMessage - The refused model response.
|
|
203
|
+
*/
|
|
204
|
+
static fromRefusal(refusal: ContentBlock.Refusal, rawMessage?: BaseMessage): ModelRefusalError;
|
|
205
|
+
}
|
|
158
206
|
export type { BrandedClass };
|
|
159
207
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":["_$___utils_namespace_js0.Namespace","_$__index_js0.BrandedClass"],"sources":["../../src/errors/index.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["_$___utils_namespace_js0.Namespace","_$__index_js0.BrandedClass"],"sources":["../../src/errors/index.ts"],"mappings":";;;;YASY;;wBAYI,wBACd,YACA,eAAe;;qBAQJ,IAAAA;;;;;;;;;;;wBAeG,eAAe,GAAG,OAAO,GAAG,qBAAqB;;;;;;;wBAqBjD,aAAa;;;;;;;;;;;;;;;;;;;;qBA2BhB,uBAAuB;WACzB;EAET,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqCD,wBAAwB;WAC1B;;;;;WAMA,gBAAgB;;;;;;;EAQzB,YAAY,iBAAiB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwClC,6BAA6B;WAI/B;;;;;;;EAQT,QAAQ;EAER,YAAY;;;;;;;;;;;;;;;;;;;;SAyBL,UAAU,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkCnB,0BAA0B;WAI5B;;;;EAKT,aAAa;EAEb,YAAY,kBAAkB;IAAW,aAAa;;;;;;;;;;;SAe/C,YACL,SAAS,aAAa,SACtB,aAAa,cACZ"}
|
package/dist/errors/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { BrandedClass, Namespace } from "../utils/namespace.js";
|
|
2
2
|
import { AIMessageChunk } from "../messages/ai.js";
|
|
3
|
+
import { BaseMessage } from "../messages/base.js";
|
|
4
|
+
import { ContentBlock } from "../messages/content/index.js";
|
|
3
5
|
export type LangChainErrorCodes = "CONTEXT_OVERFLOW" | "INVALID_PROMPT_INPUT" | "INVALID_TOOL_RESULTS" | "MESSAGE_COERCION_FAILURE" | "MODEL_AUTHENTICATION" | "MODEL_NOT_FOUND" | "MODEL_RATE_LIMIT" | "OUTPUT_PARSING_FAILURE" | "MODEL_ABORTED";
|
|
4
6
|
/** @deprecated Subclass LangChainError instead */
|
|
5
7
|
export declare function addLangChainErrorFields(error: any, lc_error_code: LangChainErrorCodes): any;
|
|
@@ -155,5 +157,51 @@ export declare class ContextOverflowError extends ContextOverflowError_base {
|
|
|
155
157
|
*/
|
|
156
158
|
static fromError(obj: Error): ContextOverflowError;
|
|
157
159
|
}
|
|
160
|
+
declare const ModelRefusalError_base: BrandedClass<typeof LangChainError>;
|
|
161
|
+
/**
|
|
162
|
+
* Error class representing a model refusal.
|
|
163
|
+
*
|
|
164
|
+
* Providers report a refusal, such as a safety-policy refusal, as a successful
|
|
165
|
+
* response rather than an error. LangChain raises this error where a refusal
|
|
166
|
+
* cannot be treated as an answer, for example when structured output has
|
|
167
|
+
* nothing to parse, or when an agent uses refusal middleware.
|
|
168
|
+
*
|
|
169
|
+
* The {@link ModelRefusalError} extends the {@link LangChainError} base class with
|
|
170
|
+
* the marker `"model-refusal"`. Retrying the same request is unlikely to succeed,
|
|
171
|
+
* so the error is marked as not retryable.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```typescript
|
|
175
|
+
* try {
|
|
176
|
+
* await model.withStructuredOutput(schema).invoke(input);
|
|
177
|
+
* } catch (err) {
|
|
178
|
+
* if (ModelRefusalError.isInstance(err)) {
|
|
179
|
+
* console.warn("Model refused:", err.message, err.rawMessage);
|
|
180
|
+
* } else {
|
|
181
|
+
* throw err;
|
|
182
|
+
* }
|
|
183
|
+
* }
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
export declare class ModelRefusalError extends ModelRefusalError_base {
|
|
187
|
+
readonly name = "ModelRefusalError";
|
|
188
|
+
/**
|
|
189
|
+
* The refused model response, if available.
|
|
190
|
+
*/
|
|
191
|
+
rawMessage?: BaseMessage;
|
|
192
|
+
constructor(message?: string, fields?: {
|
|
193
|
+
rawMessage?: BaseMessage;
|
|
194
|
+
});
|
|
195
|
+
/**
|
|
196
|
+
* Creates a {@link ModelRefusalError} from a refusal content block.
|
|
197
|
+
*
|
|
198
|
+
* The message includes the provider's refusal `category`, when present, and
|
|
199
|
+
* the refusal text.
|
|
200
|
+
*
|
|
201
|
+
* @param refusal - The refusal content block from the model response.
|
|
202
|
+
* @param rawMessage - The refused model response.
|
|
203
|
+
*/
|
|
204
|
+
static fromRefusal(refusal: ContentBlock.Refusal, rawMessage?: BaseMessage): ModelRefusalError;
|
|
205
|
+
}
|
|
158
206
|
export type { BrandedClass };
|
|
159
207
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["_$___utils_namespace_js0.Namespace","_$__index_js0.BrandedClass"],"sources":["../../src/errors/index.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["_$___utils_namespace_js0.Namespace","_$__index_js0.BrandedClass"],"sources":["../../src/errors/index.ts"],"mappings":";;;;YASY;;wBAYI,wBACd,YACA,eAAe;;qBAQJ,IAAAA;;;;;;;;;;;wBAeG,eAAe,GAAG,OAAO,GAAG,qBAAqB;;;;;;;wBAqBjD,aAAa;;;;;;;;;;;;;;;;;;;;qBA2BhB,uBAAuB;WACzB;EAET,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqCD,wBAAwB;WAC1B;;;;;WAMA,gBAAgB;;;;;;;EAQzB,YAAY,iBAAiB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwClC,6BAA6B;WAI/B;;;;;;;EAQT,QAAQ;EAER,YAAY;;;;;;;;;;;;;;;;;;;;SAyBL,UAAU,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkCnB,0BAA0B;WAI5B;;;;EAKT,aAAa;EAEb,YAAY,kBAAkB;IAAW,aAAa;;;;;;;;;;;SAe/C,YACL,SAAS,aAAa,SACtB,aAAa,cACZ"}
|
package/dist/errors/index.js
CHANGED
|
@@ -5,6 +5,7 @@ var errors_exports = /* @__PURE__ */ __exportAll({
|
|
|
5
5
|
ContextOverflowError: () => ContextOverflowError,
|
|
6
6
|
LangChainError: () => LangChainError,
|
|
7
7
|
ModelAbortError: () => ModelAbortError,
|
|
8
|
+
ModelRefusalError: () => ModelRefusalError,
|
|
8
9
|
addLangChainErrorFields: () => addLangChainErrorFields,
|
|
9
10
|
getRetryable: () => getRetryable,
|
|
10
11
|
ns: () => ns,
|
|
@@ -193,6 +194,60 @@ var ContextOverflowError = class ContextOverflowError extends ns.brand(LangChain
|
|
|
193
194
|
return error;
|
|
194
195
|
}
|
|
195
196
|
};
|
|
196
|
-
|
|
197
|
+
const DEFAULT_REFUSAL_MESSAGE = "Model refused to produce the requested output";
|
|
198
|
+
/**
|
|
199
|
+
* Error class representing a model refusal.
|
|
200
|
+
*
|
|
201
|
+
* Providers report a refusal, such as a safety-policy refusal, as a successful
|
|
202
|
+
* response rather than an error. LangChain raises this error where a refusal
|
|
203
|
+
* cannot be treated as an answer, for example when structured output has
|
|
204
|
+
* nothing to parse, or when an agent uses refusal middleware.
|
|
205
|
+
*
|
|
206
|
+
* The {@link ModelRefusalError} extends the {@link LangChainError} base class with
|
|
207
|
+
* the marker `"model-refusal"`. Retrying the same request is unlikely to succeed,
|
|
208
|
+
* so the error is marked as not retryable.
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* ```typescript
|
|
212
|
+
* try {
|
|
213
|
+
* await model.withStructuredOutput(schema).invoke(input);
|
|
214
|
+
* } catch (err) {
|
|
215
|
+
* if (ModelRefusalError.isInstance(err)) {
|
|
216
|
+
* console.warn("Model refused:", err.message, err.rawMessage);
|
|
217
|
+
* } else {
|
|
218
|
+
* throw err;
|
|
219
|
+
* }
|
|
220
|
+
* }
|
|
221
|
+
* ```
|
|
222
|
+
*/
|
|
223
|
+
var ModelRefusalError = class ModelRefusalError extends ns.brand(LangChainError, "model-refusal") {
|
|
224
|
+
name = "ModelRefusalError";
|
|
225
|
+
/**
|
|
226
|
+
* The refused model response, if available.
|
|
227
|
+
*/
|
|
228
|
+
rawMessage;
|
|
229
|
+
constructor(message, fields) {
|
|
230
|
+
super(message ?? DEFAULT_REFUSAL_MESSAGE);
|
|
231
|
+
this.rawMessage = fields?.rawMessage;
|
|
232
|
+
stampRetryable(this, false);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Creates a {@link ModelRefusalError} from a refusal content block.
|
|
236
|
+
*
|
|
237
|
+
* The message includes the provider's refusal `category`, when present, and
|
|
238
|
+
* the refusal text.
|
|
239
|
+
*
|
|
240
|
+
* @param refusal - The refusal content block from the model response.
|
|
241
|
+
* @param rawMessage - The refused model response.
|
|
242
|
+
*/
|
|
243
|
+
static fromRefusal(refusal, rawMessage) {
|
|
244
|
+
let message = DEFAULT_REFUSAL_MESSAGE;
|
|
245
|
+
const category = refusal.extras?.category;
|
|
246
|
+
if (category) message += ` (category='${String(category)}')`;
|
|
247
|
+
if (refusal.refusal) message += `: ${refusal.refusal}`;
|
|
248
|
+
return new ModelRefusalError(message, { rawMessage });
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
export { ContextOverflowError, LangChainError, ModelAbortError, ModelRefusalError, addLangChainErrorFields, errors_exports, getRetryable, ns, stampRetryable };
|
|
197
252
|
|
|
198
253
|
//# 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 { BrandedClass } 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":";;;;;;;;;;;;;AAmBA,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;;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"}
|
|
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 type { BaseMessage } from \"../messages/base.js\";\nimport type { ContentBlock } from \"../messages/content/index.js\";\nimport { ns as baseNs } from \"../utils/namespace.js\";\n\nexport type { BrandedClass } 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\nconst DEFAULT_REFUSAL_MESSAGE = \"Model refused to produce the requested output\";\n\n/**\n * Error class representing a model refusal.\n *\n * Providers report a refusal, such as a safety-policy refusal, as a successful\n * response rather than an error. LangChain raises this error where a refusal\n * cannot be treated as an answer, for example when structured output has\n * nothing to parse, or when an agent uses refusal middleware.\n *\n * The {@link ModelRefusalError} extends the {@link LangChainError} base class with\n * the marker `\"model-refusal\"`. Retrying the same request is unlikely to succeed,\n * so the error is marked as not retryable.\n *\n * @example\n * ```typescript\n * try {\n * await model.withStructuredOutput(schema).invoke(input);\n * } catch (err) {\n * if (ModelRefusalError.isInstance(err)) {\n * console.warn(\"Model refused:\", err.message, err.rawMessage);\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class ModelRefusalError extends ns.brand(\n LangChainError,\n \"model-refusal\"\n) {\n readonly name = \"ModelRefusalError\";\n\n /**\n * The refused model response, if available.\n */\n rawMessage?: BaseMessage;\n\n constructor(message?: string, fields?: { rawMessage?: BaseMessage }) {\n super(message ?? DEFAULT_REFUSAL_MESSAGE);\n this.rawMessage = fields?.rawMessage;\n stampRetryable(this, false);\n }\n\n /**\n * Creates a {@link ModelRefusalError} from a refusal content block.\n *\n * The message includes the provider's refusal `category`, when present, and\n * the refusal text.\n *\n * @param refusal - The refusal content block from the model response.\n * @param rawMessage - The refused model response.\n */\n static fromRefusal(\n refusal: ContentBlock.Refusal,\n rawMessage?: BaseMessage\n ): ModelRefusalError {\n let message = DEFAULT_REFUSAL_MESSAGE;\n const category = refusal.extras?.category;\n if (category) {\n message += ` (category='${String(category)}')`;\n }\n if (refusal.refusal) {\n message += `: ${refusal.refusal}`;\n }\n return new ModelRefusalError(message, { rawMessage });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,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;;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;AAEA,MAAM,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BhC,IAAa,oBAAb,MAAa,0BAA0B,GAAG,MACxC,gBACA,eACF,CAAC,CAAC;CACA,OAAgB;;;;CAKhB;CAEA,YAAY,SAAkB,QAAuC;EACnE,MAAM,WAAW,uBAAuB;EACxC,KAAK,aAAa,QAAQ;EAC1B,eAAe,MAAM,KAAK;CAC5B;;;;;;;;;;CAWA,OAAO,YACL,SACA,YACmB;EACnB,IAAI,UAAU;EACd,MAAM,WAAW,QAAQ,QAAQ;EACjC,IAAI,UACF,WAAW,eAAe,OAAO,QAAQ,EAAE;EAE7C,IAAI,QAAQ,SACV,WAAW,KAAK,QAAQ;EAE1B,OAAO,IAAI,kBAAkB,SAAS,EAAE,WAAW,CAAC;CACtD;AACF"}
|
|
@@ -139,7 +139,7 @@ var BaseLangChain = class extends require_base.Runnable {
|
|
|
139
139
|
this.callbacks = params.callbacks;
|
|
140
140
|
this.tags = params.tags ?? [];
|
|
141
141
|
this.metadata = params.metadata ?? {};
|
|
142
|
-
this._addVersion("@langchain/core", "1.3.
|
|
142
|
+
this._addVersion("@langchain/core", "1.3.7");
|
|
143
143
|
}
|
|
144
144
|
_addVersion(pkg, version) {
|
|
145
145
|
const existing = this.metadata?.versions;
|
|
@@ -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.3.
|
|
141
|
+
this._addVersion("@langchain/core", "1.3.7");
|
|
142
142
|
}
|
|
143
143
|
_addVersion(pkg, version) {
|
|
144
144
|
const existing = this.metadata?.versions;
|
|
@@ -173,6 +173,7 @@ function convertToV1FromAnthropicInput(content) {
|
|
|
173
173
|
* ```
|
|
174
174
|
*/
|
|
175
175
|
function convertToV1FromAnthropicMessage(message) {
|
|
176
|
+
let hasRefusal = false;
|
|
176
177
|
function* iterateContent() {
|
|
177
178
|
const content = typeof message.content === "string" ? [{
|
|
178
179
|
type: "text",
|
|
@@ -333,6 +334,11 @@ function convertToV1FromAnthropicMessage(message) {
|
|
|
333
334
|
};
|
|
334
335
|
continue;
|
|
335
336
|
} else {
|
|
337
|
+
if (require_utils._isContentBlock(block, "refusal") && require_utils._isString(block.refusal)) {
|
|
338
|
+
hasRefusal = true;
|
|
339
|
+
yield block;
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
336
342
|
const stdBlock = convertToV1FromAnthropicContentBlock(block);
|
|
337
343
|
if (stdBlock) {
|
|
338
344
|
yield stdBlock;
|
|
@@ -344,9 +350,21 @@ function convertToV1FromAnthropicMessage(message) {
|
|
|
344
350
|
value: block
|
|
345
351
|
};
|
|
346
352
|
}
|
|
353
|
+
const stopFields = message.response_metadata.stop_reason !== void 0 ? message.response_metadata : message.additional_kwargs;
|
|
354
|
+
if (!hasRefusal && stopFields.stop_reason === "refusal") yield refusalFromStopDetails(stopFields.stop_details);
|
|
347
355
|
}
|
|
348
356
|
return Array.from(iterateContent());
|
|
349
357
|
}
|
|
358
|
+
function refusalFromStopDetails(details) {
|
|
359
|
+
const stopDetails = require_utils._isObject(details) ? details : {};
|
|
360
|
+
const explanation = stopDetails.explanation;
|
|
361
|
+
const category = stopDetails.category;
|
|
362
|
+
return {
|
|
363
|
+
type: "refusal",
|
|
364
|
+
refusal: require_utils._isString(explanation) ? explanation : "",
|
|
365
|
+
...require_utils._isString(category) ? { extras: { category } } : {}
|
|
366
|
+
};
|
|
367
|
+
}
|
|
350
368
|
const ChatAnthropicTranslator = {
|
|
351
369
|
translateContent: convertToV1FromAnthropicMessage,
|
|
352
370
|
translateContentChunk: convertToV1FromAnthropicMessage
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.cjs","names":["_isString","_isNumber","_isContentBlock","_isObject","_isArray","iife","safeParseJson"],"sources":["../../../src/messages/block_translators/anthropic.ts"],"sourcesContent":["import type { StandardContentBlockTranslator } from \"./index.js\";\nimport type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { BaseMessage, BaseMessageChunk } from \"../base.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isNumber,\n _isObject,\n _isString,\n safeParseJson,\n iife,\n} from \"./utils.js\";\n\nfunction convertAnthropicAnnotation(\n citation: ContentBlock\n): ContentBlock.Citation | undefined {\n if (\n citation.type === \"char_location\" &&\n _isString(citation.document_title) &&\n _isNumber(citation.start_char_index) &&\n _isNumber(citation.end_char_index) &&\n _isString(citation.cited_text)\n ) {\n const {\n document_title,\n start_char_index,\n end_char_index,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"char\",\n title: document_title ?? undefined,\n startIndex: start_char_index,\n endIndex: end_char_index,\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"page_location\" &&\n _isString(citation.document_title) &&\n _isNumber(citation.start_page_number) &&\n _isNumber(citation.end_page_number) &&\n _isString(citation.cited_text)\n ) {\n const {\n document_title,\n start_page_number,\n end_page_number,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"page\",\n title: document_title ?? undefined,\n startIndex: start_page_number,\n endIndex: end_page_number,\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"content_block_location\" &&\n _isString(citation.document_title) &&\n _isNumber(citation.start_block_index) &&\n _isNumber(citation.end_block_index) &&\n _isString(citation.cited_text)\n ) {\n const {\n document_title,\n start_block_index,\n end_block_index,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"block\",\n title: document_title ?? undefined,\n startIndex: start_block_index,\n endIndex: end_block_index,\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"web_search_result_location\" &&\n _isString(citation.url) &&\n _isString(citation.title) &&\n _isString(citation.encrypted_index) &&\n _isString(citation.cited_text)\n ) {\n const { url, title, encrypted_index, cited_text, ...rest } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"url\",\n url,\n title,\n startIndex: Number(encrypted_index),\n endIndex: Number(encrypted_index),\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"search_result_location\" &&\n _isString(citation.source) &&\n _isString(citation.title) &&\n _isNumber(citation.start_block_index) &&\n _isNumber(citation.end_block_index) &&\n _isString(citation.cited_text)\n ) {\n const {\n source,\n title,\n start_block_index,\n end_block_index,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"search\",\n url: source,\n title: title ?? undefined,\n startIndex: start_block_index,\n endIndex: end_block_index,\n citedText: cited_text,\n };\n }\n return undefined;\n}\n\n/**\n * Converts an Anthropic content block to a standard V1 content block.\n *\n * This function handles the conversion of Anthropic-specific content blocks\n * (document and image blocks) to the standardized V1 format. It supports\n * various source types including base64 data, URLs, file IDs, and text data.\n *\n * @param block - The Anthropic content block to convert\n * @returns A standard V1 content block if conversion is successful, undefined otherwise\n *\n * @example\n * ```typescript\n * const anthropicBlock = {\n * type: \"image\",\n * source: {\n * type: \"base64\",\n * media_type: \"image/png\",\n * data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==\"\n * }\n * };\n *\n * const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock);\n * // Returns: { type: \"image\", mimeType: \"image/png\", data: \"...\" }\n * ```\n */\nexport function convertToV1FromAnthropicContentBlock(\n block: ContentBlock\n): ContentBlock.Standard | undefined {\n if (\n _isContentBlock(block, \"document\") &&\n _isObject(block.source) &&\n \"type\" in block.source\n ) {\n if (\n block.source.type === \"base64\" &&\n _isString(block.source.media_type) &&\n _isString(block.source.data)\n ) {\n return {\n type: \"file\",\n mimeType: block.source.media_type,\n data: block.source.data,\n };\n } else if (block.source.type === \"url\" && _isString(block.source.url)) {\n return {\n type: \"file\",\n url: block.source.url,\n };\n } else if (\n block.source.type === \"file\" &&\n _isString(block.source.file_id)\n ) {\n return {\n type: \"file\",\n fileId: block.source.file_id,\n };\n } else if (block.source.type === \"text\" && _isString(block.source.data)) {\n return {\n type: \"file\",\n mimeType: String(block.source.media_type ?? \"text/plain\"),\n data: block.source.data,\n };\n }\n } else if (\n _isContentBlock(block, \"image\") &&\n _isObject(block.source) &&\n \"type\" in block.source\n ) {\n if (\n block.source.type === \"base64\" &&\n _isString(block.source.media_type) &&\n _isString(block.source.data)\n ) {\n return {\n type: \"image\",\n mimeType: block.source.media_type,\n data: block.source.data,\n };\n } else if (block.source.type === \"url\" && _isString(block.source.url)) {\n return {\n type: \"image\",\n url: block.source.url,\n };\n } else if (\n block.source.type === \"file\" &&\n _isString(block.source.file_id)\n ) {\n return {\n type: \"image\",\n fileId: block.source.file_id,\n };\n }\n }\n return undefined;\n}\n\n/**\n * Converts an array of content blocks from Anthropic format to v1 standard format.\n *\n * This function processes each content block in the input array, attempting to convert\n * Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.)\n * to the standardized v1 content block format. If a block cannot be converted, it is\n * passed through as-is with a type assertion to ContentBlock.Standard.\n *\n * @param content - Array of content blocks in Anthropic format to be converted\n * @returns Array of content blocks in v1 standard format\n */\nexport function convertToV1FromAnthropicInput(\n content: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n for (const block of content) {\n const stdBlock = convertToV1FromAnthropicContentBlock(block);\n if (stdBlock) {\n yield stdBlock;\n } else {\n yield block as ContentBlock.Standard;\n }\n }\n }\n return Array.from(iterateContent());\n}\n\n/**\n * Converts an Anthropic AI message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing Anthropic-specific content blocks\n * and converts them to the standardized v1 content block format.\n *\n * @param message - The AI message containing Anthropic-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"thinking\", text: \"Let me think about this...\" },\n * { type: \"tool_use\", id: \"123\", name: \"calculator\", input: { a: 1, b: 2 } }\n * ]);\n *\n * const standardBlocks = convertToV1FromAnthropicMessage(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromAnthropicMessage(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n // TextBlock\n if (_isContentBlock(block, \"text\") && _isString(block.text)) {\n const { text, citations, ...rest } = block;\n if (_isArray(citations) && citations.length) {\n const _citations = citations.reduce<ContentBlock.Citation[]>(\n (acc, item) => {\n const citation = convertAnthropicAnnotation(item as ContentBlock);\n if (citation) {\n return [...acc, citation];\n }\n return acc;\n },\n []\n );\n yield {\n ...rest,\n type: \"text\",\n text,\n annotations: _citations,\n };\n continue;\n } else {\n yield {\n ...rest,\n type: \"text\",\n text,\n };\n continue;\n }\n }\n // ThinkingBlock\n else if (\n _isContentBlock(block, \"thinking\") &&\n _isString(block.thinking)\n ) {\n const { thinking, signature, ...rest } = block;\n yield {\n ...rest,\n type: \"reasoning\",\n reasoning: thinking,\n signature,\n };\n continue;\n }\n // RedactedThinkingBlock\n else if (_isContentBlock(block, \"redacted_thinking\")) {\n yield { type: \"non_standard\", value: block };\n continue;\n }\n // ToolUseBlock\n else if (\n _isContentBlock(block, \"tool_use\") &&\n _isString(block.name) &&\n _isString(block.id)\n ) {\n yield {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: block.input,\n };\n continue;\n }\n // message chunks can have input_json_delta contents\n else if (_isContentBlock(block, \"input_json_delta\")) {\n if (_isAIMessageChunk(message) && message.tool_call_chunks?.length) {\n const tool_call_chunk = message.tool_call_chunks[0];\n yield {\n type: \"tool_call_chunk\",\n id: tool_call_chunk.id,\n name: tool_call_chunk.name,\n args: tool_call_chunk.args,\n index: tool_call_chunk.index,\n };\n continue;\n }\n }\n // ServerToolUseBlock\n else if (\n _isContentBlock(block, \"server_tool_use\") &&\n _isString(block.name) &&\n _isString(block.id)\n ) {\n const { name, id } = block;\n if (name === \"web_search\") {\n const query = iife(() => {\n if (typeof block.input === \"string\") {\n return block.input;\n } else if (_isObject(block.input) && _isString(block.input.query)) {\n return block.input.query;\n } else if (_isString(block.partial_json)) {\n const json = safeParseJson<{ query?: string }>(\n block.partial_json\n );\n if (json?.query) {\n return json.query;\n }\n }\n return \"\";\n });\n yield {\n id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: { query },\n };\n continue;\n } else if (block.name === \"code_execution\") {\n const code = iife(() => {\n if (typeof block.input === \"string\") {\n return block.input;\n } else if (_isObject(block.input) && _isString(block.input.code)) {\n return block.input.code;\n } else if (_isString(block.partial_json)) {\n const json = safeParseJson<{ code?: string }>(block.partial_json);\n if (json?.code) {\n return json.code;\n }\n }\n return \"\";\n });\n yield {\n id,\n type: \"server_tool_call\",\n name: \"code_execution\",\n args: { code },\n };\n continue;\n }\n }\n // WebSearchToolResultBlock\n else if (\n _isContentBlock(block, \"web_search_tool_result\") &&\n _isString(block.tool_use_id) &&\n _isArray(block.content)\n ) {\n const { content, tool_use_id } = block;\n const urls = content.reduce<string[]>((acc, content) => {\n if (_isContentBlock(content, \"web_search_result\")) {\n return [...acc, content.url as string];\n }\n return acc;\n }, []);\n yield {\n type: \"server_tool_call_result\",\n name: \"web_search\",\n toolCallId: tool_use_id,\n status: \"success\",\n output: {\n urls,\n },\n };\n continue;\n }\n // CodeExecutionToolResultBlock\n else if (\n _isContentBlock(block, \"code_execution_tool_result\") &&\n _isString(block.tool_use_id) &&\n _isObject(block.content)\n ) {\n yield {\n type: \"server_tool_call_result\",\n name: \"code_execution\",\n toolCallId: block.tool_use_id,\n status: \"success\",\n output: block.content,\n };\n continue;\n }\n // MCPToolUseBlock\n else if (_isContentBlock(block, \"mcp_tool_use\")) {\n yield {\n id: block.id,\n type: \"server_tool_call\",\n name: \"mcp_tool_use\",\n args: block.input,\n };\n continue;\n }\n // MCPToolResultBlock\n else if (\n _isContentBlock(block, \"mcp_tool_result\") &&\n _isString(block.tool_use_id) &&\n _isObject(block.content)\n ) {\n yield {\n type: \"server_tool_call_result\",\n name: \"mcp_tool_use\",\n toolCallId: block.tool_use_id,\n status: \"success\",\n output: block.content,\n };\n continue;\n }\n // ContainerUploadBlock\n else if (_isContentBlock(block, \"container_upload\")) {\n yield {\n type: \"server_tool_call\",\n name: \"container_upload\",\n args: block.input,\n };\n continue;\n }\n // SearchResultBlockParam\n else if (_isContentBlock(block, \"search_result\")) {\n yield { id: block.id, type: \"non_standard\", value: block };\n continue;\n }\n // ToolResultBlockParam\n else if (_isContentBlock(block, \"tool_result\")) {\n yield { id: block.id, type: \"non_standard\", value: block };\n continue;\n } else {\n // For all other blocks, we try to convert them to a standard block\n const stdBlock = convertToV1FromAnthropicContentBlock(block);\n if (stdBlock) {\n yield stdBlock;\n continue;\n }\n }\n yield { type: \"non_standard\", value: block };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatAnthropicTranslator: StandardContentBlockTranslator = {\n translateContent: convertToV1FromAnthropicMessage,\n translateContentChunk: convertToV1FromAnthropicMessage,\n};\n\nfunction _isAIMessageChunk(message: unknown): message is AIMessageChunk {\n return (\n typeof (message as BaseMessage)?._getType === \"function\" &&\n typeof (message as BaseMessageChunk).concat === \"function\" &&\n (message as BaseMessageChunk)._getType() === \"ai\"\n );\n}\n"],"mappings":";;AAcA,SAAS,2BACP,UACmC;CACnC,IACE,SAAS,SAAS,mBAClBA,cAAAA,UAAU,SAAS,cAAc,KACjCC,cAAAA,UAAU,SAAS,gBAAgB,KACnCA,cAAAA,UAAU,SAAS,cAAc,KACjCD,cAAAA,UAAU,SAAS,UAAU,GAC7B;EACA,MAAM,EACJ,gBACA,kBACA,gBACA,YACA,GAAG,SACD;EACJ,OAAO;GACL,GAAG;GACH,MAAM;GACN,QAAQ;GACR,OAAO,kBAAkB,KAAA;GACzB,YAAY;GACZ,UAAU;GACV,WAAW;EACb;CACF;CACA,IACE,SAAS,SAAS,mBAClBA,cAAAA,UAAU,SAAS,cAAc,KACjCC,cAAAA,UAAU,SAAS,iBAAiB,KACpCA,cAAAA,UAAU,SAAS,eAAe,KAClCD,cAAAA,UAAU,SAAS,UAAU,GAC7B;EACA,MAAM,EACJ,gBACA,mBACA,iBACA,YACA,GAAG,SACD;EACJ,OAAO;GACL,GAAG;GACH,MAAM;GACN,QAAQ;GACR,OAAO,kBAAkB,KAAA;GACzB,YAAY;GACZ,UAAU;GACV,WAAW;EACb;CACF;CACA,IACE,SAAS,SAAS,4BAClBA,cAAAA,UAAU,SAAS,cAAc,KACjCC,cAAAA,UAAU,SAAS,iBAAiB,KACpCA,cAAAA,UAAU,SAAS,eAAe,KAClCD,cAAAA,UAAU,SAAS,UAAU,GAC7B;EACA,MAAM,EACJ,gBACA,mBACA,iBACA,YACA,GAAG,SACD;EACJ,OAAO;GACL,GAAG;GACH,MAAM;GACN,QAAQ;GACR,OAAO,kBAAkB,KAAA;GACzB,YAAY;GACZ,UAAU;GACV,WAAW;EACb;CACF;CACA,IACE,SAAS,SAAS,gCAClBA,cAAAA,UA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AA6C;CACtE,OACE,OAAQ,SAAyB,aAAa,cAC9C,OAAQ,QAA6B,WAAW,cAC/C,QAA6B,SAAS,MAAM;AAEjD"}
|
|
1
|
+
{"version":3,"file":"anthropic.cjs","names":["_isString","_isNumber","_isContentBlock","_isObject","_isArray","iife","safeParseJson"],"sources":["../../../src/messages/block_translators/anthropic.ts"],"sourcesContent":["import type { StandardContentBlockTranslator } from \"./index.js\";\nimport type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { BaseMessage, BaseMessageChunk } from \"../base.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isNumber,\n _isObject,\n _isString,\n safeParseJson,\n iife,\n} from \"./utils.js\";\n\nfunction convertAnthropicAnnotation(\n citation: ContentBlock\n): ContentBlock.Citation | undefined {\n if (\n citation.type === \"char_location\" &&\n _isString(citation.document_title) &&\n _isNumber(citation.start_char_index) &&\n _isNumber(citation.end_char_index) &&\n _isString(citation.cited_text)\n ) {\n const {\n document_title,\n start_char_index,\n end_char_index,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"char\",\n title: document_title ?? undefined,\n startIndex: start_char_index,\n endIndex: end_char_index,\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"page_location\" &&\n _isString(citation.document_title) &&\n _isNumber(citation.start_page_number) &&\n _isNumber(citation.end_page_number) &&\n _isString(citation.cited_text)\n ) {\n const {\n document_title,\n start_page_number,\n end_page_number,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"page\",\n title: document_title ?? undefined,\n startIndex: start_page_number,\n endIndex: end_page_number,\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"content_block_location\" &&\n _isString(citation.document_title) &&\n _isNumber(citation.start_block_index) &&\n _isNumber(citation.end_block_index) &&\n _isString(citation.cited_text)\n ) {\n const {\n document_title,\n start_block_index,\n end_block_index,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"block\",\n title: document_title ?? undefined,\n startIndex: start_block_index,\n endIndex: end_block_index,\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"web_search_result_location\" &&\n _isString(citation.url) &&\n _isString(citation.title) &&\n _isString(citation.encrypted_index) &&\n _isString(citation.cited_text)\n ) {\n const { url, title, encrypted_index, cited_text, ...rest } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"url\",\n url,\n title,\n startIndex: Number(encrypted_index),\n endIndex: Number(encrypted_index),\n citedText: cited_text,\n };\n }\n if (\n citation.type === \"search_result_location\" &&\n _isString(citation.source) &&\n _isString(citation.title) &&\n _isNumber(citation.start_block_index) &&\n _isNumber(citation.end_block_index) &&\n _isString(citation.cited_text)\n ) {\n const {\n source,\n title,\n start_block_index,\n end_block_index,\n cited_text,\n ...rest\n } = citation;\n return {\n ...rest,\n type: \"citation\",\n source: \"search\",\n url: source,\n title: title ?? undefined,\n startIndex: start_block_index,\n endIndex: end_block_index,\n citedText: cited_text,\n };\n }\n return undefined;\n}\n\n/**\n * Converts an Anthropic content block to a standard V1 content block.\n *\n * This function handles the conversion of Anthropic-specific content blocks\n * (document and image blocks) to the standardized V1 format. It supports\n * various source types including base64 data, URLs, file IDs, and text data.\n *\n * @param block - The Anthropic content block to convert\n * @returns A standard V1 content block if conversion is successful, undefined otherwise\n *\n * @example\n * ```typescript\n * const anthropicBlock = {\n * type: \"image\",\n * source: {\n * type: \"base64\",\n * media_type: \"image/png\",\n * data: \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==\"\n * }\n * };\n *\n * const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock);\n * // Returns: { type: \"image\", mimeType: \"image/png\", data: \"...\" }\n * ```\n */\nexport function convertToV1FromAnthropicContentBlock(\n block: ContentBlock\n): ContentBlock.Standard | undefined {\n if (\n _isContentBlock(block, \"document\") &&\n _isObject(block.source) &&\n \"type\" in block.source\n ) {\n if (\n block.source.type === \"base64\" &&\n _isString(block.source.media_type) &&\n _isString(block.source.data)\n ) {\n return {\n type: \"file\",\n mimeType: block.source.media_type,\n data: block.source.data,\n };\n } else if (block.source.type === \"url\" && _isString(block.source.url)) {\n return {\n type: \"file\",\n url: block.source.url,\n };\n } else if (\n block.source.type === \"file\" &&\n _isString(block.source.file_id)\n ) {\n return {\n type: \"file\",\n fileId: block.source.file_id,\n };\n } else if (block.source.type === \"text\" && _isString(block.source.data)) {\n return {\n type: \"file\",\n mimeType: String(block.source.media_type ?? \"text/plain\"),\n data: block.source.data,\n };\n }\n } else if (\n _isContentBlock(block, \"image\") &&\n _isObject(block.source) &&\n \"type\" in block.source\n ) {\n if (\n block.source.type === \"base64\" &&\n _isString(block.source.media_type) &&\n _isString(block.source.data)\n ) {\n return {\n type: \"image\",\n mimeType: block.source.media_type,\n data: block.source.data,\n };\n } else if (block.source.type === \"url\" && _isString(block.source.url)) {\n return {\n type: \"image\",\n url: block.source.url,\n };\n } else if (\n block.source.type === \"file\" &&\n _isString(block.source.file_id)\n ) {\n return {\n type: \"image\",\n fileId: block.source.file_id,\n };\n }\n }\n return undefined;\n}\n\n/**\n * Converts an array of content blocks from Anthropic format to v1 standard format.\n *\n * This function processes each content block in the input array, attempting to convert\n * Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.)\n * to the standardized v1 content block format. If a block cannot be converted, it is\n * passed through as-is with a type assertion to ContentBlock.Standard.\n *\n * @param content - Array of content blocks in Anthropic format to be converted\n * @returns Array of content blocks in v1 standard format\n */\nexport function convertToV1FromAnthropicInput(\n content: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n for (const block of content) {\n const stdBlock = convertToV1FromAnthropicContentBlock(block);\n if (stdBlock) {\n yield stdBlock;\n } else {\n yield block as ContentBlock.Standard;\n }\n }\n }\n return Array.from(iterateContent());\n}\n\n/**\n * Converts an Anthropic AI message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing Anthropic-specific content blocks\n * and converts them to the standardized v1 content block format.\n *\n * @param message - The AI message containing Anthropic-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"thinking\", text: \"Let me think about this...\" },\n * { type: \"tool_use\", id: \"123\", name: \"calculator\", input: { a: 1, b: 2 } }\n * ]);\n *\n * const standardBlocks = convertToV1FromAnthropicMessage(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromAnthropicMessage(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n let hasRefusal = false;\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n // TextBlock\n if (_isContentBlock(block, \"text\") && _isString(block.text)) {\n const { text, citations, ...rest } = block;\n if (_isArray(citations) && citations.length) {\n const _citations = citations.reduce<ContentBlock.Citation[]>(\n (acc, item) => {\n const citation = convertAnthropicAnnotation(item as ContentBlock);\n if (citation) {\n return [...acc, citation];\n }\n return acc;\n },\n []\n );\n yield {\n ...rest,\n type: \"text\",\n text,\n annotations: _citations,\n };\n continue;\n } else {\n yield {\n ...rest,\n type: \"text\",\n text,\n };\n continue;\n }\n }\n // ThinkingBlock\n else if (\n _isContentBlock(block, \"thinking\") &&\n _isString(block.thinking)\n ) {\n const { thinking, signature, ...rest } = block;\n yield {\n ...rest,\n type: \"reasoning\",\n reasoning: thinking,\n signature,\n };\n continue;\n }\n // RedactedThinkingBlock\n else if (_isContentBlock(block, \"redacted_thinking\")) {\n yield { type: \"non_standard\", value: block };\n continue;\n }\n // ToolUseBlock\n else if (\n _isContentBlock(block, \"tool_use\") &&\n _isString(block.name) &&\n _isString(block.id)\n ) {\n yield {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: block.input,\n };\n continue;\n }\n // message chunks can have input_json_delta contents\n else if (_isContentBlock(block, \"input_json_delta\")) {\n if (_isAIMessageChunk(message) && message.tool_call_chunks?.length) {\n const tool_call_chunk = message.tool_call_chunks[0];\n yield {\n type: \"tool_call_chunk\",\n id: tool_call_chunk.id,\n name: tool_call_chunk.name,\n args: tool_call_chunk.args,\n index: tool_call_chunk.index,\n };\n continue;\n }\n }\n // ServerToolUseBlock\n else if (\n _isContentBlock(block, \"server_tool_use\") &&\n _isString(block.name) &&\n _isString(block.id)\n ) {\n const { name, id } = block;\n if (name === \"web_search\") {\n const query = iife(() => {\n if (typeof block.input === \"string\") {\n return block.input;\n } else if (_isObject(block.input) && _isString(block.input.query)) {\n return block.input.query;\n } else if (_isString(block.partial_json)) {\n const json = safeParseJson<{ query?: string }>(\n block.partial_json\n );\n if (json?.query) {\n return json.query;\n }\n }\n return \"\";\n });\n yield {\n id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: { query },\n };\n continue;\n } else if (block.name === \"code_execution\") {\n const code = iife(() => {\n if (typeof block.input === \"string\") {\n return block.input;\n } else if (_isObject(block.input) && _isString(block.input.code)) {\n return block.input.code;\n } else if (_isString(block.partial_json)) {\n const json = safeParseJson<{ code?: string }>(block.partial_json);\n if (json?.code) {\n return json.code;\n }\n }\n return \"\";\n });\n yield {\n id,\n type: \"server_tool_call\",\n name: \"code_execution\",\n args: { code },\n };\n continue;\n }\n }\n // WebSearchToolResultBlock\n else if (\n _isContentBlock(block, \"web_search_tool_result\") &&\n _isString(block.tool_use_id) &&\n _isArray(block.content)\n ) {\n const { content, tool_use_id } = block;\n const urls = content.reduce<string[]>((acc, content) => {\n if (_isContentBlock(content, \"web_search_result\")) {\n return [...acc, content.url as string];\n }\n return acc;\n }, []);\n yield {\n type: \"server_tool_call_result\",\n name: \"web_search\",\n toolCallId: tool_use_id,\n status: \"success\",\n output: {\n urls,\n },\n };\n continue;\n }\n // CodeExecutionToolResultBlock\n else if (\n _isContentBlock(block, \"code_execution_tool_result\") &&\n _isString(block.tool_use_id) &&\n _isObject(block.content)\n ) {\n yield {\n type: \"server_tool_call_result\",\n name: \"code_execution\",\n toolCallId: block.tool_use_id,\n status: \"success\",\n output: block.content,\n };\n continue;\n }\n // MCPToolUseBlock\n else if (_isContentBlock(block, \"mcp_tool_use\")) {\n yield {\n id: block.id,\n type: \"server_tool_call\",\n name: \"mcp_tool_use\",\n args: block.input,\n };\n continue;\n }\n // MCPToolResultBlock\n else if (\n _isContentBlock(block, \"mcp_tool_result\") &&\n _isString(block.tool_use_id) &&\n _isObject(block.content)\n ) {\n yield {\n type: \"server_tool_call_result\",\n name: \"mcp_tool_use\",\n toolCallId: block.tool_use_id,\n status: \"success\",\n output: block.content,\n };\n continue;\n }\n // ContainerUploadBlock\n else if (_isContentBlock(block, \"container_upload\")) {\n yield {\n type: \"server_tool_call\",\n name: \"container_upload\",\n args: block.input,\n };\n continue;\n }\n // SearchResultBlockParam\n else if (_isContentBlock(block, \"search_result\")) {\n yield { id: block.id, type: \"non_standard\", value: block };\n continue;\n }\n // ToolResultBlockParam\n else if (_isContentBlock(block, \"tool_result\")) {\n yield { id: block.id, type: \"non_standard\", value: block };\n continue;\n } else {\n // Anthropic has no refusal part; this is a stored standard block.\n if (_isContentBlock(block, \"refusal\") && _isString(block.refusal)) {\n hasRefusal = true;\n yield block as ContentBlock.Refusal;\n continue;\n }\n // For all other blocks, we try to convert them to a standard block\n const stdBlock = convertToV1FromAnthropicContentBlock(block);\n if (stdBlock) {\n yield stdBlock;\n continue;\n }\n }\n yield { type: \"non_standard\", value: block };\n }\n // Streamed chunks carry `message_delta` fields in `additional_kwargs`.\n const stopFields =\n message.response_metadata.stop_reason !== undefined\n ? message.response_metadata\n : message.additional_kwargs;\n if (!hasRefusal && stopFields.stop_reason === \"refusal\") {\n yield refusalFromStopDetails(stopFields.stop_details);\n }\n }\n return Array.from(iterateContent());\n}\n\nfunction refusalFromStopDetails(details: unknown): ContentBlock.Refusal {\n const stopDetails = _isObject(details) ? details : {};\n const explanation = stopDetails.explanation;\n const category = stopDetails.category;\n return {\n type: \"refusal\",\n refusal: _isString(explanation) ? explanation : \"\",\n ...(_isString(category) ? { extras: { category } } : {}),\n };\n}\n\nexport const ChatAnthropicTranslator: StandardContentBlockTranslator = {\n translateContent: convertToV1FromAnthropicMessage,\n translateContentChunk: convertToV1FromAnthropicMessage,\n};\n\nfunction _isAIMessageChunk(message: unknown): message is AIMessageChunk {\n return (\n typeof (message as BaseMessage)?._getType === \"function\" &&\n typeof (message as BaseMessageChunk).concat === \"function\" &&\n (message as BaseMessageChunk)._getType() === \"ai\"\n );\n}\n"],"mappings":";;AAcA,SAAS,2BACP,UACmC;CACnC,IACE,SAAS,SAAS,mBAClBA,cAAAA,UAAU,SAAS,cAAc,KACjCC,cAAAA,UAAU,SAAS,gBAAgB,KACnCA,cAAAA,UAAU,SAAS,cAAc,KACjCD,cAAAA,UAAU,SAAS,UAAU,GAC7B;EACA,MAAM,EACJ,gBACA,kBACA,gBACA,YACA,GAAG,SACD;EACJ,OAAO;GACL,GAAG;GACH,MAAM;GACN,QAAQ;GACR,OAAO,kBAAkB,KAAA;GACzB,YAAY;GACZ,UAAU;GACV,WAAW;EACb;CACF;CACA,IACE,SAAS,SAAS,mBAClBA,cAAAA,UAAU,SAAS,cAAc,KACjCC,cAAAA,UAAU,SAAS,iBAAiB,KACpCA,cAAAA,UAAU,SAAS,eAAe,KAClCD,cAAAA,UAAU,SAAS,UAAU,GAC7B;EACA,MAAM,EACJ,gBACA,mBACA,iBACA,YACA,GAAG,SACD;EACJ,OAAO;GACL,GAAG;GACH,MAAM;GACN,QAAQ;GACR,OAAO,kBAAkB,KAAA;GACzB,YAAY;GACZ,UAAU;GACV,WAAW;EACb;CACF;CACA,IACE,SAAS,SAAS,4BAClBA,cAAAA,UAA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AO,aAAa,GAAG;IAC9C,MAAM;KAAE,IAAI,MAAM;KAAI,MAAM;KAAgB,OAAO;IAAM;IACzD;GACF,OAAO;IAEL,IAAIA,cAAAA,gBAAgB,OAAO,SAAS,KAAKF,cAAAA,UAAU,MAAM,OAAO,GAAG;KACjE,aAAa;KACb,MAAM;KACN;IACF;IAEA,MAAM,WAAW,qCAAqC,KAAK;IAC3D,IAAI,UAAU;KACZ,MAAM;KACN;IACF;GACF;GACA,MAAM;IAAE,MAAM;IAAgB,OAAO;GAAM;EAC7C;EAEA,MAAM,aACJ,QAAQ,kBAAkB,gBAAgB,KAAA,IACtC,QAAQ,oBACR,QAAQ;EACd,IAAI,CAAC,cAAc,WAAW,gBAAgB,WAC5C,MAAM,uBAAuB,WAAW,YAAY;CAExD;CACA,OAAO,MAAM,KAAK,eAAe,CAAC;AACpC;AAEA,SAAS,uBAAuB,SAAwC;CACtE,MAAM,cAAcG,cAAAA,UAAU,OAAO,IAAI,UAAU,CAAC;CACpD,MAAM,cAAc,YAAY;CAChC,MAAM,WAAW,YAAY;CAC7B,OAAO;EACL,MAAM;EACN,SAASH,cAAAA,UAAU,WAAW,IAAI,cAAc;EAChD,GAAIA,cAAAA,UAAU,QAAQ,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC;CACxD;AACF;AAEA,MAAa,0BAA0D;CACrE,kBAAkB;CAClB,uBAAuB;AACzB;AAEA,SAAS,kBAAkB,SAA6C;CACtE,OACE,OAAQ,SAAyB,aAAa,cAC9C,OAAQ,QAA6B,WAAW,cAC/C,QAA6B,SAAS,MAAM;AAEjD"}
|
|
@@ -173,6 +173,7 @@ function convertToV1FromAnthropicInput(content) {
|
|
|
173
173
|
* ```
|
|
174
174
|
*/
|
|
175
175
|
function convertToV1FromAnthropicMessage(message) {
|
|
176
|
+
let hasRefusal = false;
|
|
176
177
|
function* iterateContent() {
|
|
177
178
|
const content = typeof message.content === "string" ? [{
|
|
178
179
|
type: "text",
|
|
@@ -333,6 +334,11 @@ function convertToV1FromAnthropicMessage(message) {
|
|
|
333
334
|
};
|
|
334
335
|
continue;
|
|
335
336
|
} else {
|
|
337
|
+
if (_isContentBlock(block, "refusal") && _isString(block.refusal)) {
|
|
338
|
+
hasRefusal = true;
|
|
339
|
+
yield block;
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
336
342
|
const stdBlock = convertToV1FromAnthropicContentBlock(block);
|
|
337
343
|
if (stdBlock) {
|
|
338
344
|
yield stdBlock;
|
|
@@ -344,9 +350,21 @@ function convertToV1FromAnthropicMessage(message) {
|
|
|
344
350
|
value: block
|
|
345
351
|
};
|
|
346
352
|
}
|
|
353
|
+
const stopFields = message.response_metadata.stop_reason !== void 0 ? message.response_metadata : message.additional_kwargs;
|
|
354
|
+
if (!hasRefusal && stopFields.stop_reason === "refusal") yield refusalFromStopDetails(stopFields.stop_details);
|
|
347
355
|
}
|
|
348
356
|
return Array.from(iterateContent());
|
|
349
357
|
}
|
|
358
|
+
function refusalFromStopDetails(details) {
|
|
359
|
+
const stopDetails = _isObject(details) ? details : {};
|
|
360
|
+
const explanation = stopDetails.explanation;
|
|
361
|
+
const category = stopDetails.category;
|
|
362
|
+
return {
|
|
363
|
+
type: "refusal",
|
|
364
|
+
refusal: _isString(explanation) ? explanation : "",
|
|
365
|
+
..._isString(category) ? { extras: { category } } : {}
|
|
366
|
+
};
|
|
367
|
+
}
|
|
350
368
|
const ChatAnthropicTranslator = {
|
|
351
369
|
translateContent: convertToV1FromAnthropicMessage,
|
|
352
370
|
translateContentChunk: convertToV1FromAnthropicMessage
|