Skip to content

Commit 5813fdf

Browse files
jmaddingtondanny-avilaberry-13
authored
Tracking/2025/04/16 (#76)
* 🖥️ feat: Code Interpreter API for Non-Agent Endpoints (danny-avila#6803) * fix: Prevent parsing 'undefined' string in useLocalStorage initialization * feat: first pass, code interpreter badge * feat: Integrate API key authentication and default checked value in Code Interpreter Badge * refactor: Rename showMCPServers to showEphemeralBadges and update related components, memoize values in useChatBadges * refactor: Enhance AttachFileChat to support ephemeral agents in file attachment logic * fix: Add baseURL configuration option to legacy function call * refactor: Update dependency array in useDragHelpers to include handleFiles * refactor: Update isEphemeralAgent function to accept optional endpoint parameter * refactor: Update file handling to support ephemeral agents in AttachFileMenu and useDragHelpers * fix: improve compatibility issues with OpenAI usage field handling in createRun function * refactor: usage field compatibility * fix: ensure mcp servers are no longer "selected" if mcp servers are now unavailable * 💾 chore: Enhance Local Storage Handling and Update MCP SDK (danny-avila#6809) * feat: Update MCP package version and dependencies; refactor ToolContentPart type * refactor: Change module type to commonjs and update rollup configuration, remove unused dev dependency * refactor: Change async calls to synchronous for MCP and FlowStateManager retrieval * chore: Add eslint disable comment for i18next rule in DropdownPopup component * fix: improve statefulness of mcp servers selected if some were removed since last session * feat: implement conversation storage cleanup functions and integrate them into mutation success handlers * feat: enhance storage condition logic in useLocalStorageAlt to prevent unnecessary local storage writes * refactor: streamline local storage update logic in useLocalStorageAlt * ⚡ feat: Self-hosted Artifacts Static Bundler URL (danny-avila#6827) * v0.7.791 * feat: configuration via `SANDPACK_STATIC_BUNDLER_URL` env var and update bundlerURL logic in Artifact components * fix: update minimum length requirement for auth fields from 10 to 1 character * 🐳 feat: Add Jemalloc and UV to Docker Builds (danny-avila#6836) * feat: Add `uv` for extended MCP support in Dockerfiles * feat: Install jemalloc and set environment variable to use it * 🤖 refactor: Improve Agents Memory Usage, Bump Keyv, Grok 3 (danny-avila#6850) * chore: remove unused redis file * chore: bump keyv dependencies, and update related imports * refactor: Implement IoRedis client for rate limiting across middleware, as node-redis via keyv not compatible * fix: Set max listeners to expected amount * WIP: memory improvements * refactor: Simplify getAbortData assignment in createAbortController * refactor: Update getAbortData to use WeakRef for content management * WIP: memory improvements in agent chat requests * refactor: Enhance memory management with finalization registry and cleanup functions * refactor: Simplify domainParser calls by removing unnecessary request parameter * refactor: Update parameter types for action tools and agent loading functions to use minimal configs * refactor: Simplify domainParser tests by removing unnecessary request parameter * refactor: Simplify domainParser call by removing unnecessary request parameter * refactor: Enhance client disposal by nullifying additional properties to improve memory management * refactor: Improve title generation by adding abort controller and timeout handling, consolidate request cleanup * refactor: Update checkIdleConnections to skip current user when checking for idle connections if passed * refactor: Update createMCPTool to derive userId from config and handle abort signals * refactor: Introduce createTokenCounter function and update tokenCounter usage; enhance disposeClient to reset Graph values * refactor: Update getMCPManager to accept userId parameter for improved idle connection handling * refactor: Extract logToolError function for improved error handling in AgentClient * refactor: Update disposeClient to clear handlerRegistry and graphRunnable references in client.run * refactor: Extract createHandleNewToken function to streamline token handling in initializeClient * chore: bump @librechat/agents * refactor: Improve timeout handling in addTitle function for better error management * refactor: Introduce createFetch instead of using class method * refactor: Enhance client disposal and request data handling in AskController and EditController * refactor: Update import statements for AnthropicClient and OpenAIClient to use specific paths * refactor: Use WeakRef for response handling in SplitStreamHandler to prevent memory leaks * refactor: Simplify client disposal and rename getReqData to processReqData in AskController and EditController * refactor: Improve logging structure and parameter handling in OpenAIClient * refactor: Remove unused GraphEvents and improve stream event handling in AnthropicClient and OpenAIClient * refactor: Simplify client initialization in AskController and EditController * refactor: Remove unused mock functions and implement in-memory store for KeyvMongo * chore: Update dependencies in package-lock.json to latest versions * refactor: Await token usage recording in OpenAIClient to ensure proper async handling * refactor: Remove handleAbort route from multiple endpoints and enhance client disposal logic * refactor: Enhance abort controller logic by managing abortKey more effectively * refactor: Add newConversation handling in useEventHandlers for improved conversation management * fix: dropparams * refactor: Use optional chaining for safer access to request properties in BaseClient * refactor: Move client disposal and request data processing logic to cleanup module for better organization * refactor: Remove aborted request check from addTitle function for cleaner logic * feat: Add Grok 3 model pricing and update tests for new models * chore: Remove trace warnings and inspect flags from backend start script used for debugging * refactor: Replace user identifier handling with userId for consistency across controllers, use UserId in clientRegistry * refactor: Enhance client disposal logic to prevent memory leaks by clearing additional references * chore: Update @librechat/agents to version 2.4.14 in package.json and package-lock.json * 💾 refactor: Enhance Memory In Image Encodings & Client Disposal (danny-avila#6852) * 💾 chore: Clear Additional Properties in `disposeClient` * refactor: stream handling and base64 conversion in encode.js to better free memory * 🔧 fix: Keyv and Proxy Issues, and More Memory Optimizations (danny-avila#6867) * chore: update @librechat/agents dependency to version 2.4.15 * refactor: Prevent memory leaks by nullifying boundModel.client in disposeClient function * fix: use of proxy, use undici * chore: update @librechat/agents dependency to version 2.4.16 * Revert "fix: use of proxy, use undici" This reverts commit 83153cd. * fix: ensure fetch is imported for HTTP requests * fix: replace direct OpenAI import with CustomOpenAIClient from @librechat/agents * fix: update keyv peer dependency to version 5.3.2 * fix: update keyv dependency to version 5.3.2 * refactor: replace KeyvMongo with custom implementation and update flow state manager usage * fix: update @librechat/agents dependency to version 2.4.17 * ci: update OpenAIClient tests to use CustomOpenAIClient from @librechat/agents * refactor: remove KeyvMongo mock and related dependencies * 🤖 feat: GPT-4.1 (danny-avila#6880) * fix: Agent Builder setting not applying in useSideNavLinks * fix: Remove unused type imports in useSideNavLinks * feat: gpt-4.1 * fix: Update getCacheMultiplier and getMultiplier tests to use dynamic token values * feat: Add gpt-4.1 to the list of vision models * chore: Bump version of librechat-data-provider to 0.7.792 * 🔁 refactor: Token Event Handler and Standardize `maxTokens` Key (danny-avila#6886) * refactor: agent token handling to use createHandleLLMNewToken for improved closure * refactor: update llmConfig to use maxTokens instead of max_tokens for consistency * 👋 feat: remove Edge TTS (danny-avila#6885) * feat: remove Edge TTS * remove the remaining edge code * chore: cleanup * chore: cleanup package-lock * ✨ style: Dynamic text sizing for greeting and name display (danny-avila#6833) * ✨ feat: Implement dynamic text sizing for greeting and name display * refactor: simplified text-size logic * ⌨️ a11y: enhance accessibility & visual consistency (danny-avila#6866) * a11y: TemporaryChat label * style: ChatForm badges update * 📜 refactor: Optimize Conversation History Nav with Cursor Pagination (danny-avila#5785) * ✨ feat: improve Nav/Conversations/Convo/NewChat component performance * ✨ feat: implement cursor-based pagination for conversations API * 🔧 refactor: remove createdAt from conversation selection in API and type definitions * 🔧 refactor: include createdAt in conversation selection and update related types * ✨ fix: search functionality and bugs with loadMoreConversations * feat: move ArchivedChats to cursor and DataTable standard * 🔧 refactor: add InfiniteQueryObserverResult type import in Nav component * feat: enhance conversation listing with pagination, sorting, and search capabilities * 🔧 refactor: remove unnecessary comment regarding lodash/debounce in ArchivedChatsTable * 🔧 refactor: remove unused translation keys for archived chats and search results * 🔧 fix: Archived Chats, Delete Convo, Duplicate Convo * 🔧 refactor: improve conversation components with layout adjustments and new translations * 🔧 refactor: simplify archive conversation mutation and improve unarchive handling; fix: update fork mutation * 🔧 refactor: decode search query parameter in conversation route; improve error handling in unarchive mutation; clean up DataTable component styles * 🔧 refactor: remove unused translation key for empty archived chats * 🚀 fix: `archivedConversation` query key not updated correctly while archiving * 🧠 feat: Bedrock Anthropic Reasoning & Update Endpoint Handling (danny-avila#6163) * feat: Add thinking and thinkingBudget parameters for Bedrock Anthropic models * chore: Update @librechat/agents to version 2.1.8 * refactor: change region order in params * refactor: Add maxTokens parameter to conversation preset schema * refactor: Update agent client to use bedrockInputSchema and improve error handling for model parameters * refactor: streamline/optimize llmConfig initialization and saving for bedrock * fix: ensure config titleModel is used for all endpoints * refactor: enhance OpenAIClient and agent initialization to support endpoint checks for OpenRouter * chore: bump @google/generative-ai * ✨ feat: improve Nav/Conversations/Convo/NewChat component performance * 🔧 refactor: remove unnecessary comment regarding lodash/debounce in ArchivedChatsTable * 🔧 refactor: update translation keys for clarity; simplify conversation query parameters and improve sorting functionality in SharedLinks component * 🔧 refactor: optimize conversation loading logic and improve search handling in Nav component * fix: package-lock * fix: package-lock 2 * fix: package lock 3 * refactor: remove unused utility files and exports to clean up the codebase * refactor: remove i18n and useAuthRedirect modules to streamline codebase * refactor: optimize Conversations component and remove unused ToggleContext * refactor(Convo): add RenameForm and ConvoLink components; enhance Conversations component with responsive design * fix: add missing @azure/storage-blob dependency in package.json * refactor(Search): add error handling with toast notification for search errors * refactor: make createdAt and updatedAt fields of tConvoUpdateSchema less restrictive if timestamps are missing * chore: update @azure/storage-blob dependency to version 12.27.0, ensure package-lock is correct * refactor(Search): improve conversation handling server side * fix: eslint warning and errors * refactor(Search): improved search loading state and overall UX * Refactors conversation cache management Centralizes conversation mutation logic into dedicated utility functions for adding, updating, and removing conversations from query caches. Improves reliability and maintainability by: - Consolidating duplicate cache manipulation code - Adding type safety for infinite query data structures - Implementing consistent cache update patterns across all conversation operations - Removing obsolete conversation helper functions in favor of standardized utilities * fix: conversation handling and SSE event processing - Optimizes conversation state management with useMemo and proper hook ordering - Improves SSE event handler documentation and error handling - Adds reset guard flag for conversation changes - Removes redundant navigation call - Cleans up cursor handling logic and document structure Improves code maintainability and prevents potential race conditions in conversation state updates * refactor: add type for SearchBar `onChange` * fix: type tags * style: rounded to xl all Header buttons * fix: activeConvo in Convo not working * style(Bookmarks): improved UI * a11y(AccountSettings): fixed hover style not visible when using light theme * style(SettingsTabs): improved tab switchers and dropdowns * feat: add translations keys for Speech * chore: fix package-lock * fix(mutations): legacy import after rebase * feat: refactor conversation navigation for accessibility * fix(search): convo and message create/update date not returned * fix(search): show correct iconURL and endpoint for searched messages * fix: small UI improvements * chore: console.log cleanup * chore: fix tests * fix(ChatForm): improve conversation ID handling and clean up useMemo dependencies * chore: improve typing * chore: improve typing * fix(useSSE): clear conversation ID on submission to prevent draft restoration * refactor(OpenAIClient): clean up abort handler * refactor(abortMiddleware): change handleAbort to use function expression * feat: add PENDING_CONVO constant and update conversation ID checks * fix: final event handling on abort * fix: improve title sync and query cache sync on final event * fix: prevent overwriting cached conversation data if it already exists --------- Co-authored-by: Danny Avila <[email protected]> * 📝 fix: Mistral OCR Image Support and Azure Agent Titles (danny-avila#6901) * fix: azure title model * refactor: typing for uploadMistralOCR * fix: update conversation ID handling in useSSE for better state management, only use PENDING_CONVO for new conversations * fix: streamline conversation ID handling in useSSE for simplicity, only needs state update to prevent draft from applying * fix: update performOCR and tests to support document and image URLs with appropriate types * 📢 fix: Invalid `engineTTS` and Conversation State on Navigation (danny-avila#6904) * fix: handle invalid engineTTS values and prevent VoiceDropdown render errors * refactor: add verbose developer logging for debugging conversation state issues * refactor: remove unnecessary effect for conversationId changes * chore: imports * fix: include model and entity IDs in conversation query selection * feat: add fetchFreshData function to retrieve conversation data on navigation * fix: remove unnecessary comment in fetchFreshData function * chore: reorder imports in useNavigateToConvo for consistency --------- Co-authored-by: Danny Avila <[email protected]> * 🛠️ fix: Improve Accessibility and Display of Conversation Menu (danny-avila#6913) * 📦 chore: update @ariakit/react-core to version 0.4.17 in package.json and package-lock.json * refactor: add additional ariakit menu props and unmount menu if state changes * fix: accessibility issues and incompatibility issues due to non-portaled menu * fix: improve visibility and accessibility of conversation options, making sure to expand dynamically when becoming active * fix: adjust max width for conversation options popover to improve visibility * Revert changes to files that shouldn't be modified from upstream Restored upstream versions of these files: - api/server/routes/actions.js - api/server/services/ActionService.js - api/server/services/MCP.js - client/src/components/Chat/Input/ChatForm.tsx - client/src/components/ui/CheckboxButton.tsx - client/src/components/ui/DropdownPopup.tsx - client/src/data-provider/mutations.ts - client/src/utils/convos.ts - client/src/utils/index.ts - packages/data-provider/package.json * Revert changes to api/config/index.js and api/package.json Restored upstream versions of these files to avoid conflicts in future merges. * chore: updated dependencies --------- Co-authored-by: Danny Avila <[email protected]> Co-authored-by: Marco Beretta <[email protected]>
1 parent 3415afe commit 5813fdf

File tree

172 files changed

+5848
-3581
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

172 files changed

+5848
-3581
lines changed

Dockerfile

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,15 @@
33
# Base node image
44
FROM node:20-alpine AS node
55

6-
RUN apk --no-cache add curl
6+
# Install jemalloc
7+
RUN apk add --no-cache jemalloc
8+
9+
# Set environment variable to use jemalloc
10+
ENV LD_PRELOAD=/usr/lib/libjemalloc.so.2
11+
12+
# Add `uv` for extended MCP support
13+
COPY --from=ghcr.io/astral-sh/uv:0.6.13 /uv /uvx /bin/
14+
RUN uv --version
715

816
RUN mkdir -p /app && chown node:node /app
917
WORKDIR /app
@@ -38,4 +46,4 @@ CMD ["npm", "run", "backend"]
3846
# WORKDIR /usr/share/nginx/html
3947
# COPY --from=node /app/client/dist /usr/share/nginx/html
4048
# COPY client/nginx.conf /etc/nginx/conf.d/default.conf
41-
# ENTRYPOINT ["nginx", "-g", "daemon off;"]
49+
# ENTRYPOINT ["nginx", "-g", "daemon off;"]

Dockerfile.multi

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33

44
# Base for all builds
55
FROM node:20-alpine AS base-min
6+
# Install jemalloc
7+
RUN apk add --no-cache jemalloc
8+
# Set environment variable to use jemalloc
9+
ENV LD_PRELOAD=/usr/lib/libjemalloc.so.2
610
WORKDIR /app
711
RUN apk --no-cache add curl
812
RUN npm config set fetch-retry-maxtimeout 600000 && \
@@ -50,6 +54,9 @@ RUN npm run build
5054

5155
# API setup (including client dist)
5256
FROM base-min AS api-build
57+
# Add `uv` for extended MCP support
58+
COPY --from=ghcr.io/astral-sh/uv:0.6.13 /uv /uvx /bin/
59+
RUN uv --version
5360
WORKDIR /app
5461
# Install only production deps
5562
RUN npm ci --omit=dev

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ To merge with upstream ensure that the `main-upstream` branch is up to date with
3131

3232
Then, create a new tracking branch from it, `tracking/YYYY/MM/DD-XX` and begin a merge from `dev/main` or `main` into the new tracking branch.
3333

34-
Most of the files should be taken from upstream. verbatim. The following files should be taken from out fork:
34+
Most of the files should be taken from upstream. verbatim. That includes the package and package lock files, until later in this process.
35+
36+
The following files should be taken from out fork:
3537

3638
- `.github/workflows/jm*.yml` - These are the CI/CD workflows for this fork.
3739
- `.devcontainer/*` - This is the devcontainer for this fork.
@@ -40,12 +42,20 @@ Most of the files should be taken from upstream. verbatim. The following files s
4042
- `api/app/clients/tools/structured/WebNavigator.js`
4143
- `api/app/clients/tools/structured/TimeAPI.js`
4244
- `api/app/clients/tools/structured/QuickChart.js`
45+
- `client/public/assets/*` related to the tools listed above.
46+
- All `.sh` files.
4347

4448
These files need to be merged:
4549

4650
- `api/app/clients/tools/manifest.json`
4751
- `api/app/clients/tools/index.js`
4852
- `api/app/clients/tools/util/handleTools.js`
53+
- `.gitignore` - This is the gitignore for this fork.
54+
55+
After you've merged but before you commit, run `./clean.sh` _from inside the devcontainer`
56+
57+
This will update the package and package lock files, so long as you properly took the files from upstream.
58+
4959

5060
After the merge is complete, run `./build-local.sh` to ensure things build on your machine. After that, push the tracking branch
5161
and open a PR from the tracking branch into `main` or `dev/main` as appropriate.

api/app/clients/AnthropicClient.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const {
99
getResponseSender,
1010
validateVisionModel,
1111
} = require('librechat-data-provider');
12-
const { SplitStreamHandler: _Handler, GraphEvents } = require('@librechat/agents');
12+
const { SplitStreamHandler: _Handler } = require('@librechat/agents');
1313
const {
1414
truncateText,
1515
formatMessage,
@@ -26,10 +26,11 @@ const {
2626
const { getModelMaxTokens, getModelMaxOutputTokens, matchModelName } = require('~/utils');
2727
const { spendTokens, spendStructuredTokens } = require('~/models/spendTokens');
2828
const { encodeAndFormat } = require('~/server/services/Files/images/encode');
29+
const { createFetch, createStreamEventHandlers } = require('./generators');
2930
const Tokenizer = require('~/server/services/Tokenizer');
30-
const { logger, sendEvent } = require('~/config');
3131
const { sleep } = require('~/server/utils');
3232
const BaseClient = require('./BaseClient');
33+
const { logger } = require('~/config');
3334

3435
const HUMAN_PROMPT = '\n\nHuman:';
3536
const AI_PROMPT = '\n\nAssistant:';
@@ -184,7 +185,10 @@ class AnthropicClient extends BaseClient {
184185
getClient(requestOptions) {
185186
/** @type {Anthropic.ClientOptions} */
186187
const options = {
187-
fetch: this.fetch,
188+
fetch: createFetch({
189+
directEndpoint: this.options.directEndpoint,
190+
reverseProxyUrl: this.options.reverseProxyUrl,
191+
}),
188192
apiKey: this.apiKey,
189193
};
190194

@@ -795,14 +799,11 @@ class AnthropicClient extends BaseClient {
795799
}
796800

797801
logger.debug('[AnthropicClient]', { ...requestOptions });
802+
const handlers = createStreamEventHandlers(this.options.res);
798803
this.streamHandler = new SplitStreamHandler({
799804
accumulate: true,
800805
runId: this.responseMessageId,
801-
handlers: {
802-
[GraphEvents.ON_RUN_STEP]: (event) => sendEvent(this.options.res, event),
803-
[GraphEvents.ON_MESSAGE_DELTA]: (event) => sendEvent(this.options.res, event),
804-
[GraphEvents.ON_REASONING_DELTA]: (event) => sendEvent(this.options.res, event),
805-
},
806+
handlers,
806807
});
807808

808809
let intermediateReply = this.streamHandler.tokens;

api/app/clients/BaseClient.js

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,10 @@ class BaseClient {
2828
month: 'long',
2929
day: 'numeric',
3030
});
31-
this.fetch = this.fetch.bind(this);
3231
/** @type {boolean} */
3332
this.skipSaveConvo = false;
3433
/** @type {boolean} */
3534
this.skipSaveUserMessage = false;
36-
/** @type {ClientDatabaseSavePromise} */
37-
this.userMessagePromise;
38-
/** @type {ClientDatabaseSavePromise} */
39-
this.responsePromise;
4035
/** @type {string} */
4136
this.user;
4237
/** @type {string} */
@@ -564,6 +559,8 @@ class BaseClient {
564559
}
565560

566561
async sendMessage(message, opts = {}) {
562+
/** @type {Promise<TMessage>} */
563+
let userMessagePromise;
567564
const { user, head, isEdited, conversationId, responseMessageId, saveOptions, userMessage } =
568565
await this.handleStartMethods(message, opts);
569566

@@ -625,11 +622,11 @@ class BaseClient {
625622
}
626623

627624
if (!isEdited && !this.skipSaveUserMessage) {
628-
this.userMessagePromise = this.saveMessageToDatabase(userMessage, saveOptions, user);
625+
userMessagePromise = this.saveMessageToDatabase(userMessage, saveOptions, user);
629626
this.savedMessageIds.add(userMessage.messageId);
630627
if (typeof opts?.getReqData === 'function') {
631628
opts.getReqData({
632-
userMessagePromise: this.userMessagePromise,
629+
userMessagePromise,
633630
});
634631
}
635632
}
@@ -655,7 +652,9 @@ class BaseClient {
655652

656653
/** @type {string|string[]|undefined} */
657654
const completion = await this.sendCompletion(payload, opts);
658-
this.abortController.requestCompleted = true;
655+
if (this.abortController) {
656+
this.abortController.requestCompleted = true;
657+
}
659658

660659
/** @type {TMessage} */
661660
const responseMessage = {
@@ -703,7 +702,13 @@ class BaseClient {
703702
if (usage != null && Number(usage[this.outputTokensKey]) > 0) {
704703
responseMessage.tokenCount = usage[this.outputTokensKey];
705704
completionTokens = responseMessage.tokenCount;
706-
await this.updateUserMessageTokenCount({ usage, tokenCountMap, userMessage, opts });
705+
await this.updateUserMessageTokenCount({
706+
usage,
707+
tokenCountMap,
708+
userMessage,
709+
userMessagePromise,
710+
opts,
711+
});
707712
} else {
708713
responseMessage.tokenCount = this.getTokenCountForResponse(responseMessage);
709714
completionTokens = responseMessage.tokenCount;
@@ -712,8 +717,8 @@ class BaseClient {
712717
await this.recordTokenUsage({ promptTokens, completionTokens, usage });
713718
}
714719

715-
if (this.userMessagePromise) {
716-
await this.userMessagePromise;
720+
if (userMessagePromise) {
721+
await userMessagePromise;
717722
}
718723

719724
if (this.artifactPromises) {
@@ -728,7 +733,11 @@ class BaseClient {
728733
}
729734
}
730735

731-
this.responsePromise = this.saveMessageToDatabase(responseMessage, saveOptions, user);
736+
responseMessage.databasePromise = this.saveMessageToDatabase(
737+
responseMessage,
738+
saveOptions,
739+
user,
740+
);
732741
this.savedMessageIds.add(responseMessage.messageId);
733742
delete responseMessage.tokenCount;
734743
return responseMessage;
@@ -749,9 +758,16 @@ class BaseClient {
749758
* @param {StreamUsage} params.usage
750759
* @param {Record<string, number>} params.tokenCountMap
751760
* @param {TMessage} params.userMessage
761+
* @param {Promise<TMessage>} params.userMessagePromise
752762
* @param {object} params.opts
753763
*/
754-
async updateUserMessageTokenCount({ usage, tokenCountMap, userMessage, opts }) {
764+
async updateUserMessageTokenCount({
765+
usage,
766+
tokenCountMap,
767+
userMessage,
768+
userMessagePromise,
769+
opts,
770+
}) {
755771
/** @type {boolean} */
756772
const shouldUpdateCount =
757773
this.calculateCurrentTokenCount != null &&
@@ -787,7 +803,7 @@ class BaseClient {
787803
Note: we update the user message to be sure it gets the calculated token count;
788804
though `AskController` saves the user message, EditController does not
789805
*/
790-
await this.userMessagePromise;
806+
await userMessagePromise;
791807
await this.updateMessageInDatabase({
792808
messageId: userMessage.messageId,
793809
tokenCount: userMessageTokenCount,
@@ -853,7 +869,7 @@ class BaseClient {
853869
}
854870

855871
const savedMessage = await saveMessage(
856-
this.options.req,
872+
this.options?.req,
857873
{
858874
...message,
859875
endpoint: this.options.endpoint,
@@ -877,7 +893,7 @@ class BaseClient {
877893
const existingConvo =
878894
this.fetchedConvo === true
879895
? null
880-
: await getConvo(this.options.req?.user?.id, message.conversationId);
896+
: await getConvo(this.options?.req?.user?.id, message.conversationId);
881897

882898
const unsetFields = {};
883899
const exceptions = new Set(['spec', 'iconURL']);
@@ -897,7 +913,7 @@ class BaseClient {
897913
}
898914
}
899915

900-
const conversation = await saveConvo(this.options.req, fieldsToKeep, {
916+
const conversation = await saveConvo(this.options?.req, fieldsToKeep, {
901917
context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo',
902918
unsetFields,
903919
});

api/app/clients/ChatGPTClient.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const Keyv = require('keyv');
1+
const { Keyv } = require('keyv');
22
const crypto = require('crypto');
33
const { CohereClient } = require('cohere-ai');
44
const { fetchEventSource } = require('@waylaidwanderer/fetch-event-source');
@@ -339,7 +339,7 @@ class ChatGPTClient extends BaseClient {
339339
opts.body = JSON.stringify(modelOptions);
340340

341341
if (modelOptions.stream) {
342-
// eslint-disable-next-line no-async-promise-executor
342+
343343
return new Promise(async (resolve, reject) => {
344344
try {
345345
let done = false;

0 commit comments

Comments
 (0)