@langchain/core 1.2.9 → 1.2.11
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 +20 -0
- package/dist/_virtual/_rolldown/runtime.cjs +1 -1
- package/dist/callbacks/dispatch/index.cjs +2 -1
- package/dist/callbacks/dispatch/index.cjs.map +1 -1
- package/dist/callbacks/dispatch/index.js +2 -1
- package/dist/callbacks/dispatch/index.js.map +1 -1
- package/dist/indexing/base.cjs +10 -6
- package/dist/indexing/base.cjs.map +1 -1
- package/dist/indexing/base.js +10 -6
- package/dist/indexing/base.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs +22 -17
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.d.cts.map +1 -1
- package/dist/language_models/chat_models.d.ts.map +1 -1
- package/dist/language_models/chat_models.js +23 -18
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/stream.cjs +0 -2
- package/dist/language_models/stream.cjs.map +1 -1
- package/dist/language_models/stream.js +0 -2
- package/dist/language_models/stream.js.map +1 -1
- package/dist/load/index.cjs +7 -5
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.js +7 -5
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +2 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js +2 -1
- package/dist/load/serializable.js.map +1 -1
- package/dist/load/validation.cjs +4 -3
- package/dist/load/validation.cjs.map +1 -1
- package/dist/load/validation.js +4 -3
- package/dist/load/validation.js.map +1 -1
- package/dist/messages/base.cjs +13 -18
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js +13 -18
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/block_translators/anthropic.cjs.map +1 -1
- package/dist/messages/block_translators/anthropic.js.map +1 -1
- package/dist/messages/block_translators/google.cjs +10 -9
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js +10 -9
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/messages/block_translators/google_vertexai.cjs +14 -12
- package/dist/messages/block_translators/google_vertexai.cjs.map +1 -1
- package/dist/messages/block_translators/google_vertexai.js +14 -12
- package/dist/messages/block_translators/google_vertexai.js.map +1 -1
- package/dist/messages/block_translators/openai.cjs +212 -164
- package/dist/messages/block_translators/openai.cjs.map +1 -1
- package/dist/messages/block_translators/openai.js +212 -164
- package/dist/messages/block_translators/openai.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.d.cts.map +1 -1
- package/dist/messages/message.d.ts.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/messages/transformers.cjs +12 -8
- package/dist/messages/transformers.cjs.map +1 -1
- package/dist/messages/transformers.js +12 -8
- package/dist/messages/transformers.js.map +1 -1
- package/dist/output_parsers/transform.cjs.map +1 -1
- package/dist/prompts/chat.cjs +2 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js +2 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/few_shot.cjs +6 -4
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js +6 -4
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/image.cjs +2 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.js +2 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.d.cts.map +1 -1
- package/dist/prompts/prompt.d.ts.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs +2 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js +2 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js.map +1 -1
- package/dist/runnables/base.cjs +60 -40
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js +60 -40
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs +16 -12
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js +16 -12
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/config.cjs +28 -23
- package/dist/runnables/config.cjs.map +1 -1
- package/dist/runnables/config.js +28 -23
- package/dist/runnables/config.js.map +1 -1
- package/dist/runnables/graph.cjs +2 -1
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.js +2 -1
- package/dist/runnables/graph.js.map +1 -1
- package/dist/runnables/passthrough.cjs +8 -6
- package/dist/runnables/passthrough.cjs.map +1 -1
- package/dist/runnables/passthrough.js +8 -6
- package/dist/runnables/passthrough.js.map +1 -1
- package/dist/singletons/async_local_storage/context.cjs.map +1 -1
- package/dist/singletons/tracer.cjs +4 -1
- package/dist/singletons/tracer.cjs.map +1 -1
- package/dist/singletons/tracer.js +4 -1
- package/dist/singletons/tracer.js.map +1 -1
- package/dist/tools/index.cjs +22 -20
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js +22 -20
- package/dist/tools/index.js.map +1 -1
- package/dist/tracers/base.cjs +11 -10
- package/dist/tracers/base.cjs.map +1 -1
- package/dist/tracers/base.js +11 -10
- package/dist/tracers/base.js.map +1 -1
- package/dist/tracers/log_stream.cjs +7 -6
- package/dist/tracers/log_stream.cjs.map +1 -1
- package/dist/tracers/log_stream.js +7 -6
- package/dist/tracers/log_stream.js.map +1 -1
- package/dist/tracers/tracer_langchain.cjs.map +1 -1
- package/dist/utils/env.cjs.map +1 -1
- package/dist/utils/env.d.cts.map +1 -1
- package/dist/utils/env.d.ts.map +1 -1
- package/dist/utils/env.js.map +1 -1
- package/dist/utils/event_source_parse.cjs +1 -3
- package/dist/utils/event_source_parse.cjs.map +1 -1
- package/dist/utils/event_source_parse.js +1 -3
- package/dist/utils/event_source_parse.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs +4 -2
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js +4 -2
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/fast-json-patch/src/helpers.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/helpers.js.map +1 -1
- package/dist/utils/js-sha256/hash.cjs.map +1 -1
- package/dist/utils/js-sha256/hash.js.map +1 -1
- package/dist/utils/json_schema.cjs +4 -2
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.js +4 -2
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/sax-js/sax.cjs +41 -35
- package/dist/utils/sax-js/sax.cjs.map +1 -1
- package/dist/utils/sax-js/sax.js +41 -35
- package/dist/utils/sax-js/sax.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs +2 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js +2 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/tiktoken.cjs.map +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/bigint.cjs +9 -9
- package/dist/utils/zod-to-json-schema/parsers/bigint.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/bigint.js +9 -9
- package/dist/utils/zod-to-json-schema/parsers/bigint.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/date.cjs +1 -3
- package/dist/utils/zod-to-json-schema/parsers/date.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/date.js +1 -3
- package/dist/utils/zod-to-json-schema/parsers/date.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/number.cjs +9 -9
- package/dist/utils/zod-to-json-schema/parsers/number.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/number.js +9 -9
- package/dist/utils/zod-to-json-schema/parsers/number.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.cjs +3 -13
- package/dist/utils/zod-to-json-schema/parsers/string.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.js +3 -13
- package/dist/utils/zod-to-json-schema/parsers/string.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @langchain/core
|
|
2
2
|
|
|
3
|
+
## 1.2.11
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#11603](https://github.com/langchain-ai/langchainjs/pull/11603) [`fec9cd8`](https://github.com/langchain-ai/langchainjs/commit/fec9cd87b01976014dd549bd2cf7849aee89a566) Thanks [@thushanth-bengre-langchain](https://github.com/thushanth-bengre-langchain)! - fix(core): build streaming `llmOutput.tokenUsage` from the fully-accumulated chunk instead of whichever individual chunk's `usage_metadata` arrived last
|
|
8
|
+
|
|
9
|
+
Affects both core streaming paths — `.stream()`/`.streamEvents()` (`_streamIterator`) and `.invoke()`/`.generate()` when a streaming-preferring callback is attached (`_generateWithCache`'s `hasStreamingHandler` branch). Previously, `llmOutput.tokenUsage` was overwritten by each chunk in turn, so only the last chunk carrying `usage_metadata` won — correct for providers that emit one cumulative total on a final chunk, but wrong for providers (e.g. `@langchain/google`, `@langchain/anthropic`) that emit `usage_metadata` as a per-chunk delta across multiple chunks, where the values must be summed.
|
|
10
|
+
|
|
11
|
+
Note for provider authors: this assumes each streamed chunk's `usage_metadata` is either a per-chunk delta or appears only on a single final chunk. A provider that instead repeats a cumulative total on every chunk will now see it summed (and inflated) in `llmOutput.tokenUsage`, matching the existing behavior of the correctly-working `message.usage_metadata` field.
|
|
12
|
+
|
|
13
|
+
Also fixes `@langchain/google`'s `invoke({streaming: true})` path (no streaming-preferring callback attached), where `llmOutput` was never populated at all.
|
|
14
|
+
|
|
15
|
+
- [#11590](https://github.com/langchain-ai/langchainjs/pull/11590) [`ffebdc2`](https://github.com/langchain-ai/langchainjs/commit/ffebdc2f00f3290d19f85e5afd6a297920ae584c) Thanks [@thushanth-bengre-langchain](https://github.com/thushanth-bengre-langchain)! - Fix OpenAI Responses API replay under Zero Data Retention when a response contains more than one reasoning item, for both v0 and v1. In v0, the default replay path now reuses `response_metadata.output` directly, preserving every reasoning item's `id`/`encrypted_content` in original order. In v1, `AIMessage.contentBlocks` (`outputVersion: "v1"`) is fixed the same way. `additional_kwargs.reasoning` is unchanged.
|
|
16
|
+
|
|
17
|
+
## 1.2.10
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- [#10047](https://github.com/langchain-ai/langchainjs/pull/10047) [`ff1248f`](https://github.com/langchain-ai/langchainjs/commit/ff1248fd49dacdb35f5da128278cd777068481d7) Thanks [@afirstenberg](https://github.com/afirstenberg)! - fix(core): BaseMessage.text use contentBlocks
|
|
22
|
+
|
|
3
23
|
## 1.2.9
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
|
@@ -24,7 +24,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
24
24
|
}
|
|
25
25
|
return to;
|
|
26
26
|
};
|
|
27
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
27
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
28
28
|
value: mod,
|
|
29
29
|
enumerable: true
|
|
30
30
|
}) : target, mod));
|
|
@@ -40,7 +40,8 @@ require_index.AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new no
|
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
async function dispatchCustomEvent(eventName, payload, config) {
|
|
43
|
-
|
|
43
|
+
const ensuredConfig = require_config.ensureConfig(config);
|
|
44
|
+
await require_callbacks_dispatch_web.dispatchCustomEvent(eventName, payload, ensuredConfig);
|
|
44
45
|
}
|
|
45
46
|
//#endregion
|
|
46
47
|
exports.dispatchCustomEvent = dispatchCustomEvent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["AsyncLocalStorageProviderSingleton","AsyncLocalStorage","
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["AsyncLocalStorageProviderSingleton","AsyncLocalStorage","ensureConfig","dispatchCustomEventWeb"],"sources":["../../../src/callbacks/dispatch/index.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { dispatchCustomEvent as dispatchCustomEventWeb } from \"./web.js\";\nimport { type RunnableConfig, ensureConfig } from \"../../runnables/config.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../../singletons/index.js\";\n\nAsyncLocalStorageProviderSingleton.initializeGlobalInstance(\n new AsyncLocalStorage()\n);\n\n/**\n * Dispatch a custom event.\n *\n * Note: this method is only supported in non-web environments\n * due to usage of async_hooks to infer config.\n *\n * If you are using this method in the browser, please import and use\n * from \"@langchain/core/callbacks/dispatch/web\".\n *\n * @param name The name of the custom event.\n * @param payload The data for the custom event.\n * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.\n * @param config Optional config object.\n *\n * @example\n * ```typescript\n * import { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\n *\n * const foo = RunnableLambda.from(async (input: string) => {\n * await dispatchCustomEvent(\"my_custom_event\", { arbitraryField: \"someval\" });\n * return input;\n * });\n *\n * const callbacks = [{\n * handleCustomEvent: (eventName: string, payload: any) => {\n * // Logs \"my_custom_event\" and { arbitraryField: \"someval\" }\n * console.log(eventName, payload);\n * }\n * }];\n *\n * await foo.invoke(\"hi\", { callbacks })\n * ```\n */\nexport async function dispatchCustomEvent(\n eventName: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n payload: any,\n config?: RunnableConfig\n) {\n const ensuredConfig = ensureConfig(config);\n await dispatchCustomEventWeb(eventName, payload, ensuredConfig);\n}\n"],"mappings":";;;;;;;AAOAA,cAAAA,mCAAmC,yBACjC,IAAIC,iBAAAA,kBAAkB,CACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,oBACpB,WAEA,SACA,QACA;CACA,MAAM,gBAAgBC,eAAAA,aAAa,MAAM;CACzC,MAAMC,+BAAAA,oBAAuB,WAAW,SAAS,aAAa;AAChE"}
|
|
@@ -39,7 +39,8 @@ AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorag
|
|
|
39
39
|
* ```
|
|
40
40
|
*/
|
|
41
41
|
async function dispatchCustomEvent(eventName, payload, config) {
|
|
42
|
-
|
|
42
|
+
const ensuredConfig = ensureConfig(config);
|
|
43
|
+
await dispatchCustomEvent$1(eventName, payload, ensuredConfig);
|
|
43
44
|
}
|
|
44
45
|
//#endregion
|
|
45
46
|
export { dispatchCustomEvent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["dispatchCustomEventWeb"],"sources":["../../../src/callbacks/dispatch/index.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { dispatchCustomEvent as dispatchCustomEventWeb } from \"./web.js\";\nimport { type RunnableConfig, ensureConfig } from \"../../runnables/config.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../../singletons/index.js\";\n\nAsyncLocalStorageProviderSingleton.initializeGlobalInstance(\n new AsyncLocalStorage()\n);\n\n/**\n * Dispatch a custom event.\n *\n * Note: this method is only supported in non-web environments\n * due to usage of async_hooks to infer config.\n *\n * If you are using this method in the browser, please import and use\n * from \"@langchain/core/callbacks/dispatch/web\".\n *\n * @param name The name of the custom event.\n * @param payload The data for the custom event.\n * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.\n * @param config Optional config object.\n *\n * @example\n * ```typescript\n * import { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\n *\n * const foo = RunnableLambda.from(async (input: string) => {\n * await dispatchCustomEvent(\"my_custom_event\", { arbitraryField: \"someval\" });\n * return input;\n * });\n *\n * const callbacks = [{\n * handleCustomEvent: (eventName: string, payload: any) => {\n * // Logs \"my_custom_event\" and { arbitraryField: \"someval\" }\n * console.log(eventName, payload);\n * }\n * }];\n *\n * await foo.invoke(\"hi\", { callbacks })\n * ```\n */\nexport async function dispatchCustomEvent(\n eventName: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n payload: any,\n config?: RunnableConfig\n) {\n const ensuredConfig = ensureConfig(config);\n await dispatchCustomEventWeb(eventName, payload, ensuredConfig);\n}\n"],"mappings":";;;;;;AAOA,mCAAmC,yBACjC,IAAI,kBAAkB,CACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,oBACpB,WAEA,SACA,QACA;
|
|
1
|
+
{"version":3,"file":"index.js","names":["dispatchCustomEventWeb"],"sources":["../../../src/callbacks/dispatch/index.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { dispatchCustomEvent as dispatchCustomEventWeb } from \"./web.js\";\nimport { type RunnableConfig, ensureConfig } from \"../../runnables/config.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../../singletons/index.js\";\n\nAsyncLocalStorageProviderSingleton.initializeGlobalInstance(\n new AsyncLocalStorage()\n);\n\n/**\n * Dispatch a custom event.\n *\n * Note: this method is only supported in non-web environments\n * due to usage of async_hooks to infer config.\n *\n * If you are using this method in the browser, please import and use\n * from \"@langchain/core/callbacks/dispatch/web\".\n *\n * @param name The name of the custom event.\n * @param payload The data for the custom event.\n * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.\n * @param config Optional config object.\n *\n * @example\n * ```typescript\n * import { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\n *\n * const foo = RunnableLambda.from(async (input: string) => {\n * await dispatchCustomEvent(\"my_custom_event\", { arbitraryField: \"someval\" });\n * return input;\n * });\n *\n * const callbacks = [{\n * handleCustomEvent: (eventName: string, payload: any) => {\n * // Logs \"my_custom_event\" and { arbitraryField: \"someval\" }\n * console.log(eventName, payload);\n * }\n * }];\n *\n * await foo.invoke(\"hi\", { callbacks })\n * ```\n */\nexport async function dispatchCustomEvent(\n eventName: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n payload: any,\n config?: RunnableConfig\n) {\n const ensuredConfig = ensureConfig(config);\n await dispatchCustomEventWeb(eventName, payload, ensuredConfig);\n}\n"],"mappings":";;;;;;AAOA,mCAAmC,yBACjC,IAAI,kBAAkB,CACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,oBACpB,WAEA,SACA,QACA;CACA,MAAM,gBAAgB,aAAa,MAAM;CACzC,MAAMA,sBAAuB,WAAW,SAAS,aAAa;AAChE"}
|
package/dist/indexing/base.cjs
CHANGED
|
@@ -59,11 +59,13 @@ var _HashedDocument = class {
|
|
|
59
59
|
return doc;
|
|
60
60
|
}
|
|
61
61
|
_hashStringToUUID(inputString) {
|
|
62
|
-
|
|
62
|
+
const hash_value = this.keyEncoder(inputString);
|
|
63
|
+
return require_utils_uuid_index.v5(hash_value, require_record_manager.UUIDV5_NAMESPACE);
|
|
63
64
|
}
|
|
64
65
|
_hashNestedDictToUUID(data) {
|
|
65
66
|
const serialized_data = JSON.stringify(data, Object.keys(data).sort());
|
|
66
|
-
|
|
67
|
+
const hash_value = this.keyEncoder(serialized_data);
|
|
68
|
+
return require_utils_uuid_index.v5(hash_value, require_record_manager.UUIDV5_NAMESPACE);
|
|
67
69
|
}
|
|
68
70
|
};
|
|
69
71
|
function _batch(size, iterable) {
|
|
@@ -144,10 +146,12 @@ async function index(args) {
|
|
|
144
146
|
const docsToUpdate = [];
|
|
145
147
|
const seenDocs = /* @__PURE__ */ new Set();
|
|
146
148
|
hashedDocs.forEach((hashedDoc, i) => {
|
|
147
|
-
if (batchExists[i])
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
149
|
+
if (batchExists[i]) {
|
|
150
|
+
if (forceUpdate) seenDocs.add(hashedDoc.uid);
|
|
151
|
+
else {
|
|
152
|
+
docsToUpdate.push(hashedDoc.uid);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
151
155
|
}
|
|
152
156
|
uids.push(hashedDoc.uid);
|
|
153
157
|
docsToIndex.push(hashedDoc.toDocument());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["sha256","Document","uuidv5","UUIDV5_NAMESPACE"],"sources":["../../src/indexing/base.ts"],"sourcesContent":["import { v5 as uuidv5 } from \"../utils/uuid/index.js\";\nimport { VectorStore } from \"../vectorstores.js\";\nimport { RecordManagerInterface, UUIDV5_NAMESPACE } from \"./record_manager.js\";\nimport { sha256, type HashKeyEncoder } from \"../utils/hash.js\";\nimport { DocumentInterface, Document } from \"../documents/document.js\";\nimport { BaseDocumentLoader } from \"../document_loaders/base.js\";\n\ntype Metadata = Record<string, unknown>;\n\ntype IndexingResult = {\n numAdded: number;\n numDeleted: number;\n numUpdated: number;\n numSkipped: number;\n};\n\ntype StringOrDocFunc = string | ((doc: DocumentInterface) => string);\n\nexport interface HashedDocumentInterface extends DocumentInterface {\n uid: string;\n hash_?: string;\n contentHash?: string;\n metadataHash?: string;\n pageContent: string;\n metadata: Metadata;\n calculateHashes(): void;\n toDocument(): DocumentInterface;\n}\n\ninterface HashedDocumentArgs {\n pageContent: string;\n metadata: Metadata;\n uid: string;\n}\n\n/**\n * HashedDocument is a Document with hashes calculated.\n * Hashes are calculated based on page content and metadata.\n * It is used for indexing.\n */\nexport class _HashedDocument implements HashedDocumentInterface {\n uid: string;\n\n hash_?: string;\n\n contentHash?: string;\n\n metadataHash?: string;\n\n pageContent: string;\n\n metadata: Metadata;\n\n private keyEncoder: HashKeyEncoder = sha256;\n\n constructor(fields: HashedDocumentArgs) {\n this.uid = fields.uid;\n this.pageContent = fields.pageContent;\n this.metadata = fields.metadata;\n }\n\n makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void {\n this.keyEncoder = keyEncoderFn;\n }\n\n calculateHashes(): void {\n const forbiddenKeys = [\"hash_\", \"content_hash\", \"metadata_hash\"];\n\n for (const key of forbiddenKeys) {\n if (key in this.metadata) {\n throw new Error(\n `Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(\n \", \"\n )}]`\n );\n }\n }\n\n const contentHash = this._hashStringToUUID(this.pageContent);\n\n try {\n const metadataHash = this._hashNestedDictToUUID(this.metadata);\n this.contentHash = contentHash;\n this.metadataHash = metadataHash;\n } catch (e) {\n throw new Error(\n `Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`\n );\n }\n\n this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash);\n\n if (!this.uid) {\n this.uid = this.hash_;\n }\n }\n\n toDocument(): DocumentInterface {\n return new Document({\n pageContent: this.pageContent,\n metadata: this.metadata,\n });\n }\n\n static fromDocument(\n document: DocumentInterface,\n uid?: string\n ): _HashedDocument {\n const doc = new this({\n pageContent: document.pageContent,\n metadata: document.metadata,\n uid: uid || (document as DocumentInterface & { uid: string }).uid,\n });\n doc.calculateHashes();\n return doc;\n }\n\n private _hashStringToUUID(inputString: string): string {\n const hash_value = this.keyEncoder(inputString);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n\n private _hashNestedDictToUUID(data: Record<string, unknown>): string {\n const serialized_data = JSON.stringify(data, Object.keys(data).sort());\n const hash_value = this.keyEncoder(serialized_data);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n}\n\nexport type CleanupMode = \"full\" | \"incremental\";\n\nexport type IndexOptions = {\n /**\n * The number of documents to index in one batch.\n */\n batchSize?: number;\n /**\n * The cleanup mode to use. Can be \"full\", \"incremental\" or undefined.\n * - **Incremental**: Cleans up all documents that haven't been updated AND\n * that are associated with source ids that were seen\n * during indexing.\n * Clean up is done continuously during indexing helping\n * to minimize the probability of users seeing duplicated\n * content.\n * - **Full**: Delete all documents that haven to been returned by the loader.\n * Clean up runs after all documents have been indexed.\n * This means that users may see duplicated content during indexing.\n * - **undefined**: Do not delete any documents.\n */\n cleanup?: CleanupMode;\n /**\n * Optional key that helps identify the original source of the document.\n * Must either be a string representing the key of the source in the metadata\n * or a function that takes a document and returns a string representing the source.\n * **Required when cleanup is incremental**.\n */\n sourceIdKey?: StringOrDocFunc;\n /**\n * Batch size to use when cleaning up documents.\n */\n cleanupBatchSize?: number;\n /**\n * Force update documents even if they are present in the\n * record manager. Useful if you are re-indexing with updated embeddings.\n */\n forceUpdate?: boolean;\n};\n\nexport function _batch<T>(size: number, iterable: T[]): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n\n iterable.forEach((item) => {\n currentBatch.push(item);\n\n if (currentBatch.length >= size) {\n batches.push(currentBatch);\n currentBatch = [];\n }\n });\n\n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n\n return batches;\n}\n\nexport function _deduplicateInOrder(\n hashedDocuments: HashedDocumentInterface[]\n): HashedDocumentInterface[] {\n const seen = new Set<string>();\n const deduplicated: HashedDocumentInterface[] = [];\n\n for (const hashedDoc of hashedDocuments) {\n if (!hashedDoc.hash_) {\n throw new Error(\"Hashed document does not have a hash\");\n }\n\n if (!seen.has(hashedDoc.hash_)) {\n seen.add(hashedDoc.hash_);\n deduplicated.push(hashedDoc);\n }\n }\n return deduplicated;\n}\n\nexport function _getSourceIdAssigner(\n sourceIdKey: StringOrDocFunc | null\n): (doc: DocumentInterface) => string | null {\n if (sourceIdKey === null) {\n return (_doc: DocumentInterface) => null;\n } else if (typeof sourceIdKey === \"string\") {\n return (doc: DocumentInterface) => doc.metadata[sourceIdKey];\n } else if (typeof sourceIdKey === \"function\") {\n return sourceIdKey;\n } else {\n throw new Error(\n `sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`\n );\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _isBaseDocumentLoader = (arg: any): arg is BaseDocumentLoader => {\n if (\n \"load\" in arg &&\n typeof arg.load === \"function\" &&\n \"loadAndSplit\" in arg &&\n typeof arg.loadAndSplit === \"function\"\n ) {\n return true;\n }\n return false;\n};\n\ninterface IndexArgs {\n docsSource: BaseDocumentLoader | DocumentInterface[];\n recordManager: RecordManagerInterface;\n vectorStore: VectorStore;\n options?: IndexOptions;\n}\n\n/**\n * Index data from the doc source into the vector store.\n *\n * Indexing functionality uses a manager to keep track of which documents\n * are in the vector store.\n *\n * This allows us to keep track of which documents were updated, and which\n * documents were deleted, which documents should be skipped.\n *\n * For the time being, documents are indexed using their hashes, and users\n * are not able to specify the uid of the document.\n *\n * @param {IndexArgs} args\n * @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents.\n * @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents.\n * @param {VectorStore} args.vectorStore The vector store to use for storing the documents.\n * @param {IndexOptions | undefined} args.options Options for indexing.\n * @returns {Promise<IndexingResult>}\n */\nexport async function index(args: IndexArgs): Promise<IndexingResult> {\n const { docsSource, recordManager, vectorStore, options } = args;\n const {\n batchSize = 100,\n cleanup,\n sourceIdKey,\n cleanupBatchSize = 1000,\n forceUpdate = false,\n } = options ?? {};\n\n if (cleanup === \"incremental\" && !sourceIdKey) {\n throw new Error(\n \"sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.\"\n );\n }\n\n const docs = _isBaseDocumentLoader(docsSource)\n ? await docsSource.load()\n : docsSource;\n\n const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null);\n\n const indexStartDt = await recordManager.getTime();\n let numAdded = 0;\n let numDeleted = 0;\n let numUpdated = 0;\n let numSkipped = 0;\n\n const batches = _batch<DocumentInterface>(batchSize ?? 100, docs);\n\n for (const batch of batches) {\n const hashedDocs = _deduplicateInOrder(\n batch.map((doc) => _HashedDocument.fromDocument(doc))\n );\n\n const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc));\n\n if (cleanup === \"incremental\") {\n hashedDocs.forEach((_hashedDoc, index) => {\n const source = sourceIds[index];\n if (source === null) {\n throw new Error(\n \"sourceIdKey must be provided when cleanup is incremental\"\n );\n }\n });\n }\n\n const batchExists = await recordManager.exists(\n hashedDocs.map((doc) => doc.uid)\n );\n\n const uids: string[] = [];\n const docsToIndex: DocumentInterface[] = [];\n const docsToUpdate: string[] = [];\n const seenDocs = new Set<string>();\n hashedDocs.forEach((hashedDoc, i) => {\n const docExists = batchExists[i];\n if (docExists) {\n if (forceUpdate) {\n seenDocs.add(hashedDoc.uid);\n } else {\n docsToUpdate.push(hashedDoc.uid);\n return;\n }\n }\n uids.push(hashedDoc.uid);\n docsToIndex.push(hashedDoc.toDocument());\n });\n\n if (docsToUpdate.length > 0) {\n await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt });\n numSkipped += docsToUpdate.length;\n }\n\n if (docsToIndex.length > 0) {\n await vectorStore.addDocuments(docsToIndex, { ids: uids });\n numAdded += docsToIndex.length - seenDocs.size;\n numUpdated += seenDocs.size;\n }\n\n await recordManager.update(\n hashedDocs.map((doc) => doc.uid),\n { timeAtLeast: indexStartDt, groupIds: sourceIds }\n );\n\n if (cleanup === \"incremental\") {\n sourceIds.forEach((sourceId) => {\n if (!sourceId) throw new Error(\"Source id cannot be null\");\n });\n const uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n groupIds: sourceIds,\n });\n\n if (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n }\n }\n }\n\n if (cleanup === \"full\") {\n let uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n while (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n }\n }\n\n return {\n numAdded,\n numDeleted,\n numUpdated,\n numSkipped,\n };\n}\n"],"mappings":";;;;;;;;;;;AAwCA,IAAa,kBAAb,MAAgE;CAC9D;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,aAAqCA,aAAAA;CAErC,YAAY,QAA4B;EACtC,KAAK,MAAM,OAAO;EAClB,KAAK,cAAc,OAAO;EAC1B,KAAK,WAAW,OAAO;CACzB;CAEA,sBAAsB,cAAoC;EACxD,KAAK,aAAa;CACpB;CAEA,kBAAwB;EACtB,MAAM,gBAAgB;GAAC;GAAS;GAAgB;EAAe;EAE/D,KAAK,MAAM,OAAO,eAChB,IAAI,OAAO,KAAK,UACd,MAAM,IAAI,MACR,+BAA+B,IAAI,yDAAyD,cAAc,KACxG,IACF,EAAE,EACJ;EAIJ,MAAM,cAAc,KAAK,kBAAkB,KAAK,WAAW;EAE3D,IAAI;GACF,MAAM,eAAe,KAAK,sBAAsB,KAAK,QAAQ;GAC7D,KAAK,cAAc;GACnB,KAAK,eAAe;EACtB,SAAS,GAAG;GACV,MAAM,IAAI,MACR,4BAA4B,EAAE,uDAChC;EACF;EAEA,KAAK,QAAQ,KAAK,kBAAkB,KAAK,cAAc,KAAK,YAAY;EAExE,IAAI,CAAC,KAAK,KACR,KAAK,MAAM,KAAK;CAEpB;CAEA,aAAgC;EAC9B,OAAO,IAAIC,iBAAAA,SAAS;GAClB,aAAa,KAAK;GAClB,UAAU,KAAK;EACjB,CAAC;CACH;CAEA,OAAO,aACL,UACA,KACiB;EACjB,MAAM,MAAM,IAAI,KAAK;GACnB,aAA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vB,YAAY,KAAK,UAAU,WAAW,CAAC;EACzC,CAAC;EAED,IAAI,aAAa,SAAS,GAAG;GAC3B,MAAM,cAAc,OAAO,cAAc,EAAE,aAAa,aAAa,CAAC;GACtE,cAAc,aAAa;EAC7B;EAEA,IAAI,YAAY,SAAS,GAAG;GAC1B,MAAM,YAAY,aAAa,aAAa,EAAE,KAAK,KAAK,CAAC;GACzD,YAAY,YAAY,SAAS,SAAS;GAC1C,cAAc,SAAS;EACzB;EAEA,MAAM,cAAc,OAClB,WAAW,KAAK,QAAQ,IAAI,GAAG,GAC/B;GAAE,aAAa;GAAc,UAAU;EAAU,CACnD;EAEA,IAAI,YAAY,eAAe;GAC7B,UAAU,SAAS,aAAa;IAC9B,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,0BAA0B;GAC3D,CAAC;GACD,MAAM,eAAe,MAAM,cAAc,SAAS;IAChD,QAAQ;IACR,UAAU;GACZ,CAAC;GAED,IAAI,aAAa,SAAS,GAAG;IAC3B,MAAM,YAAY,OAAO,EAAE,KAAK,aAAa,CAAC;IAC9C,MAAM,cAAc,WAAW,YAAY;IAC3C,cAAc,aAAa;GAC7B;EACF;CACF;CAEA,IAAI,YAAY,QAAQ;EACtB,IAAI,eAAe,MAAM,cAAc,SAAS;GAC9C,QAAQ;GACR,OAAO;EACT,CAAC;EACD,OAAO,aAAa,SAAS,GAAG;GAC9B,MAAM,YAAY,OAAO,EAAE,KAAK,aAAa,CAAC;GAC9C,MAAM,cAAc,WAAW,YAAY;GAC3C,cAAc,aAAa;GAC3B,eAAe,MAAM,cAAc,SAAS;IAC1C,QAAQ;IACR,OAAO;GACT,CAAC;EACH;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base.cjs","names":["sha256","Document","uuidv5","UUIDV5_NAMESPACE"],"sources":["../../src/indexing/base.ts"],"sourcesContent":["import { v5 as uuidv5 } from \"../utils/uuid/index.js\";\nimport { VectorStore } from \"../vectorstores.js\";\nimport { RecordManagerInterface, UUIDV5_NAMESPACE } from \"./record_manager.js\";\nimport { sha256, type HashKeyEncoder } from \"../utils/hash.js\";\nimport { DocumentInterface, Document } from \"../documents/document.js\";\nimport { BaseDocumentLoader } from \"../document_loaders/base.js\";\n\ntype Metadata = Record<string, unknown>;\n\ntype IndexingResult = {\n numAdded: number;\n numDeleted: number;\n numUpdated: number;\n numSkipped: number;\n};\n\ntype StringOrDocFunc = string | ((doc: DocumentInterface) => string);\n\nexport interface HashedDocumentInterface extends DocumentInterface {\n uid: string;\n hash_?: string;\n contentHash?: string;\n metadataHash?: string;\n pageContent: string;\n metadata: Metadata;\n calculateHashes(): void;\n toDocument(): DocumentInterface;\n}\n\ninterface HashedDocumentArgs {\n pageContent: string;\n metadata: Metadata;\n uid: string;\n}\n\n/**\n * HashedDocument is a Document with hashes calculated.\n * Hashes are calculated based on page content and metadata.\n * It is used for indexing.\n */\nexport class _HashedDocument implements HashedDocumentInterface {\n uid: string;\n\n hash_?: string;\n\n contentHash?: string;\n\n metadataHash?: string;\n\n pageContent: string;\n\n metadata: Metadata;\n\n private keyEncoder: HashKeyEncoder = sha256;\n\n constructor(fields: HashedDocumentArgs) {\n this.uid = fields.uid;\n this.pageContent = fields.pageContent;\n this.metadata = fields.metadata;\n }\n\n makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void {\n this.keyEncoder = keyEncoderFn;\n }\n\n calculateHashes(): void {\n const forbiddenKeys = [\"hash_\", \"content_hash\", \"metadata_hash\"];\n\n for (const key of forbiddenKeys) {\n if (key in this.metadata) {\n throw new Error(\n `Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(\n \", \"\n )}]`\n );\n }\n }\n\n const contentHash = this._hashStringToUUID(this.pageContent);\n\n try {\n const metadataHash = this._hashNestedDictToUUID(this.metadata);\n this.contentHash = contentHash;\n this.metadataHash = metadataHash;\n } catch (e) {\n throw new Error(\n `Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`\n );\n }\n\n this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash);\n\n if (!this.uid) {\n this.uid = this.hash_;\n }\n }\n\n toDocument(): DocumentInterface {\n return new Document({\n pageContent: this.pageContent,\n metadata: this.metadata,\n });\n }\n\n static fromDocument(\n document: DocumentInterface,\n uid?: string\n ): _HashedDocument {\n const doc = new this({\n pageContent: document.pageContent,\n metadata: document.metadata,\n uid: uid || (document as DocumentInterface & { uid: string }).uid,\n });\n doc.calculateHashes();\n return doc;\n }\n\n private _hashStringToUUID(inputString: string): string {\n const hash_value = this.keyEncoder(inputString);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n\n private _hashNestedDictToUUID(data: Record<string, unknown>): string {\n const serialized_data = JSON.stringify(data, Object.keys(data).sort());\n const hash_value = this.keyEncoder(serialized_data);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n}\n\nexport type CleanupMode = \"full\" | \"incremental\";\n\nexport type IndexOptions = {\n /**\n * The number of documents to index in one batch.\n */\n batchSize?: number;\n /**\n * The cleanup mode to use. Can be \"full\", \"incremental\" or undefined.\n * - **Incremental**: Cleans up all documents that haven't been updated AND\n * that are associated with source ids that were seen\n * during indexing.\n * Clean up is done continuously during indexing helping\n * to minimize the probability of users seeing duplicated\n * content.\n * - **Full**: Delete all documents that haven to been returned by the loader.\n * Clean up runs after all documents have been indexed.\n * This means that users may see duplicated content during indexing.\n * - **undefined**: Do not delete any documents.\n */\n cleanup?: CleanupMode;\n /**\n * Optional key that helps identify the original source of the document.\n * Must either be a string representing the key of the source in the metadata\n * or a function that takes a document and returns a string representing the source.\n * **Required when cleanup is incremental**.\n */\n sourceIdKey?: StringOrDocFunc;\n /**\n * Batch size to use when cleaning up documents.\n */\n cleanupBatchSize?: number;\n /**\n * Force update documents even if they are present in the\n * record manager. Useful if you are re-indexing with updated embeddings.\n */\n forceUpdate?: boolean;\n};\n\nexport function _batch<T>(size: number, iterable: T[]): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n\n iterable.forEach((item) => {\n currentBatch.push(item);\n\n if (currentBatch.length >= size) {\n batches.push(currentBatch);\n currentBatch = [];\n }\n });\n\n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n\n return batches;\n}\n\nexport function _deduplicateInOrder(\n hashedDocuments: HashedDocumentInterface[]\n): HashedDocumentInterface[] {\n const seen = new Set<string>();\n const deduplicated: HashedDocumentInterface[] = [];\n\n for (const hashedDoc of hashedDocuments) {\n if (!hashedDoc.hash_) {\n throw new Error(\"Hashed document does not have a hash\");\n }\n\n if (!seen.has(hashedDoc.hash_)) {\n seen.add(hashedDoc.hash_);\n deduplicated.push(hashedDoc);\n }\n }\n return deduplicated;\n}\n\nexport function _getSourceIdAssigner(\n sourceIdKey: StringOrDocFunc | null\n): (doc: DocumentInterface) => string | null {\n if (sourceIdKey === null) {\n return (_doc: DocumentInterface) => null;\n } else if (typeof sourceIdKey === \"string\") {\n return (doc: DocumentInterface) => doc.metadata[sourceIdKey];\n } else if (typeof sourceIdKey === \"function\") {\n return sourceIdKey;\n } else {\n throw new Error(\n `sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`\n );\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _isBaseDocumentLoader = (arg: any): arg is BaseDocumentLoader => {\n if (\n \"load\" in arg &&\n typeof arg.load === \"function\" &&\n \"loadAndSplit\" in arg &&\n typeof arg.loadAndSplit === \"function\"\n ) {\n return true;\n }\n return false;\n};\n\ninterface IndexArgs {\n docsSource: BaseDocumentLoader | DocumentInterface[];\n recordManager: RecordManagerInterface;\n vectorStore: VectorStore;\n options?: IndexOptions;\n}\n\n/**\n * Index data from the doc source into the vector store.\n *\n * Indexing functionality uses a manager to keep track of which documents\n * are in the vector store.\n *\n * This allows us to keep track of which documents were updated, and which\n * documents were deleted, which documents should be skipped.\n *\n * For the time being, documents are indexed using their hashes, and users\n * are not able to specify the uid of the document.\n *\n * @param {IndexArgs} args\n * @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents.\n * @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents.\n * @param {VectorStore} args.vectorStore The vector store to use for storing the documents.\n * @param {IndexOptions | undefined} args.options Options for indexing.\n * @returns {Promise<IndexingResult>}\n */\nexport async function index(args: IndexArgs): Promise<IndexingResult> {\n const { docsSource, recordManager, vectorStore, options } = args;\n const {\n batchSize = 100,\n cleanup,\n sourceIdKey,\n cleanupBatchSize = 1000,\n forceUpdate = false,\n } = options ?? {};\n\n if (cleanup === \"incremental\" && !sourceIdKey) {\n throw new Error(\n \"sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.\"\n );\n }\n\n const docs = _isBaseDocumentLoader(docsSource)\n ? await docsSource.load()\n : docsSource;\n\n const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null);\n\n const indexStartDt = await recordManager.getTime();\n let numAdded = 0;\n let numDeleted = 0;\n let numUpdated = 0;\n let numSkipped = 0;\n\n const batches = _batch<DocumentInterface>(batchSize ?? 100, docs);\n\n for (const batch of batches) {\n const hashedDocs = _deduplicateInOrder(\n batch.map((doc) => _HashedDocument.fromDocument(doc))\n );\n\n const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc));\n\n if (cleanup === \"incremental\") {\n hashedDocs.forEach((_hashedDoc, index) => {\n const source = sourceIds[index];\n if (source === null) {\n throw new Error(\n \"sourceIdKey must be provided when cleanup is incremental\"\n );\n }\n });\n }\n\n const batchExists = await recordManager.exists(\n hashedDocs.map((doc) => doc.uid)\n );\n\n const uids: string[] = [];\n const docsToIndex: DocumentInterface[] = [];\n const docsToUpdate: string[] = [];\n const seenDocs = new Set<string>();\n hashedDocs.forEach((hashedDoc, i) => {\n const docExists = batchExists[i];\n if (docExists) {\n if (forceUpdate) {\n seenDocs.add(hashedDoc.uid);\n } else {\n docsToUpdate.push(hashedDoc.uid);\n return;\n }\n }\n uids.push(hashedDoc.uid);\n docsToIndex.push(hashedDoc.toDocument());\n });\n\n if (docsToUpdate.length > 0) {\n await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt });\n numSkipped += docsToUpdate.length;\n }\n\n if (docsToIndex.length > 0) {\n await vectorStore.addDocuments(docsToIndex, { ids: uids });\n numAdded += docsToIndex.length - seenDocs.size;\n numUpdated += seenDocs.size;\n }\n\n await recordManager.update(\n hashedDocs.map((doc) => doc.uid),\n { timeAtLeast: indexStartDt, groupIds: sourceIds }\n );\n\n if (cleanup === \"incremental\") {\n sourceIds.forEach((sourceId) => {\n if (!sourceId) throw new Error(\"Source id cannot be null\");\n });\n const uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n groupIds: sourceIds,\n });\n\n if (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n }\n }\n }\n\n if (cleanup === \"full\") {\n let uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n while (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n }\n }\n\n return {\n numAdded,\n numDeleted,\n numUpdated,\n numSkipped,\n };\n}\n"],"mappings":";;;;;;;;;;;AAwCA,IAAa,kBAAb,MAAgE;CAC9D;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,aAAqCA,aAAAA;CAErC,YAAY,QAA4B;EACtC,KAAK,MAAM,OAAO;EAClB,KAAK,cAAc,OAAO;EAC1B,KAAK,WAAW,OAAO;CACzB;CAEA,sBAAsB,cAAoC;EACxD,KAAK,aAAa;CACpB;CAEA,kBAAwB;EACtB,MAAM,gBAAgB;GAAC;GAAS;GAAgB;EAAe;EAE/D,KAAK,MAAM,OAAO,eAChB,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;IAC3B,MAAM,YAAY,OAAO,EAAE,KAAK,aAAa,CAAC;IAC9C,MAAM,cAAc,WAAW,YAAY;IAC3C,cAAc,aAAa;GAC7B;EACF;CACF;CAEA,IAAI,YAAY,QAAQ;EACtB,IAAI,eAAe,MAAM,cAAc,SAAS;GAC9C,QAAQ;GACR,OAAO;EACT,CAAC;EACD,OAAO,aAAa,SAAS,GAAG;GAC9B,MAAM,YAAY,OAAO,EAAE,KAAK,aAAa,CAAC;GAC9C,MAAM,cAAc,WAAW,YAAY;GAC3C,cAAc,aAAa;GAC3B,eAAe,MAAM,cAAc,SAAS;IAC1C,QAAQ;IACR,OAAO;GACT,CAAC;EACH;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
|
package/dist/indexing/base.js
CHANGED
|
@@ -59,11 +59,13 @@ var _HashedDocument = class {
|
|
|
59
59
|
return doc;
|
|
60
60
|
}
|
|
61
61
|
_hashStringToUUID(inputString) {
|
|
62
|
-
|
|
62
|
+
const hash_value = this.keyEncoder(inputString);
|
|
63
|
+
return v5(hash_value, UUIDV5_NAMESPACE);
|
|
63
64
|
}
|
|
64
65
|
_hashNestedDictToUUID(data) {
|
|
65
66
|
const serialized_data = JSON.stringify(data, Object.keys(data).sort());
|
|
66
|
-
|
|
67
|
+
const hash_value = this.keyEncoder(serialized_data);
|
|
68
|
+
return v5(hash_value, UUIDV5_NAMESPACE);
|
|
67
69
|
}
|
|
68
70
|
};
|
|
69
71
|
function _batch(size, iterable) {
|
|
@@ -144,10 +146,12 @@ async function index(args) {
|
|
|
144
146
|
const docsToUpdate = [];
|
|
145
147
|
const seenDocs = /* @__PURE__ */ new Set();
|
|
146
148
|
hashedDocs.forEach((hashedDoc, i) => {
|
|
147
|
-
if (batchExists[i])
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
149
|
+
if (batchExists[i]) {
|
|
150
|
+
if (forceUpdate) seenDocs.add(hashedDoc.uid);
|
|
151
|
+
else {
|
|
152
|
+
docsToUpdate.push(hashedDoc.uid);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
151
155
|
}
|
|
152
156
|
uids.push(hashedDoc.uid);
|
|
153
157
|
docsToIndex.push(hashedDoc.toDocument());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":["uuidv5"],"sources":["../../src/indexing/base.ts"],"sourcesContent":["import { v5 as uuidv5 } from \"../utils/uuid/index.js\";\nimport { VectorStore } from \"../vectorstores.js\";\nimport { RecordManagerInterface, UUIDV5_NAMESPACE } from \"./record_manager.js\";\nimport { sha256, type HashKeyEncoder } from \"../utils/hash.js\";\nimport { DocumentInterface, Document } from \"../documents/document.js\";\nimport { BaseDocumentLoader } from \"../document_loaders/base.js\";\n\ntype Metadata = Record<string, unknown>;\n\ntype IndexingResult = {\n numAdded: number;\n numDeleted: number;\n numUpdated: number;\n numSkipped: number;\n};\n\ntype StringOrDocFunc = string | ((doc: DocumentInterface) => string);\n\nexport interface HashedDocumentInterface extends DocumentInterface {\n uid: string;\n hash_?: string;\n contentHash?: string;\n metadataHash?: string;\n pageContent: string;\n metadata: Metadata;\n calculateHashes(): void;\n toDocument(): DocumentInterface;\n}\n\ninterface HashedDocumentArgs {\n pageContent: string;\n metadata: Metadata;\n uid: string;\n}\n\n/**\n * HashedDocument is a Document with hashes calculated.\n * Hashes are calculated based on page content and metadata.\n * It is used for indexing.\n */\nexport class _HashedDocument implements HashedDocumentInterface {\n uid: string;\n\n hash_?: string;\n\n contentHash?: string;\n\n metadataHash?: string;\n\n pageContent: string;\n\n metadata: Metadata;\n\n private keyEncoder: HashKeyEncoder = sha256;\n\n constructor(fields: HashedDocumentArgs) {\n this.uid = fields.uid;\n this.pageContent = fields.pageContent;\n this.metadata = fields.metadata;\n }\n\n makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void {\n this.keyEncoder = keyEncoderFn;\n }\n\n calculateHashes(): void {\n const forbiddenKeys = [\"hash_\", \"content_hash\", \"metadata_hash\"];\n\n for (const key of forbiddenKeys) {\n if (key in this.metadata) {\n throw new Error(\n `Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(\n \", \"\n )}]`\n );\n }\n }\n\n const contentHash = this._hashStringToUUID(this.pageContent);\n\n try {\n const metadataHash = this._hashNestedDictToUUID(this.metadata);\n this.contentHash = contentHash;\n this.metadataHash = metadataHash;\n } catch (e) {\n throw new Error(\n `Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`\n );\n }\n\n this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash);\n\n if (!this.uid) {\n this.uid = this.hash_;\n }\n }\n\n toDocument(): DocumentInterface {\n return new Document({\n pageContent: this.pageContent,\n metadata: this.metadata,\n });\n }\n\n static fromDocument(\n document: DocumentInterface,\n uid?: string\n ): _HashedDocument {\n const doc = new this({\n pageContent: document.pageContent,\n metadata: document.metadata,\n uid: uid || (document as DocumentInterface & { uid: string }).uid,\n });\n doc.calculateHashes();\n return doc;\n }\n\n private _hashStringToUUID(inputString: string): string {\n const hash_value = this.keyEncoder(inputString);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n\n private _hashNestedDictToUUID(data: Record<string, unknown>): string {\n const serialized_data = JSON.stringify(data, Object.keys(data).sort());\n const hash_value = this.keyEncoder(serialized_data);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n}\n\nexport type CleanupMode = \"full\" | \"incremental\";\n\nexport type IndexOptions = {\n /**\n * The number of documents to index in one batch.\n */\n batchSize?: number;\n /**\n * The cleanup mode to use. Can be \"full\", \"incremental\" or undefined.\n * - **Incremental**: Cleans up all documents that haven't been updated AND\n * that are associated with source ids that were seen\n * during indexing.\n * Clean up is done continuously during indexing helping\n * to minimize the probability of users seeing duplicated\n * content.\n * - **Full**: Delete all documents that haven to been returned by the loader.\n * Clean up runs after all documents have been indexed.\n * This means that users may see duplicated content during indexing.\n * - **undefined**: Do not delete any documents.\n */\n cleanup?: CleanupMode;\n /**\n * Optional key that helps identify the original source of the document.\n * Must either be a string representing the key of the source in the metadata\n * or a function that takes a document and returns a string representing the source.\n * **Required when cleanup is incremental**.\n */\n sourceIdKey?: StringOrDocFunc;\n /**\n * Batch size to use when cleaning up documents.\n */\n cleanupBatchSize?: number;\n /**\n * Force update documents even if they are present in the\n * record manager. Useful if you are re-indexing with updated embeddings.\n */\n forceUpdate?: boolean;\n};\n\nexport function _batch<T>(size: number, iterable: T[]): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n\n iterable.forEach((item) => {\n currentBatch.push(item);\n\n if (currentBatch.length >= size) {\n batches.push(currentBatch);\n currentBatch = [];\n }\n });\n\n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n\n return batches;\n}\n\nexport function _deduplicateInOrder(\n hashedDocuments: HashedDocumentInterface[]\n): HashedDocumentInterface[] {\n const seen = new Set<string>();\n const deduplicated: HashedDocumentInterface[] = [];\n\n for (const hashedDoc of hashedDocuments) {\n if (!hashedDoc.hash_) {\n throw new Error(\"Hashed document does not have a hash\");\n }\n\n if (!seen.has(hashedDoc.hash_)) {\n seen.add(hashedDoc.hash_);\n deduplicated.push(hashedDoc);\n }\n }\n return deduplicated;\n}\n\nexport function _getSourceIdAssigner(\n sourceIdKey: StringOrDocFunc | null\n): (doc: DocumentInterface) => string | null {\n if (sourceIdKey === null) {\n return (_doc: DocumentInterface) => null;\n } else if (typeof sourceIdKey === \"string\") {\n return (doc: DocumentInterface) => doc.metadata[sourceIdKey];\n } else if (typeof sourceIdKey === \"function\") {\n return sourceIdKey;\n } else {\n throw new Error(\n `sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`\n );\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _isBaseDocumentLoader = (arg: any): arg is BaseDocumentLoader => {\n if (\n \"load\" in arg &&\n typeof arg.load === \"function\" &&\n \"loadAndSplit\" in arg &&\n typeof arg.loadAndSplit === \"function\"\n ) {\n return true;\n }\n return false;\n};\n\ninterface IndexArgs {\n docsSource: BaseDocumentLoader | DocumentInterface[];\n recordManager: RecordManagerInterface;\n vectorStore: VectorStore;\n options?: IndexOptions;\n}\n\n/**\n * Index data from the doc source into the vector store.\n *\n * Indexing functionality uses a manager to keep track of which documents\n * are in the vector store.\n *\n * This allows us to keep track of which documents were updated, and which\n * documents were deleted, which documents should be skipped.\n *\n * For the time being, documents are indexed using their hashes, and users\n * are not able to specify the uid of the document.\n *\n * @param {IndexArgs} args\n * @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents.\n * @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents.\n * @param {VectorStore} args.vectorStore The vector store to use for storing the documents.\n * @param {IndexOptions | undefined} args.options Options for indexing.\n * @returns {Promise<IndexingResult>}\n */\nexport async function index(args: IndexArgs): Promise<IndexingResult> {\n const { docsSource, recordManager, vectorStore, options } = args;\n const {\n batchSize = 100,\n cleanup,\n sourceIdKey,\n cleanupBatchSize = 1000,\n forceUpdate = false,\n } = options ?? {};\n\n if (cleanup === \"incremental\" && !sourceIdKey) {\n throw new Error(\n \"sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.\"\n );\n }\n\n const docs = _isBaseDocumentLoader(docsSource)\n ? await docsSource.load()\n : docsSource;\n\n const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null);\n\n const indexStartDt = await recordManager.getTime();\n let numAdded = 0;\n let numDeleted = 0;\n let numUpdated = 0;\n let numSkipped = 0;\n\n const batches = _batch<DocumentInterface>(batchSize ?? 100, docs);\n\n for (const batch of batches) {\n const hashedDocs = _deduplicateInOrder(\n batch.map((doc) => _HashedDocument.fromDocument(doc))\n );\n\n const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc));\n\n if (cleanup === \"incremental\") {\n hashedDocs.forEach((_hashedDoc, index) => {\n const source = sourceIds[index];\n if (source === null) {\n throw new Error(\n \"sourceIdKey must be provided when cleanup is incremental\"\n );\n }\n });\n }\n\n const batchExists = await recordManager.exists(\n hashedDocs.map((doc) => doc.uid)\n );\n\n const uids: string[] = [];\n const docsToIndex: DocumentInterface[] = [];\n const docsToUpdate: string[] = [];\n const seenDocs = new Set<string>();\n hashedDocs.forEach((hashedDoc, i) => {\n const docExists = batchExists[i];\n if (docExists) {\n if (forceUpdate) {\n seenDocs.add(hashedDoc.uid);\n } else {\n docsToUpdate.push(hashedDoc.uid);\n return;\n }\n }\n uids.push(hashedDoc.uid);\n docsToIndex.push(hashedDoc.toDocument());\n });\n\n if (docsToUpdate.length > 0) {\n await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt });\n numSkipped += docsToUpdate.length;\n }\n\n if (docsToIndex.length > 0) {\n await vectorStore.addDocuments(docsToIndex, { ids: uids });\n numAdded += docsToIndex.length - seenDocs.size;\n numUpdated += seenDocs.size;\n }\n\n await recordManager.update(\n hashedDocs.map((doc) => doc.uid),\n { timeAtLeast: indexStartDt, groupIds: sourceIds }\n );\n\n if (cleanup === \"incremental\") {\n sourceIds.forEach((sourceId) => {\n if (!sourceId) throw new Error(\"Source id cannot be null\");\n });\n const uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n groupIds: sourceIds,\n });\n\n if (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n }\n }\n }\n\n if (cleanup === \"full\") {\n let uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n while (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n }\n }\n\n return {\n numAdded,\n numDeleted,\n numUpdated,\n numSkipped,\n };\n}\n"],"mappings":";;;;;;;;;;;AAwCA,IAAa,kBAAb,MAAgE;CAC9D;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AC7B,UAAU,SAAS,aAAa;IAC9B,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,0BAA0B;GAC3D,CAAC;GACD,MAAM,eAAe,MAAM,cAAc,SAAS;IAChD,QAAQ;IACR,UAAU;GACZ,CAAC;GAED,IAAI,aAAa,SAAS,GAAG;IAC3B,MAAM,YAAY,OAAO,EAAE,KAAK,aAAa,CAAC;IAC9C,MAAM,cAAc,WAAW,YAAY;IAC3C,cAAc,aAAa;GAC7B;EACF;CACF;CAEA,IAAI,YAAY,QAAQ;EACtB,IAAI,eAAe,MAAM,cAAc,SAAS;GAC9C,QAAQ;GACR,OAAO;EACT,CAAC;EACD,OAAO,aAAa,SAAS,GAAG;GAC9B,MAAM,YAAY,OAAO,EAAE,KAAK,aAAa,CAAC;GAC9C,MAAM,cAAc,WAAW,YAAY;GAC3C,cAAc,aAAa;GAC3B,eAAe,MAAM,cAAc,SAAS;IAC1C,QAAQ;IACR,OAAO;GACT,CAAC;EACH;CACF;CAEA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base.js","names":["uuidv5"],"sources":["../../src/indexing/base.ts"],"sourcesContent":["import { v5 as uuidv5 } from \"../utils/uuid/index.js\";\nimport { VectorStore } from \"../vectorstores.js\";\nimport { RecordManagerInterface, UUIDV5_NAMESPACE } from \"./record_manager.js\";\nimport { sha256, type HashKeyEncoder } from \"../utils/hash.js\";\nimport { DocumentInterface, Document } from \"../documents/document.js\";\nimport { BaseDocumentLoader } from \"../document_loaders/base.js\";\n\ntype Metadata = Record<string, unknown>;\n\ntype IndexingResult = {\n numAdded: number;\n numDeleted: number;\n numUpdated: number;\n numSkipped: number;\n};\n\ntype StringOrDocFunc = string | ((doc: DocumentInterface) => string);\n\nexport interface HashedDocumentInterface extends DocumentInterface {\n uid: string;\n hash_?: string;\n contentHash?: string;\n metadataHash?: string;\n pageContent: string;\n metadata: Metadata;\n calculateHashes(): void;\n toDocument(): DocumentInterface;\n}\n\ninterface HashedDocumentArgs {\n pageContent: string;\n metadata: Metadata;\n uid: string;\n}\n\n/**\n * HashedDocument is a Document with hashes calculated.\n * Hashes are calculated based on page content and metadata.\n * It is used for indexing.\n */\nexport class _HashedDocument implements HashedDocumentInterface {\n uid: string;\n\n hash_?: string;\n\n contentHash?: string;\n\n metadataHash?: string;\n\n pageContent: string;\n\n metadata: Metadata;\n\n private keyEncoder: HashKeyEncoder = sha256;\n\n constructor(fields: HashedDocumentArgs) {\n this.uid = fields.uid;\n this.pageContent = fields.pageContent;\n this.metadata = fields.metadata;\n }\n\n makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void {\n this.keyEncoder = keyEncoderFn;\n }\n\n calculateHashes(): void {\n const forbiddenKeys = [\"hash_\", \"content_hash\", \"metadata_hash\"];\n\n for (const key of forbiddenKeys) {\n if (key in this.metadata) {\n throw new Error(\n `Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(\n \", \"\n )}]`\n );\n }\n }\n\n const contentHash = this._hashStringToUUID(this.pageContent);\n\n try {\n const metadataHash = this._hashNestedDictToUUID(this.metadata);\n this.contentHash = contentHash;\n this.metadataHash = metadataHash;\n } catch (e) {\n throw new Error(\n `Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`\n );\n }\n\n this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash);\n\n if (!this.uid) {\n this.uid = this.hash_;\n }\n }\n\n toDocument(): DocumentInterface {\n return new Document({\n pageContent: this.pageContent,\n metadata: this.metadata,\n });\n }\n\n static fromDocument(\n document: DocumentInterface,\n uid?: string\n ): _HashedDocument {\n const doc = new this({\n pageContent: document.pageContent,\n metadata: document.metadata,\n uid: uid || (document as DocumentInterface & { uid: string }).uid,\n });\n doc.calculateHashes();\n return doc;\n }\n\n private _hashStringToUUID(inputString: string): string {\n const hash_value = this.keyEncoder(inputString);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n\n private _hashNestedDictToUUID(data: Record<string, unknown>): string {\n const serialized_data = JSON.stringify(data, Object.keys(data).sort());\n const hash_value = this.keyEncoder(serialized_data);\n return uuidv5(hash_value, UUIDV5_NAMESPACE);\n }\n}\n\nexport type CleanupMode = \"full\" | \"incremental\";\n\nexport type IndexOptions = {\n /**\n * The number of documents to index in one batch.\n */\n batchSize?: number;\n /**\n * The cleanup mode to use. Can be \"full\", \"incremental\" or undefined.\n * - **Incremental**: Cleans up all documents that haven't been updated AND\n * that are associated with source ids that were seen\n * during indexing.\n * Clean up is done continuously during indexing helping\n * to minimize the probability of users seeing duplicated\n * content.\n * - **Full**: Delete all documents that haven to been returned by the loader.\n * Clean up runs after all documents have been indexed.\n * This means that users may see duplicated content during indexing.\n * - **undefined**: Do not delete any documents.\n */\n cleanup?: CleanupMode;\n /**\n * Optional key that helps identify the original source of the document.\n * Must either be a string representing the key of the source in the metadata\n * or a function that takes a document and returns a string representing the source.\n * **Required when cleanup is incremental**.\n */\n sourceIdKey?: StringOrDocFunc;\n /**\n * Batch size to use when cleaning up documents.\n */\n cleanupBatchSize?: number;\n /**\n * Force update documents even if they are present in the\n * record manager. Useful if you are re-indexing with updated embeddings.\n */\n forceUpdate?: boolean;\n};\n\nexport function _batch<T>(size: number, iterable: T[]): T[][] {\n const batches: T[][] = [];\n let currentBatch: T[] = [];\n\n iterable.forEach((item) => {\n currentBatch.push(item);\n\n if (currentBatch.length >= size) {\n batches.push(currentBatch);\n currentBatch = [];\n }\n });\n\n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n\n return batches;\n}\n\nexport function _deduplicateInOrder(\n hashedDocuments: HashedDocumentInterface[]\n): HashedDocumentInterface[] {\n const seen = new Set<string>();\n const deduplicated: HashedDocumentInterface[] = [];\n\n for (const hashedDoc of hashedDocuments) {\n if (!hashedDoc.hash_) {\n throw new Error(\"Hashed document does not have a hash\");\n }\n\n if (!seen.has(hashedDoc.hash_)) {\n seen.add(hashedDoc.hash_);\n deduplicated.push(hashedDoc);\n }\n }\n return deduplicated;\n}\n\nexport function _getSourceIdAssigner(\n sourceIdKey: StringOrDocFunc | null\n): (doc: DocumentInterface) => string | null {\n if (sourceIdKey === null) {\n return (_doc: DocumentInterface) => null;\n } else if (typeof sourceIdKey === \"string\") {\n return (doc: DocumentInterface) => doc.metadata[sourceIdKey];\n } else if (typeof sourceIdKey === \"function\") {\n return sourceIdKey;\n } else {\n throw new Error(\n `sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`\n );\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _isBaseDocumentLoader = (arg: any): arg is BaseDocumentLoader => {\n if (\n \"load\" in arg &&\n typeof arg.load === \"function\" &&\n \"loadAndSplit\" in arg &&\n typeof arg.loadAndSplit === \"function\"\n ) {\n return true;\n }\n return false;\n};\n\ninterface IndexArgs {\n docsSource: BaseDocumentLoader | DocumentInterface[];\n recordManager: RecordManagerInterface;\n vectorStore: VectorStore;\n options?: IndexOptions;\n}\n\n/**\n * Index data from the doc source into the vector store.\n *\n * Indexing functionality uses a manager to keep track of which documents\n * are in the vector store.\n *\n * This allows us to keep track of which documents were updated, and which\n * documents were deleted, which documents should be skipped.\n *\n * For the time being, documents are indexed using their hashes, and users\n * are not able to specify the uid of the document.\n *\n * @param {IndexArgs} args\n * @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents.\n * @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents.\n * @param {VectorStore} args.vectorStore The vector store to use for storing the documents.\n * @param {IndexOptions | undefined} args.options Options for indexing.\n * @returns {Promise<IndexingResult>}\n */\nexport async function index(args: IndexArgs): Promise<IndexingResult> {\n const { docsSource, recordManager, vectorStore, options } = args;\n const {\n batchSize = 100,\n cleanup,\n sourceIdKey,\n cleanupBatchSize = 1000,\n forceUpdate = false,\n } = options ?? {};\n\n if (cleanup === \"incremental\" && !sourceIdKey) {\n throw new Error(\n \"sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.\"\n );\n }\n\n const docs = _isBaseDocumentLoader(docsSource)\n ? await docsSource.load()\n : docsSource;\n\n const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null);\n\n const indexStartDt = await recordManager.getTime();\n let numAdded = 0;\n let numDeleted = 0;\n let numUpdated = 0;\n let numSkipped = 0;\n\n const batches = _batch<DocumentInterface>(batchSize ?? 100, docs);\n\n for (const batch of batches) {\n const hashedDocs = _deduplicateInOrder(\n batch.map((doc) => _HashedDocument.fromDocument(doc))\n );\n\n const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc));\n\n if (cleanup === \"incremental\") {\n hashedDocs.forEach((_hashedDoc, index) => {\n const source = sourceIds[index];\n if (source === null) {\n throw new Error(\n \"sourceIdKey must be provided when cleanup is incremental\"\n );\n }\n });\n }\n\n const batchExists = await recordManager.exists(\n hashedDocs.map((doc) => doc.uid)\n );\n\n const uids: string[] = [];\n const docsToIndex: DocumentInterface[] = [];\n const docsToUpdate: string[] = [];\n const seenDocs = new Set<string>();\n hashedDocs.forEach((hashedDoc, i) => {\n const docExists = batchExists[i];\n if (docExists) {\n if (forceUpdate) {\n seenDocs.add(hashedDoc.uid);\n } else {\n docsToUpdate.push(hashedDoc.uid);\n return;\n }\n }\n uids.push(hashedDoc.uid);\n docsToIndex.push(hashedDoc.toDocument());\n });\n\n if (docsToUpdate.length > 0) {\n await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt });\n numSkipped += docsToUpdate.length;\n }\n\n if (docsToIndex.length > 0) {\n await vectorStore.addDocuments(docsToIndex, { ids: uids });\n numAdded += docsToIndex.length - seenDocs.size;\n numUpdated += seenDocs.size;\n }\n\n await recordManager.update(\n hashedDocs.map((doc) => doc.uid),\n { timeAtLeast: indexStartDt, groupIds: sourceIds }\n );\n\n if (cleanup === \"incremental\") {\n sourceIds.forEach((sourceId) => {\n if (!sourceId) throw new Error(\"Source id cannot be null\");\n });\n const uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n groupIds: sourceIds,\n });\n\n if (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n }\n }\n }\n\n if (cleanup === \"full\") {\n let uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n while (uidsToDelete.length > 0) {\n await vectorStore.delete({ ids: uidsToDelete });\n await recordManager.deleteKeys(uidsToDelete);\n numDeleted += uidsToDelete.length;\n uidsToDelete = await recordManager.listKeys({\n before: indexStartDt,\n limit: cleanupBatchSize,\n });\n }\n }\n\n return {\n numAdded,\n numDeleted,\n numUpdated,\n numSkipped,\n };\n}\n"],"mappings":";;;;;;;;;;;AAwCA,IAAa,kBAAb,MAAgE;CAC9D;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,aAAqC;CAErC,YAAY,QAA4B;EACtC,KAAK,MAAM,OAAO;EAClB,KAAK,cAAc,OAAO;EAC1B,KAAK,WAAW,OAAO;CACzB;CAEA,sBAAsB,cAAoC;EACxD,KAAK,aAAa;CACpB;CAEA,kBAAwB;EACtB,MAAM,gBAAgB;GAAC;GAAS;GAAgB;EAAe;EAE/D,KAAK,MAAM,OAAO,eAChB,IAAI,OAAO,KAAK,UACd,MAAM,IAAI,MACR,+BAA+B,IAAI,yDAAyD,cAAc,KACxG,IACF,EAAE,EACJ;EAIJ,MAAM,cAAc,KAAK,kBAAkB,KAAK,WAAW;EAE3D,IAAI;GACF,MAAM,eAAe,KAAK,sBAAsB,KAAK,QAAQ;GAC7D,KAAK,cAAc;GACnB,KAAK,eAAe;EACtB,SAAS,GAAG;GACV,MAAM,IAAI,MACR,4BAA4B,EAAE,uDAChC;EACF;EAEA,KAAK,QAAQ,KAAK,kBAAkB,KAAK,cAAc,KAAK,YAAY;EAExE,IAAI,CAAC,KAAK,KACR,KAAK,MAAM,KAAK;CAEpB;CAEA,aAAgC;EAC9B,OAAO,IAAI,SAAS;GAClB,aA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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.2.
|
|
142
|
+
this._addVersion("@langchain/core", "1.2.11");
|
|
143
143
|
}
|
|
144
144
|
_addVersion(pkg, version) {
|
|
145
145
|
const existing = this.metadata?.versions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["encodingForModel","Runnable","InMemoryCache","AsyncCaller","StringPromptValue","ChatPromptValue","coerceMessageLikeToMessage"],"sources":["../../src/language_models/base.ts"],"sourcesContent":["import type { Tiktoken, TiktokenModel } from \"js-tiktoken/lite\";\nimport type { ZodV3Like, ZodV4Like } from \"../utils/types/zod.js\";\n\nimport { type BaseCache, InMemoryCache } from \"../caches/index.js\";\nimport {\n type BasePromptValueInterface,\n StringPromptValue,\n ChatPromptValue,\n} from \"../prompt_values.js\";\nimport {\n type BaseMessage,\n type BaseMessageLike,\n type MessageContent,\n} from \"../messages/base.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { type LLMResult } from \"../outputs.js\";\nimport { CallbackManager, Callbacks } from \"../callbacks/manager.js\";\nimport { AsyncCaller, AsyncCallerParams } from \"../utils/async_caller.js\";\nimport { encodingForModel } from \"../utils/tiktoken.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport {\n InferInteropZodOutput,\n InteropZodObject,\n InteropZodType,\n} from \"../utils/types/zod.js\";\nimport { ModelProfile } from \"./profile.js\";\nimport { type SerializableSchema } from \"../utils/standard_schema.js\";\n\n// https://www.npmjs.com/package/js-tiktoken\n\nexport const getModelNameForTiktoken = (modelName: string): TiktokenModel => {\n if (modelName.startsWith(\"gpt-5\")) {\n return \"gpt-5\" as TiktokenModel;\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-16k\")) {\n return \"gpt-3.5-turbo-16k\";\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-\")) {\n return \"gpt-3.5-turbo\";\n }\n\n if (modelName.startsWith(\"gpt-4-32k\")) {\n return \"gpt-4-32k\";\n }\n\n if (modelName.startsWith(\"gpt-4-\")) {\n return \"gpt-4\";\n }\n\n if (modelName.startsWith(\"gpt-4o\")) {\n return \"gpt-4o\";\n }\n\n return modelName as TiktokenModel;\n};\n\nexport const getEmbeddingContextSize = (modelName?: string): number => {\n switch (modelName) {\n case \"text-embedding-ada-002\":\n return 8191;\n default:\n return 2046;\n }\n};\n\n/**\n * Get the context window size (max input tokens) for a given model.\n *\n * Context window sizes are sourced from official model documentation:\n * - OpenAI: https://platform.openai.com/docs/models\n * - Anthropic: https://docs.anthropic.com/claude/docs/models-overview\n * - Google: https://ai.google.dev/gemini/docs/models/gemini\n *\n * @param modelName - The name of the model\n * @returns The context window size in tokens\n */\nexport const getModelContextSize = (modelName: string): number => {\n const normalizedName = getModelNameForTiktoken(modelName) as string;\n\n switch (normalizedName) {\n // GPT-5 series\n case \"gpt-5\":\n case \"gpt-5-turbo\":\n case \"gpt-5-turbo-preview\":\n return 400000;\n\n // GPT-4o series\n case \"gpt-4o\":\n case \"gpt-4o-mini\":\n case \"gpt-4o-2024-05-13\":\n case \"gpt-4o-2024-08-06\":\n return 128000;\n\n // GPT-4 Turbo series\n case \"gpt-4-turbo\":\n case \"gpt-4-turbo-preview\":\n case \"gpt-4-turbo-2024-04-09\":\n case \"gpt-4-0125-preview\":\n case \"gpt-4-1106-preview\":\n return 128000;\n\n // GPT-4 series\n case \"gpt-4-32k\":\n case \"gpt-4-32k-0314\":\n case \"gpt-4-32k-0613\":\n return 32768;\n case \"gpt-4\":\n case \"gpt-4-0314\":\n case \"gpt-4-0613\":\n return 8192;\n\n // GPT-3.5 Turbo series\n case \"gpt-3.5-turbo-16k\":\n case \"gpt-3.5-turbo-16k-0613\":\n return 16384;\n case \"gpt-3.5-turbo\":\n case \"gpt-3.5-turbo-0301\":\n case \"gpt-3.5-turbo-0613\":\n case \"gpt-3.5-turbo-1106\":\n case \"gpt-3.5-turbo-0125\":\n return 4096;\n\n // Legacy GPT-3 models\n case \"text-davinci-003\":\n case \"text-davinci-002\":\n return 4097;\n case \"text-davinci-001\":\n return 2049;\n case \"text-curie-001\":\n case \"text-babbage-001\":\n case \"text-ada-001\":\n return 2048;\n\n // Code models\n case \"code-davinci-002\":\n case \"code-davinci-001\":\n return 8000;\n case \"code-cushman-001\":\n return 2048;\n\n // Claude models (Anthropic)\n case \"claude-3-5-sonnet-20241022\":\n case \"claude-3-5-sonnet-20240620\":\n case \"claude-3-opus-20240229\":\n case \"claude-3-sonnet-20240229\":\n case \"claude-3-haiku-20240307\":\n case \"claude-2.1\":\n return 200000;\n case \"claude-2.0\":\n case \"claude-instant-1.2\":\n return 100000;\n\n // Gemini models (Google)\n case \"gemini-1.5-pro\":\n case \"gemini-1.5-pro-latest\":\n case \"gemini-1.5-flash\":\n case \"gemini-1.5-flash-latest\":\n return 1000000; // 1M tokens\n case \"gemini-pro\":\n case \"gemini-pro-vision\":\n return 32768;\n\n default:\n return 4097;\n }\n};\n\n/**\n * Whether or not the input matches the OpenAI tool definition.\n * @param {unknown} tool The input to check.\n * @returns {boolean} Whether the input is an OpenAI tool definition.\n */\nexport function isOpenAITool(tool: unknown): tool is ToolDefinition {\n if (typeof tool !== \"object\" || !tool) return false;\n if (\n \"type\" in tool &&\n tool.type === \"function\" &&\n \"function\" in tool &&\n typeof tool.function === \"object\" &&\n tool.function &&\n \"name\" in tool.function &&\n \"parameters\" in tool.function\n ) {\n return true;\n }\n return false;\n}\n\ninterface CalculateMaxTokenProps {\n prompt: string;\n modelName: TiktokenModel;\n}\n\nexport const calculateMaxTokens = async ({\n prompt,\n modelName,\n}: CalculateMaxTokenProps) => {\n let numTokens;\n\n try {\n numTokens = (\n await encodingForModel(getModelNameForTiktoken(modelName))\n ).encode(prompt).length;\n } catch {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\"\n );\n\n // fallback to approximate calculation if tiktoken is not available\n // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them#\n numTokens = Math.ceil(prompt.length / 4);\n }\n\n const maxTokens = getModelContextSize(modelName);\n return maxTokens - numTokens;\n};\n\nconst getVerbosity = () => false;\n\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n} & Record<string, any>;\n\nexport interface BaseLangChainParams {\n verbose?: boolean;\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Base class for language models, chains, tools.\n */\nexport abstract class BaseLangChain<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Runnable<RunInput, RunOutput, CallOptions>\n implements BaseLangChainParams\n{\n /**\n * Whether to print out response text.\n */\n verbose: boolean;\n\n callbacks?: Callbacks;\n\n tags?: string[];\n\n metadata?: Record<string, unknown>;\n\n get lc_attributes(): { [key: string]: undefined } | undefined {\n return {\n callbacks: undefined,\n verbose: undefined,\n };\n }\n\n constructor(params: BaseLangChainParams) {\n super(params);\n this.verbose = params.verbose ?? getVerbosity();\n this.callbacks = params.callbacks;\n this.tags = params.tags ?? [];\n this.metadata = params.metadata ?? {};\n this._addVersion(\"@langchain/core\", __PKG_VERSION__);\n }\n\n protected _addVersion(pkg: string, version: string) {\n const existing = this.metadata?.versions;\n this.metadata = {\n ...this.metadata,\n versions: {\n ...(typeof existing === \"object\" && existing !== null ? existing : {}),\n [pkg]: version,\n },\n };\n }\n}\n\n/**\n * Base interface for language model parameters.\n * A subclass of {@link BaseLanguageModel} should have a constructor that\n * takes in a parameter that extends this interface.\n */\nexport interface BaseLanguageModelParams\n extends AsyncCallerParams, BaseLangChainParams {\n /**\n * @deprecated Use `callbacks` instead\n */\n callbackManager?: CallbackManager;\n\n cache?: BaseCache | boolean;\n}\n\nexport interface BaseLanguageModelTracingCallOptions {\n /**\n * Describes the format of structured outputs.\n * This should be provided if an output is considered to be structured\n */\n ls_structured_output_format?: {\n /**\n * An object containing the method used for structured output (e.g., \"jsonMode\").\n */\n kwargs: { method: string };\n /**\n * The JSON schema describing the expected output structure.\n */\n schema?: JSONSchema;\n };\n}\n\nexport interface BaseLanguageModelCallOptions\n extends RunnableConfig, BaseLanguageModelTracingCallOptions {\n /**\n * Stop tokens to use for this call.\n * If not provided, the default stop tokens for the model will be used.\n */\n stop?: string[];\n /**\n * Overrides the model's configured `maxRetries` for this call only.\n */\n maxRetries?: number;\n}\n\nexport interface FunctionDefinition {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](https://platform.openai.com/docs/guides/gpt/function-calling) for\n * examples, and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * To describe a function that accepts no parameters, provide the value\n * `{\"type\": \"object\", \"properties\": {}}`.\n */\n parameters: Record<string, unknown> | JSONSchema;\n\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: FunctionDefinition;\n}\n\nexport type FunctionCallOption = {\n name: string;\n};\n\nexport interface BaseFunctionCallOptions extends BaseLanguageModelCallOptions {\n function_call?: FunctionCallOption;\n functions?: FunctionDefinition[];\n}\n\nexport type BaseLanguageModelInput =\n | BasePromptValueInterface\n | string\n | BaseMessageLike[];\n\nexport type StructuredOutputType = InferInteropZodOutput<InteropZodObject>;\n\nexport type StructuredOutputMethodOptions<IncludeRaw extends boolean = false> =\n {\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\" | \"jsonSchema\" | string;\n includeRaw?: IncludeRaw;\n /** Whether to use strict mode. Currently only supported by OpenAI models. */\n strict?: boolean;\n };\n\n/** @deprecated Use StructuredOutputMethodOptions instead */\nexport type StructuredOutputMethodParams<\n RunOutput,\n IncludeRaw extends boolean = false,\n> = {\n /** @deprecated Pass schema in as the first argument */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n schema: InteropZodType<RunOutput> | Record<string, any>;\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\";\n includeRaw?: IncludeRaw;\n};\n\nexport interface BaseLanguageModelInterface<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n> extends RunnableInterface<BaseLanguageModelInput, RunOutput, CallOptions> {\n get callKeys(): string[];\n\n generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | Partial<CallOptions>,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n _modelType(): string;\n\n _llmType(): string;\n\n getNumTokens(content: MessageContent): Promise<number>;\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any>;\n\n serialize(): SerializedLLM;\n}\n\nexport type LanguageModelOutput = BaseMessage | string;\n\nexport type LanguageModelLike = RunnableInterface<\n BaseLanguageModelInput,\n LanguageModelOutput\n>;\n\n/**\n * Base class for language models.\n */\nexport abstract class BaseLanguageModel<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n>\n extends BaseLangChain<BaseLanguageModelInput, RunOutput, CallOptions>\n implements\n BaseLanguageModelParams,\n BaseLanguageModelInterface<RunOutput, CallOptions>\n{\n /**\n * Keys that the language model accepts as call options.\n */\n get callKeys(): string[] {\n return [\"stop\", \"timeout\", \"signal\", \"tags\", \"metadata\", \"callbacks\"];\n }\n\n /**\n * The async caller should be used by subclasses to make any async calls,\n * which will thus benefit from the concurrency and retry logic.\n */\n caller: AsyncCaller;\n\n cache?: BaseCache;\n\n constructor({\n callbacks,\n callbackManager,\n ...params\n }: BaseLanguageModelParams) {\n const { cache, ...rest } = params;\n super({\n callbacks: callbacks ?? callbackManager,\n ...rest,\n });\n if (typeof cache === \"object\") {\n this.cache = cache;\n } else if (cache) {\n this.cache = InMemoryCache.global();\n } else {\n this.cache = undefined;\n }\n this.caller = new AsyncCaller(params ?? {});\n }\n\n abstract generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | CallOptions,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n abstract _modelType(): string;\n\n abstract _llmType(): string;\n\n private _encoding?: Tiktoken;\n\n /**\n * Get the number of tokens in the content.\n * @param content The content to get the number of tokens for.\n * @returns The number of tokens in the content.\n */\n async getNumTokens(content: MessageContent) {\n // Extract text content from MessageContent\n let textContent: string;\n if (typeof content === \"string\") {\n textContent = content;\n } else {\n /**\n * Content is an array of ContentBlock\n *\n * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content.\n * We need to find a better way to do this.\n * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116\n */\n textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n }\n\n // fallback to approximate calculation if tiktoken is not available\n let numTokens = Math.ceil(textContent.length / 4);\n\n if (!this._encoding) {\n try {\n this._encoding = await encodingForModel(\n \"modelName\" in this\n ? getModelNameForTiktoken(this.modelName as string)\n : \"gpt2\"\n );\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n if (this._encoding) {\n try {\n numTokens = this._encoding.encode(textContent).length;\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n return numTokens;\n }\n\n protected static _convertInputToPromptValue(\n input: BaseLanguageModelInput\n ): BasePromptValueInterface {\n if (typeof input === \"string\") {\n return new StringPromptValue(input);\n } else if (Array.isArray(input)) {\n return new ChatPromptValue(input.map(coerceMessageLikeToMessage));\n } else {\n return input;\n }\n }\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any> {\n return {};\n }\n\n /**\n * Create a unique cache key for a specific call to a specific language model.\n * @param callOptions Call options for the model\n * @returns A unique cache key.\n */\n _getSerializedCacheKeyParametersForCall(\n // TODO: Fix when we remove the RunnableLambda backwards compatibility shim.\n {\n config,\n ...callOptions\n }: CallOptions & { config?: RunnableConfig }\n ): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const params: Record<string, any> = {\n ...this._identifyingParams(),\n ...callOptions,\n _type: this._llmType(),\n _model: this._modelType(),\n };\n const filteredEntries = Object.entries(params).filter(\n ([_, value]) => value !== undefined\n );\n const serializedEntries = filteredEntries\n .map(([key, value]) => `${key}:${JSON.stringify(value)}`)\n .sort()\n .join(\",\");\n return serializedEntries;\n }\n\n /**\n * @deprecated\n * Return a json-like object representing this LLM.\n */\n serialize(): SerializedLLM {\n return {\n ...this._identifyingParams(),\n _type: this._llmType(),\n _model: this._modelType(),\n };\n }\n\n /**\n * @deprecated\n * Load an LLM from a json-like object describing it.\n */\n static async deserialize(_data: SerializedLLM): Promise<BaseLanguageModel> {\n throw new Error(\"Use .toJSON() instead\");\n }\n\n /**\n * Return profiling information for the model.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return {};\n }\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Model wrapper that returns outputs formatted to match the given schema.\n *\n * @template {BaseLanguageModelInput} RunInput The input type for the Runnable, expected to be the same input for the LLM.\n * @template {Record<string, any>} RunOutput The output type for the Runnable, expected to be a Zod schema object for structured output validation.\n *\n * @param {InteropZodType<RunOutput>} schema The schema for the structured output. Either as a Zod schema or a valid JSON schema object.\n * If a Zod schema is passed, the returned attributes will be validated, whereas with JSON schema they will not be.\n * @param {string} name The name of the function to call.\n * @param {\"functionCalling\" | \"jsonMode\"} [method=functionCalling] The method to use for getting the structured output. Defaults to \"functionCalling\".\n * @param {boolean | undefined} [includeRaw=false] Whether to include the raw output in the result. Defaults to false.\n * @returns {Runnable<RunInput, RunOutput> | Runnable<RunInput, { raw: BaseMessage; parsed: RunOutput }>} A new runnable that calls the LLM with structured output.\n */\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | InteropZodType<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n {\n raw: BaseMessage;\n parsed: RunOutput;\n }\n >;\n\n /**\n * Filter out large/inappropriate fields from invocation params for tracing metadata.\n * Removes fields like tools, functions, messages, response_format that can be large.\n */\n protected _filterInvocationParamsForTracing(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n params: Record<string, any>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): Record<string, any> {\n const { tools, functions, messages, response_format, ...rest } = params;\n return rest;\n }\n}\n\n/**\n * Shared interface for token usage\n * return type from LLM calls.\n */\nexport interface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,MAAa,2BAA2B,cAAqC;CAC3E,IAAI,UAAU,WAAW,OAAO,GAC9B,OAAO;CAGT,IAAI,UAAU,WAAW,mBAAmB,GAC1C,OAAO;CAGT,IAAI,UAAU,WAAW,gBAAgB,GACvC,OAAO;CAGT,IAAI,UAAU,WAAW,WAAW,GAClC,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,GAC/B,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,GAC/B,OAAO;CAGT,OAAO;A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zB;;;;;CAMA,YAA2B;EACzB,OAAO;GACL,GAAG,KAAK,mBAAmB;GAC3B,OAAO,KAAK,SAAS;GACrB,QAAQ,KAAK,WAAW;EAC1B;CACF;;;;;CAMA,aAAa,YAAY,OAAkD;EACzE,MAAM,IAAI,MAAM,uBAAuB;CACzC;;;;;;CAOA,IAAI,UAAwB;EAC1B,OAAO,CAAC;CACV;;;;;CAkGA,kCAEE,QAEqB;EACrB,MAAM,EAAE,OAAO,WAAW,UAAU,iBAAiB,GAAG,SAAS;EACjE,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"base.cjs","names":["encodingForModel","Runnable","InMemoryCache","AsyncCaller","StringPromptValue","ChatPromptValue","coerceMessageLikeToMessage"],"sources":["../../src/language_models/base.ts"],"sourcesContent":["import type { Tiktoken, TiktokenModel } from \"js-tiktoken/lite\";\nimport type { ZodV3Like, ZodV4Like } from \"../utils/types/zod.js\";\n\nimport { type BaseCache, InMemoryCache } from \"../caches/index.js\";\nimport {\n type BasePromptValueInterface,\n StringPromptValue,\n ChatPromptValue,\n} from \"../prompt_values.js\";\nimport {\n type BaseMessage,\n type BaseMessageLike,\n type MessageContent,\n} from \"../messages/base.js\";\nimport { coerceMessageLikeToMessage } from \"../messages/utils.js\";\nimport { type LLMResult } from \"../outputs.js\";\nimport { CallbackManager, Callbacks } from \"../callbacks/manager.js\";\nimport { AsyncCaller, AsyncCallerParams } from \"../utils/async_caller.js\";\nimport { encodingForModel } from \"../utils/tiktoken.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport {\n InferInteropZodOutput,\n InteropZodObject,\n InteropZodType,\n} from \"../utils/types/zod.js\";\nimport { ModelProfile } from \"./profile.js\";\nimport { type SerializableSchema } from \"../utils/standard_schema.js\";\n\n// https://www.npmjs.com/package/js-tiktoken\n\nexport const getModelNameForTiktoken = (modelName: string): TiktokenModel => {\n if (modelName.startsWith(\"gpt-5\")) {\n return \"gpt-5\" as TiktokenModel;\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-16k\")) {\n return \"gpt-3.5-turbo-16k\";\n }\n\n if (modelName.startsWith(\"gpt-3.5-turbo-\")) {\n return \"gpt-3.5-turbo\";\n }\n\n if (modelName.startsWith(\"gpt-4-32k\")) {\n return \"gpt-4-32k\";\n }\n\n if (modelName.startsWith(\"gpt-4-\")) {\n return \"gpt-4\";\n }\n\n if (modelName.startsWith(\"gpt-4o\")) {\n return \"gpt-4o\";\n }\n\n return modelName as TiktokenModel;\n};\n\nexport const getEmbeddingContextSize = (modelName?: string): number => {\n switch (modelName) {\n case \"text-embedding-ada-002\":\n return 8191;\n default:\n return 2046;\n }\n};\n\n/**\n * Get the context window size (max input tokens) for a given model.\n *\n * Context window sizes are sourced from official model documentation:\n * - OpenAI: https://platform.openai.com/docs/models\n * - Anthropic: https://docs.anthropic.com/claude/docs/models-overview\n * - Google: https://ai.google.dev/gemini/docs/models/gemini\n *\n * @param modelName - The name of the model\n * @returns The context window size in tokens\n */\nexport const getModelContextSize = (modelName: string): number => {\n const normalizedName = getModelNameForTiktoken(modelName) as string;\n\n switch (normalizedName) {\n // GPT-5 series\n case \"gpt-5\":\n case \"gpt-5-turbo\":\n case \"gpt-5-turbo-preview\":\n return 400000;\n\n // GPT-4o series\n case \"gpt-4o\":\n case \"gpt-4o-mini\":\n case \"gpt-4o-2024-05-13\":\n case \"gpt-4o-2024-08-06\":\n return 128000;\n\n // GPT-4 Turbo series\n case \"gpt-4-turbo\":\n case \"gpt-4-turbo-preview\":\n case \"gpt-4-turbo-2024-04-09\":\n case \"gpt-4-0125-preview\":\n case \"gpt-4-1106-preview\":\n return 128000;\n\n // GPT-4 series\n case \"gpt-4-32k\":\n case \"gpt-4-32k-0314\":\n case \"gpt-4-32k-0613\":\n return 32768;\n case \"gpt-4\":\n case \"gpt-4-0314\":\n case \"gpt-4-0613\":\n return 8192;\n\n // GPT-3.5 Turbo series\n case \"gpt-3.5-turbo-16k\":\n case \"gpt-3.5-turbo-16k-0613\":\n return 16384;\n case \"gpt-3.5-turbo\":\n case \"gpt-3.5-turbo-0301\":\n case \"gpt-3.5-turbo-0613\":\n case \"gpt-3.5-turbo-1106\":\n case \"gpt-3.5-turbo-0125\":\n return 4096;\n\n // Legacy GPT-3 models\n case \"text-davinci-003\":\n case \"text-davinci-002\":\n return 4097;\n case \"text-davinci-001\":\n return 2049;\n case \"text-curie-001\":\n case \"text-babbage-001\":\n case \"text-ada-001\":\n return 2048;\n\n // Code models\n case \"code-davinci-002\":\n case \"code-davinci-001\":\n return 8000;\n case \"code-cushman-001\":\n return 2048;\n\n // Claude models (Anthropic)\n case \"claude-3-5-sonnet-20241022\":\n case \"claude-3-5-sonnet-20240620\":\n case \"claude-3-opus-20240229\":\n case \"claude-3-sonnet-20240229\":\n case \"claude-3-haiku-20240307\":\n case \"claude-2.1\":\n return 200000;\n case \"claude-2.0\":\n case \"claude-instant-1.2\":\n return 100000;\n\n // Gemini models (Google)\n case \"gemini-1.5-pro\":\n case \"gemini-1.5-pro-latest\":\n case \"gemini-1.5-flash\":\n case \"gemini-1.5-flash-latest\":\n return 1000000; // 1M tokens\n case \"gemini-pro\":\n case \"gemini-pro-vision\":\n return 32768;\n\n default:\n return 4097;\n }\n};\n\n/**\n * Whether or not the input matches the OpenAI tool definition.\n * @param {unknown} tool The input to check.\n * @returns {boolean} Whether the input is an OpenAI tool definition.\n */\nexport function isOpenAITool(tool: unknown): tool is ToolDefinition {\n if (typeof tool !== \"object\" || !tool) return false;\n if (\n \"type\" in tool &&\n tool.type === \"function\" &&\n \"function\" in tool &&\n typeof tool.function === \"object\" &&\n tool.function &&\n \"name\" in tool.function &&\n \"parameters\" in tool.function\n ) {\n return true;\n }\n return false;\n}\n\ninterface CalculateMaxTokenProps {\n prompt: string;\n modelName: TiktokenModel;\n}\n\nexport const calculateMaxTokens = async ({\n prompt,\n modelName,\n}: CalculateMaxTokenProps) => {\n let numTokens;\n\n try {\n numTokens = (\n await encodingForModel(getModelNameForTiktoken(modelName))\n ).encode(prompt).length;\n } catch {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\"\n );\n\n // fallback to approximate calculation if tiktoken is not available\n // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them#\n numTokens = Math.ceil(prompt.length / 4);\n }\n\n const maxTokens = getModelContextSize(modelName);\n return maxTokens - numTokens;\n};\n\nconst getVerbosity = () => false;\n\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n} & Record<string, any>;\n\nexport interface BaseLangChainParams {\n verbose?: boolean;\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Base class for language models, chains, tools.\n */\nexport abstract class BaseLangChain<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Runnable<RunInput, RunOutput, CallOptions>\n implements BaseLangChainParams\n{\n /**\n * Whether to print out response text.\n */\n verbose: boolean;\n\n callbacks?: Callbacks;\n\n tags?: string[];\n\n metadata?: Record<string, unknown>;\n\n get lc_attributes(): { [key: string]: undefined } | undefined {\n return {\n callbacks: undefined,\n verbose: undefined,\n };\n }\n\n constructor(params: BaseLangChainParams) {\n super(params);\n this.verbose = params.verbose ?? getVerbosity();\n this.callbacks = params.callbacks;\n this.tags = params.tags ?? [];\n this.metadata = params.metadata ?? {};\n this._addVersion(\"@langchain/core\", __PKG_VERSION__);\n }\n\n protected _addVersion(pkg: string, version: string) {\n const existing = this.metadata?.versions;\n this.metadata = {\n ...this.metadata,\n versions: {\n ...(typeof existing === \"object\" && existing !== null ? existing : {}),\n [pkg]: version,\n },\n };\n }\n}\n\n/**\n * Base interface for language model parameters.\n * A subclass of {@link BaseLanguageModel} should have a constructor that\n * takes in a parameter that extends this interface.\n */\nexport interface BaseLanguageModelParams\n extends AsyncCallerParams, BaseLangChainParams {\n /**\n * @deprecated Use `callbacks` instead\n */\n callbackManager?: CallbackManager;\n\n cache?: BaseCache | boolean;\n}\n\nexport interface BaseLanguageModelTracingCallOptions {\n /**\n * Describes the format of structured outputs.\n * This should be provided if an output is considered to be structured\n */\n ls_structured_output_format?: {\n /**\n * An object containing the method used for structured output (e.g., \"jsonMode\").\n */\n kwargs: { method: string };\n /**\n * The JSON schema describing the expected output structure.\n */\n schema?: JSONSchema;\n };\n}\n\nexport interface BaseLanguageModelCallOptions\n extends RunnableConfig, BaseLanguageModelTracingCallOptions {\n /**\n * Stop tokens to use for this call.\n * If not provided, the default stop tokens for the model will be used.\n */\n stop?: string[];\n /**\n * Overrides the model's configured `maxRetries` for this call only.\n */\n maxRetries?: number;\n}\n\nexport interface FunctionDefinition {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](https://platform.openai.com/docs/guides/gpt/function-calling) for\n * examples, and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * To describe a function that accepts no parameters, provide the value\n * `{\"type\": \"object\", \"properties\": {}}`.\n */\n parameters: Record<string, unknown> | JSONSchema;\n\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: FunctionDefinition;\n}\n\nexport type FunctionCallOption = {\n name: string;\n};\n\nexport interface BaseFunctionCallOptions extends BaseLanguageModelCallOptions {\n function_call?: FunctionCallOption;\n functions?: FunctionDefinition[];\n}\n\nexport type BaseLanguageModelInput =\n | BasePromptValueInterface\n | string\n | BaseMessageLike[];\n\nexport type StructuredOutputType = InferInteropZodOutput<InteropZodObject>;\n\nexport type StructuredOutputMethodOptions<IncludeRaw extends boolean = false> =\n {\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\" | \"jsonSchema\" | string;\n includeRaw?: IncludeRaw;\n /** Whether to use strict mode. Currently only supported by OpenAI models. */\n strict?: boolean;\n };\n\n/** @deprecated Use StructuredOutputMethodOptions instead */\nexport type StructuredOutputMethodParams<\n RunOutput,\n IncludeRaw extends boolean = false,\n> = {\n /** @deprecated Pass schema in as the first argument */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n schema: InteropZodType<RunOutput> | Record<string, any>;\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\";\n includeRaw?: IncludeRaw;\n};\n\nexport interface BaseLanguageModelInterface<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n> extends RunnableInterface<BaseLanguageModelInput, RunOutput, CallOptions> {\n get callKeys(): string[];\n\n generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | Partial<CallOptions>,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n _modelType(): string;\n\n _llmType(): string;\n\n getNumTokens(content: MessageContent): Promise<number>;\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any>;\n\n serialize(): SerializedLLM;\n}\n\nexport type LanguageModelOutput = BaseMessage | string;\n\nexport type LanguageModelLike = RunnableInterface<\n BaseLanguageModelInput,\n LanguageModelOutput\n>;\n\n/**\n * Base class for language models.\n */\nexport abstract class BaseLanguageModel<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends BaseLanguageModelCallOptions =\n BaseLanguageModelCallOptions,\n>\n extends BaseLangChain<BaseLanguageModelInput, RunOutput, CallOptions>\n implements\n BaseLanguageModelParams,\n BaseLanguageModelInterface<RunOutput, CallOptions>\n{\n /**\n * Keys that the language model accepts as call options.\n */\n get callKeys(): string[] {\n return [\"stop\", \"timeout\", \"signal\", \"tags\", \"metadata\", \"callbacks\"];\n }\n\n /**\n * The async caller should be used by subclasses to make any async calls,\n * which will thus benefit from the concurrency and retry logic.\n */\n caller: AsyncCaller;\n\n cache?: BaseCache;\n\n constructor({\n callbacks,\n callbackManager,\n ...params\n }: BaseLanguageModelParams) {\n const { cache, ...rest } = params;\n super({\n callbacks: callbacks ?? callbackManager,\n ...rest,\n });\n if (typeof cache === \"object\") {\n this.cache = cache;\n } else if (cache) {\n this.cache = InMemoryCache.global();\n } else {\n this.cache = undefined;\n }\n this.caller = new AsyncCaller(params ?? {});\n }\n\n abstract generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | CallOptions,\n callbacks?: Callbacks\n ): Promise<LLMResult>;\n\n abstract _modelType(): string;\n\n abstract _llmType(): string;\n\n private _encoding?: Tiktoken;\n\n /**\n * Get the number of tokens in the content.\n * @param content The content to get the number of tokens for.\n * @returns The number of tokens in the content.\n */\n async getNumTokens(content: MessageContent) {\n // Extract text content from MessageContent\n let textContent: string;\n if (typeof content === \"string\") {\n textContent = content;\n } else {\n /**\n * Content is an array of ContentBlock\n *\n * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content.\n * We need to find a better way to do this.\n * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116\n */\n textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n }\n\n // fallback to approximate calculation if tiktoken is not available\n let numTokens = Math.ceil(textContent.length / 4);\n\n if (!this._encoding) {\n try {\n this._encoding = await encodingForModel(\n \"modelName\" in this\n ? getModelNameForTiktoken(this.modelName as string)\n : \"gpt2\"\n );\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n if (this._encoding) {\n try {\n numTokens = this._encoding.encode(textContent).length;\n } catch (error) {\n console.warn(\n \"Failed to calculate number of tokens, falling back to approximate count\",\n error\n );\n }\n }\n\n return numTokens;\n }\n\n protected static _convertInputToPromptValue(\n input: BaseLanguageModelInput\n ): BasePromptValueInterface {\n if (typeof input === \"string\") {\n return new StringPromptValue(input);\n } else if (Array.isArray(input)) {\n return new ChatPromptValue(input.map(coerceMessageLikeToMessage));\n } else {\n return input;\n }\n }\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any> {\n return {};\n }\n\n /**\n * Create a unique cache key for a specific call to a specific language model.\n * @param callOptions Call options for the model\n * @returns A unique cache key.\n */\n _getSerializedCacheKeyParametersForCall(\n // TODO: Fix when we remove the RunnableLambda backwards compatibility shim.\n {\n config,\n ...callOptions\n }: CallOptions & { config?: RunnableConfig }\n ): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const params: Record<string, any> = {\n ...this._identifyingParams(),\n ...callOptions,\n _type: this._llmType(),\n _model: this._modelType(),\n };\n const filteredEntries = Object.entries(params).filter(\n ([_, value]) => value !== undefined\n );\n const serializedEntries = filteredEntries\n .map(([key, value]) => `${key}:${JSON.stringify(value)}`)\n .sort()\n .join(\",\");\n return serializedEntries;\n }\n\n /**\n * @deprecated\n * Return a json-like object representing this LLM.\n */\n serialize(): SerializedLLM {\n return {\n ...this._identifyingParams(),\n _type: this._llmType(),\n _model: this._modelType(),\n };\n }\n\n /**\n * @deprecated\n * Load an LLM from a json-like object describing it.\n */\n static async deserialize(_data: SerializedLLM): Promise<BaseLanguageModel> {\n throw new Error(\"Use .toJSON() instead\");\n }\n\n /**\n * Return profiling information for the model.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return {};\n }\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema: SerializableSchema<RunOutput>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV3Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | ZodV4Like<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Model wrapper that returns outputs formatted to match the given schema.\n *\n * @template {BaseLanguageModelInput} RunInput The input type for the Runnable, expected to be the same input for the LLM.\n * @template {Record<string, any>} RunOutput The output type for the Runnable, expected to be a Zod schema object for structured output validation.\n *\n * @param {InteropZodType<RunOutput>} schema The schema for the structured output. Either as a Zod schema or a valid JSON schema object.\n * If a Zod schema is passed, the returned attributes will be validated, whereas with JSON schema they will not be.\n * @param {string} name The name of the function to call.\n * @param {\"functionCalling\" | \"jsonMode\"} [method=functionCalling] The method to use for getting the structured output. Defaults to \"functionCalling\".\n * @param {boolean | undefined} [includeRaw=false] Whether to include the raw output in the result. Defaults to false.\n * @returns {Runnable<RunInput, RunOutput> | Runnable<RunInput, { raw: BaseMessage; parsed: RunOutput }>} A new runnable that calls the LLM with structured output.\n */\n withStructuredOutput?<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n schema:\n | InteropZodType<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n {\n raw: BaseMessage;\n parsed: RunOutput;\n }\n >;\n\n /**\n * Filter out large/inappropriate fields from invocation params for tracing metadata.\n * Removes fields like tools, functions, messages, response_format that can be large.\n */\n protected _filterInvocationParamsForTracing(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n params: Record<string, any>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): Record<string, any> {\n const { tools, functions, messages, response_format, ...rest } = params;\n return rest;\n }\n}\n\n/**\n * Shared interface for token usage\n * return type from LLM calls.\n */\nexport interface TokenUsage {\n completionTokens?: number;\n promptTokens?: number;\n totalTokens?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,MAAa,2BAA2B,cAAqC;CAC3E,IAAI,UAAU,WAAW,OAAO,GAC9B,OAAO;CAGT,IAAI,UAAU,WAAW,mBAAmB,GAC1C,OAAO;CAGT,IAAI,UAAU,WAAW,gBAAgB,GACvC,OAAO;CAGT,IAAI,UAAU,WAAW,WAAW,GAClC,OAAO;CAGT,IAAI,UAAU,WAAW,QAAQ,G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AG,KAAK,UAAU,KAAK,GAAG,CAAC,CACxD,KAAK,CAAC,CACN,KAAK,GACe;CACzB;;;;;CAMA,YAA2B;EACzB,OAAO;GACL,GAAG,KAAK,mBAAmB;GAC3B,OAAO,KAAK,SAAS;GACrB,QAAQ,KAAK,WAAW;EAC1B;CACF;;;;;CAMA,aAAa,YAAY,OAAkD;EACzE,MAAM,IAAI,MAAM,uBAAuB;CACzC;;;;;;CAOA,IAAI,UAAwB;EAC1B,OAAO,CAAC;CACV;;;;;CAkGA,kCAEE,QAEqB;EACrB,MAAM,EAAE,OAAO,WAAW,UAAU,iBAAiB,GAAG,SAAS;EACjE,OAAO;CACT;AACF"}
|
|
@@ -138,7 +138,7 @@ var BaseLangChain = class extends Runnable {
|
|
|
138
138
|
this.callbacks = params.callbacks;
|
|
139
139
|
this.tags = params.tags ?? [];
|
|
140
140
|
this.metadata = params.metadata ?? {};
|
|
141
|
-
this._addVersion("@langchain/core", "1.2.
|
|
141
|
+
this._addVersion("@langchain/core", "1.2.11");
|
|
142
142
|
}
|
|
143
143
|
_addVersion(pkg, version) {
|
|
144
144
|
const existing = this.metadata?.versions;
|