LibreChat/packages/api/src/utils/tokenMap.ts
Danny Avila 1b79e0b785
🧬 chore: Align LibreChat With Agents LangChain Upgrade (#12922)
* 🔧 chore: Update dependencies in package-lock.json and package.json

- Bump version of @librechat/agents to 3.1.75-dev.0 in multiple package.json files.
- Upgrade various AWS SDK and Smithy dependencies to their latest versions in package-lock.json for improved stability and performance.

* 🔧 chore: Update AWS SDK and Smithy dependencies in package-lock.json

- Bump version of @aws-sdk/client-bedrock-runtime to 3.1041.0 and update related dependencies for improved performance and stability.
- Upgrade various AWS SDK and Smithy packages to their latest versions, ensuring compatibility and enhanced functionality.

* chore: Align LibreChat with agents LangChain upgrade

- Route LangChain imports through @librechat/agents facade exports
- Update @librechat/agents to 3.1.75-dev.1 and remove direct LangChain deps
- Normalize nullable agent model params and API key override typing
- Update Google thinking config typing for newer LangChain packages
- Refresh targeted audit-related dependency overrides

* chore: Add Jest types for API specs

* test: Fix LangChain upgrade CI specs

* test: Exercise agents env facade

* fix: Clean up TS preview diagnostics

* fix: Address Codex review feedback
2026-05-03 12:46:01 -04:00

45 lines
1.4 KiB
TypeScript

import type { BaseMessage } from '@librechat/agents/langchain/messages';
/** Signature for a function that counts tokens in a LangChain message. */
export type TokenCounter = (message: BaseMessage) => number;
/**
* Lazily fills missing token counts for formatted LangChain messages.
* Preserves precomputed counts and only computes undefined indices.
*
* This is used after `formatAgentMessages` to ensure every message index
* has a token count before passing `indexTokenCountMap` to the agent run.
*/
export function hydrateMissingIndexTokenCounts({
messages,
indexTokenCountMap,
tokenCounter,
}: {
messages: BaseMessage[];
indexTokenCountMap: Record<number, number | undefined> | undefined;
tokenCounter: TokenCounter;
}): Record<number, number> {
const hydratedMap: Record<number, number> = {};
if (indexTokenCountMap) {
for (const key in indexTokenCountMap) {
const tokenCount = indexTokenCountMap[Number(key)];
if (typeof tokenCount === 'number' && Number.isFinite(tokenCount) && tokenCount > 0) {
hydratedMap[Number(key)] = tokenCount;
}
}
}
for (let i = 0; i < messages.length; i++) {
if (
typeof hydratedMap[i] === 'number' &&
Number.isFinite(hydratedMap[i]) &&
hydratedMap[i] > 0
) {
continue;
}
hydratedMap[i] = tokenCounter(messages[i]);
}
return hydratedMap;
}