Skip to content

Commit ecd63eb

Browse files
✨ feat: Assistants API, General File Support, Side Panel, File Explorer (danny-avila#1696)
* feat: assistant name/icon in Landing & Header * feat: assistname in textarea placeholder, and use `Assistant` as default name * feat: display non-image files in user messages * fix: only render files if files.length is > 0 * refactor(config -> file-config): move file related configuration values to separate module, add excel types * chore: spreadsheet file rendering * fix(Landing): dark mode style for Assistant Name * refactor: move progress incrementing to own hook, start smaller, cap near limit \(1\) * refactor(useContentHandler): add empty Text part if last part was completed tool or image * chore: add accordion trigger border styling for dark mode * feat: Assistant Builder model selection * chore: use Spinner when Assistant is mutating * fix(get/assistants): return correct response object `AssistantListResponse` * refactor(Spinner): pass size as prop * refactor: make assistant crud mutations optimistic, add types for options * chore: remove assistants route and view * chore: move assistant builder components to separate directory * feat(ContextButton): delete Assistant via context button/dialog, add localization * refactor: conditionally show use and context menu buttons, add localization for create assistant * feat: save side panel states to localStorage * style(SidePanel): improve avatar menu and assistant select styling for dark mode * refactor: make NavToggle reusable for either side (left or right), add SidePanel Toggle with ability to close it completely * fix: resize handle and navToggle behavior * fix(/avatar/:assistant_id): await `deleteFile` and assign unique name to uploaded image * WIP: file UI components from PR danny-avila#576 * refactor(OpenAIMinimalIcon): pass className * feat: formatDate helper fn * feat: DataTableColumnHeader * feat: add row selection, formatted row values, number of rows selected * WIP: add files to Side panel temporarily * feat: `LB_QueueAsyncCall`: Leaky Bucket queue for external APIs, use in `processDeleteRequest` * fix(TFile): correct `source` type with `FileSources` * fix(useFileHandling): use `continue` instead of return when iterating multiple files, add file type to extendedFile * chore: add generic setter type * refactor(processDeleteRequest): settle promises to prevent rejections from processing deletions, log errors * feat: `useFileDeletion` to reuse file deletion logic * refactor(useFileDeletion): make `setFiles` an optional param and use object as param * feat: useDeleteFilesFromTable * feat: use real `files` data and add deletion action to data table * fix(Table): make headers sticky * feat: add dynamic filtering for columns; only show to user Host or OpenAI storage type * style(DropdownMenu): replace `slate` with `gray` * style(DataTable): apply dark mode themes and other misc styling * style(Columns): add color to OpenAI Storage option * refactor(FileContainer): make file preview reusable * refactor(Images): make image preview reusable * refactor(FilePreview): make file prop optional for FileIcon and FilePreview, fix relative style * feat(Columns): add file/image previews, set a minimum size to show for file size in bytes * WIP: File Panel with real files and formatted * feat: open files dialog from panel * style: file data table mobile and general column styling fixes * refactor(api/files): return files sorted by the most recently updated * refactor: provide fileMap through context to prevent re-selecting files to map in different areas; remove unused imports commented out in PanelColumns * refactor(ExtendFile): make File type optional, add `attached` to prevent attached files from being deleted on remove, make Message.files a partial TFile type * feat: attach files through file panel * refactor(useFileHandling): move files to the start of cache list when uploaded * refactor(useDeleteFilesMutation): delete files from cache when successfully deleted from server * fix(FileRow): handle possible edge case of duplication due to attaching recently uploaded file * style(SidePanel): make resize grip border transparent, remove unnecessary styling on close sidepanel button * feat: action utilities and tests * refactor(actions): add `ValidationResult` type and change wording for no server URL found * refactor(actions): check for empty server URL * fix(data-provider): revert tsconfig to fix type issue resolution * feat(client): first pass of actions input for assistants * refactor(FunctionSignature): change method to output object instead of string * refactor(models/Assistant): add actions field to schema, use searchParams object for methods, and add `getAssistant` * feat: post actions input first pass - create new Action document - add actions to Assistant DB document - create /action/:assistant_id POST route - pass more props down from PanelSwitcher, derive assistant_id from switcher - move privacy policy to ActionInput - reset data on input change/validation - add `useUpdateAction` - conform FunctionSignature type to FunctionTool - add action, assistant doc, update hook related types * refactor: optimize assistant/actions relationship - past domain in metadata as hostname and not a URL - include domain in tool name - add `getActions` for actions retrieval by user - add `getAssistants` for assistant docs retrieval by user - add `assistant_id` to Action schema - move actions to own module as a subroute to `api/assistants` - add `useGetActionsQuery` and `useGetAssistantDocsQuery` hooks - fix Action type def * feat: show assistant actions in assistant builder * feat: switch to actions on action click, editing action styling * fix: add Assistant state for builder panel to allow immediate selection of newly created assistants as well as retaining the current assistant when switching to a different panel within the builder * refactor(SidePanel/NavToggle): offset less from right when SidePanel is completely collapsed * chore: rename `processActions` -> `processRequiredActions` * chore: rename Assistant API Action to RequiredAction * refactor(actions): avoid nesting actual API params under generic `requestBody` to optimize LLM token usage * fix(handleTools): avoid calling `validTool` if not defined, add optional param to skip the loading of specs, which throws an error in the context of assistants * WIP: working first pass of toolCalls generated from openapi specs * WIP: first pass ToolCall styling * feat: programmatic iv encryption/decryption helpers * fix: correct ActionAuth types/enums, and define type for AuthForm * feat: encryption/decryption helpers for Action AuthMetadata * refactor(getActions): remove sensitive fields from query response * refactor(POST/actions): encrypt and remove sensitive fields from mutation response * fix(ActionService): change ESM import to CJS * feat: frontend auth handling for actions + optimistic update on action update/creation * refactor(actions): use the correct variables and types for setAuth method * refactor: POST /:assistant_id action can now handle updating an existing action, add `saved_auth_fields` to determine when user explicitly saves new auth creds. only send auth metadata if user explicitly saved fields * refactor(createActionTool): catch errors and send back meaningful error message, add flag to `getActions` to determine whether to retrieve sensitive values or not * refactor(ToolService): add `action` property to ToolCall PartMetadata to determine if the tool call was an action, fix parsing function name issue with actionDelimiter * fix(ActionRequest): use URL class to correctly join endpoint parts for `execute` call * feat: delete assistant actions * refactor: conditionally show Available actions * refactor: show `retrieval` and `code_interpreter` as Capabilities, swap `Switch` for `Checkbox` * chore: remove shadow-stroke from messages * WIP: first pass of Assistants Knowledge attachments * refactor: remove AssistantsProvider in favor of FormProvider, fix selectedAssistant re-render bug, map Assistant file_ids to files via fileMap, initialize Knowledge component with mapped files if any exist * fix: prevent deleting files on assistant file upload * chore: remove console.log * refactor(useUploadFileMutation): update files and assistants cache on upload * chore: disable oauth option as not supported yet * feat: cancel assistant runs * refactor: initialize OpenAI client with helper function, resolve all related circular dependencies * fix(DALL-E): initialization * fix(process): openai client initialization * fix: select an existing Assistant when the active one is deleted * chore: allow attaching files for assistant endpoint, send back relevant OpenAI error message when uploading, deconstruct openAI initialization correctly, add `message_file` to formData when a file is attached to the message but not the assistant * fix: add assistant_id on newConvo * fix(initializeClient): import fix * chore: swap setAssistant for setOption in useEffect * fix(DALL-E): add processFileURL to loadTools call * chore: add customConfig to debug logs * feat: delete threads on convo delete * chore: replace Assistants icon * chore: remove console.dir() in `abortRun` * feat(AssistantService): accumulate text values from run in openai.responseText * feat: titling for assistants endpoint * chore: move panel file components to appropriate directory, add file checks for attaching files, change icon for Attach Files * refactor: add localizations to tools, plugins, add condition for adding/remove user plugins so tool selections don't affect this value * chore: disable `import from url` action for now * chore: remove textMimeTypes from default fileConfig for now * fix: catch tool errors and send as outputs with error messages * fix: React warning about button as descendant of button * style: retrieval and cancelled icon * WIP: pass isSubmitting to Parts, use InProgressCall to display cancelled tool calls correctly, show domain/function name * fix(meilisearch): fix `postSaveHook` issue where indexing expects a mongo document, and join all text content parts for meili indexing * ci: fix dall-e tests * ci: fix client tests * fix: button types in actions panel * fix: plugin auth form persisting across tool selections * fix(ci): update AppService spec with `loadAndFormatTools` * fix(clearConvos): add id check earlier on * refactor(AssistantAvatar): set previewURL dynamically when emtadata.avatar changes * feat(assistants): addTitle cache setting * fix(useSSE): resolve rebase conflicts * fix: delete mutation * style(SidePanel): make grip visible on active and hover, invisible otherwise * ci: add data-provider tests to workflow, also update eslint/tsconfig to recognize specs, and add `text/csv` to fileConfig * fix: handle edge case where auth object is undefined, and log errors * refactor(actions): resolve schemas, add tests for resolving refs, import specs from separate file for tests * chore: remove comment * fix(ActionsInput): re-render bug when initializing states with action fields * fix(patch/assistant): filter undefined tools * chore: add logging for errors in assistants routes * fix(updateAssistant): map actions to functions to avoid overwriting * fix(actions): properly handle GET paths * fix(convos): unhandled delete thread exception * refactor(AssistantService): pass both thread_id and conversationId when sending intermediate assistant messages, remove `mapMessagesToSteps` from AssistantService * refactor(useSSE): replace all messages with runMessages and pass latestMessageId to abortRun; fix(checkMessageGaps): include tool calls when syncing messages * refactor(assistants/chat): invoke `createOnTextProgress` after thread creation * chore: add typing * style: sidepanel styling * style: action tool call domain styling * feat(assistants): default models, limit retrieval to certain models, add env variables to to env.example * feat: assistants api key in EndpointService * refactor: set assistant model to conversation on assistant switch * refactor: set assistant model to conversation on assistant select from panel * fix(retrieveAndProcessFile): catch attempt to download file with `assistant` purpose which is not allowed; add logging * feat: retrieval styling, handling, and logging * chore: rename ASSISTANTS_REVERSE_PROXY to ASSISTANTS_BASE_URL * feat: FileContext for file metadata * feat: context file mgmt and filtering * style(Select): hover/rounded changes * refactor: explicit conversation switch, endpoint dependent, through `useSelectAssistant`, which does not create new chat if current endpoint is assistant endpoint * fix(AssistantAvatar): make empty previewURL if no avatar present * refactor: side panel mobile styling * style: merge tool and action section, optimize mobile styling for action/tool buttons * fix: localStorage issues * fix(useSelectAssistant): invoke react query hook directly in select hook as Map was not being updated in time * style: light mode fixes * fix: prevent sidepanel nav styling from shifting layout up * refactor: change default layout (collapsed by default) * style: mobile optimization of DataTable * style: datatable * feat: client-side hide right-side panel * chore(useNewConvo): add partial typing for preset * fix(useSelectAssistant): pass correct model name by using template as preset * WIP: assistant presets * refactor(ToolService): add native solution for `TavilySearchResults` and log tool output errors * refactor: organize imports and use native TavilySearchResults * fix(TavilySearchResults): stringify result * fix(ToolCall): show tool call outputs when not an action * chore: rename Prompt Prefix to custom instructions (in user facing text only) * refactor(EditPresetDialog): Optimize setting title by debouncing, reset preset on dialog close to avoid state mixture * feat: add `presetOverride` to overwrite active conversation settings when saving a Preset (relevant for client side updates only) * feat: Assistant preset settings (client-side) * fix(Switcher): only set assistant_id and model if current endpoint is Assistants * feat: use `useDebouncedInput` for updating conversation settings, starting with EditPresetDialog title setting and Assistant instructions setting * feat(Assistants): add instructions field to settings * feat(chat/assistants): pass conversation settings to run body * wip: begin localization and only allow actions if the assistant is created * refactor(AssistantsPanel): knowledge localization, allow tools on creation * feat: experimental: allow 'priming' values before assistant is created, that would normally require an assistant_id to be defined * chore: trim console logs and make more meaningful * chore: toast messages * fix(ci): date test * feat: create file when uploading Assistant Avatar * feat: file upload rate limiting from custom config with dynamic file route initialization * refactor: use file upload limiters on post routes only * refactor(fileConfig): add endpoints field for endpoint specific fileconfigs, add mergeConfig function, add tests * refactor: fileConfig route, dynamic multer instances used on all '/' and '/images' POST routes, data service and query hook * feat: supportedMimeTypesSchema, test for array of regex * feat: configurable file config limits * chore: clarify assistants file knowledge prereq. * chore(useTextarea): default to localized 'Assistant' if assistant name is empty * feat: configurable file limits and toggle file upload per endpoint * fix(useUploadFileMutation): prevent updating assistant.files cache if file upload is a message_file attachment * fix(AssistantSelect): set last selected assistant only when timeout successfully runs * refactor(queries): disable assistant queries if assistants endpoint is not enabled * chore(Switcher): add localization * chore: pluralize `assistant` for `EModelEndpoint key and value * feat: show/hide assistant UI components based on endpoint availability; librechat.yaml config for disabling builder section and setting polling/timeout intervals * fix(compactEndpointSchemas): use EModelEndpoint for schema access * feat(runAssistant): use configured values from `librechat.yaml` for `pollIntervalMs` and `timeout` * fix: naming issue * wip: revert landing * 🎉 happy birthday LibreChat (danny-avila#1768) * happy birthday LibreChat * Refactor endpoint condition in Landing component * Update birthday message in Eng.tsx * fix(/config): avoid nesting ternaries * refactor(/config): check birthday --------- Co-authored-by: Danny Avila <[email protected]> * fix: landing * fix: landing * fix(useMessageHelpers): hardcoded check to use EModelEndpoint instead * fix(ci): convo test revert to main * fix(assistants/chat): fix issue where assistant_id was being saved as model for convo * chore: added logging, promises racing to prevent longer timeouts, explicit setting of maxRetries and timeouts, robust catching of invalid abortRun params * refactor: use recoil state for `showStopButton` and only show for assistants endpoint after syncing conversation data * refactor: optimize abortRun strategy using localStorage, refactor `abortConversation` to use async/await and await the result, refactor how the abortKey cache is set for runs * fix(checkMessageGaps): assign `assistant_id` to synced messages if defined; prevents UI from showing blank assistant for cancelled messages * refactor: re-order sequence of chat route, only allow aborting messages after run is created, cancel abortRun if there was a cancelling error (likely due already cancelled in chat route), and add extra logging * chore(typedefs): add httpAgent type to OpenAIClient * refactor: use custom implementation of retrieving run with axios to allow for timing out run query * fix(waitForRun): handle timed out run retrieval query * refactor: update preset conditions: - presets will retain settings when a different endpoint is selected; for existing convos, either when modular or is assistant switch - no longer use `navigateToConvo` on preset select * fix: temporary calculator hack as expects string input when invoked * fix: cancel abortRun only when cancelling error is a result of the run already being cancelled * chore: remove use of `fileMaxSizeMB` and total counterpart (redundant) * docs: custom config documentation update * docs: assistants api setup and dotenv, new custom config fields * refactor(Switcher): make Assistant switcher sticky in SidePanel * chore(useSSE): remove console log of data and message index * refactor(AssistantPanel): button styling and add secondary select button to bottom of panel * refactor(OpenAIClient): allow passing conversationId to RunManager through titleConvo and initializeLLM to properly record title context tokens used in cases where conversationId was not defined by the client * feat(assistants): token tracking for assistant runs * chore(spendTokens): improve logging * feat: support/exclude specific assistant Ids * chore: add update `librechat.example.yaml`, optimize `AppService` handling, new tests for `AppService`, optimize missing/outdate config logging * chore: mount docker logs to root of project * chore: condense axios errors * chore: bump vite * chore: vite hot reload fix using latest version * chore(getOpenAIModels): sort instruct models to the end of models list * fix(assistants): user provided key * fix(assistants): user provided key, invalidate more queries on revoke --------- Co-authored-by: Marco Beretta <[email protected]>
1 parent cd27864 commit ecd63eb

File tree

316 files changed

+21952
-6394
lines changed

Some content is hidden

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

316 files changed

+21952
-6394
lines changed

.env.example

+8
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,14 @@ DEBUG_OPENAI=false
119119

120120
# OPENAI_ORGANIZATION=
121121

122+
#====================#
123+
# Assistants API #
124+
#====================#
125+
126+
# ASSISTANTS_API_KEY=
127+
# ASSISTANTS_BASE_URL=
128+
# ASSISTANTS_MODELS=gpt-3.5-turbo-0125,gpt-3.5-turbo-16k-0613,gpt-3.5-turbo-16k,gpt-3.5-turbo,gpt-4,gpt-4-0314,gpt-4-32k-0314,gpt-4-0613,gpt-3.5-turbo-0613,gpt-3.5-turbo-1106,gpt-4-0125-preview,gpt-4-turbo-preview,gpt-4-1106-preview
129+
122130
#============#
123131
# OpenRouter #
124132
#============#

.eslintrc.js

+6
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ module.exports = {
131131
},
132132
],
133133
},
134+
{
135+
files: ['./packages/data-provider/specs/**/*.ts'],
136+
parserOptions: {
137+
project: './packages/data-provider/tsconfig.spec.json',
138+
},
139+
},
134140
],
135141
settings: {
136142
react: {

.github/workflows/backend-review.yml

+3
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ jobs:
3939
- name: Run unit tests
4040
run: cd api && npm run test:ci
4141

42+
- name: Run librechat-data-provider unit tests
43+
run: cd packages/data-provider && npm run test:ci
44+
4245
- name: Run linters
4346
uses: wearerequired/lint-action@v2
4447
with:

.gitignore

+4-1
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,7 @@ auth.json
8888
/packages/ux-shared/
8989
/images
9090

91-
!client/src/components/Nav/SettingsTabs/Data/
91+
!client/src/components/Nav/SettingsTabs/Data/
92+
93+
# User uploads
94+
uploads/

api/app/chatgpt-browser.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
require('dotenv').config();
22
const { KeyvFile } = require('keyv-file');
3+
const { Constants } = require('librechat-data-provider');
34
const { getUserKey, checkUserKeyExpiry } = require('../server/services/UserService');
45

56
const browserClient = async ({
@@ -48,7 +49,7 @@ const browserClient = async ({
4849
options = { ...options, parentMessageId, conversationId };
4950
}
5051

51-
if (parentMessageId === '00000000-0000-0000-0000-000000000000') {
52+
if (parentMessageId === Constants.NO_PARENT) {
5253
delete options.conversationId;
5354
}
5455

api/app/clients/BaseClient.js

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const crypto = require('crypto');
2-
const { supportsBalanceCheck } = require('librechat-data-provider');
2+
const { supportsBalanceCheck, Constants } = require('librechat-data-provider');
33
const { getConvo, getMessages, saveMessage, updateMessage, saveConvo } = require('~/models');
44
const { addSpaceIfNeeded, isEnabled } = require('~/server/utils');
55
const checkBalance = require('~/models/checkBalance');
@@ -77,7 +77,7 @@ class BaseClient {
7777
const saveOptions = this.getSaveOptions();
7878
this.abortController = opts.abortController ?? new AbortController();
7979
const conversationId = opts.conversationId ?? crypto.randomUUID();
80-
const parentMessageId = opts.parentMessageId ?? '00000000-0000-0000-0000-000000000000';
80+
const parentMessageId = opts.parentMessageId ?? Constants.NO_PARENT;
8181
const userMessageId = opts.overrideParentMessageId ?? crypto.randomUUID();
8282
let responseMessageId = opts.responseMessageId ?? crypto.randomUUID();
8383
let head = isEdited ? responseMessageId : parentMessageId;
@@ -552,7 +552,7 @@ class BaseClient {
552552
*
553553
* Each message object should have an 'id' or 'messageId' property and may have a 'parentMessageId' property.
554554
* The 'parentMessageId' is the ID of the message that the current message is a reply to.
555-
* If 'parentMessageId' is not present, null, or is '00000000-0000-0000-0000-000000000000',
555+
* If 'parentMessageId' is not present, null, or is Constants.NO_PARENT,
556556
* the message is considered a root message.
557557
*
558558
* @param {Object} options - The options for the function.
@@ -607,9 +607,7 @@ class BaseClient {
607607
}
608608

609609
currentMessageId =
610-
message.parentMessageId === '00000000-0000-0000-0000-000000000000'
611-
? null
612-
: message.parentMessageId;
610+
message.parentMessageId === Constants.NO_PARENT ? null : message.parentMessageId;
613611
}
614612

615613
orderedMessages.reverse();

api/app/clients/GoogleClient.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ const { GoogleVertexAI } = require('langchain/llms/googlevertexai');
44
const { ChatGoogleGenerativeAI } = require('@langchain/google-genai');
55
const { ChatGoogleVertexAI } = require('langchain/chat_models/googlevertexai');
66
const { AIMessage, HumanMessage, SystemMessage } = require('langchain/schema');
7-
const { encodeAndFormat, validateVisionModel } = require('~/server/services/Files/images');
7+
const { encodeAndFormat } = require('~/server/services/Files/images');
88
const { encoding_for_model: encodingForModel, get_encoding: getEncoding } = require('tiktoken');
99
const {
10+
validateVisionModel,
1011
getResponseSender,
11-
EModelEndpoint,
1212
endpointSettings,
13+
EModelEndpoint,
1314
AuthKeys,
1415
} = require('librechat-data-provider');
1516
const { getModelMaxTokens } = require('~/utils');

api/app/clients/OpenAIClient.js

+19-7
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
const OpenAI = require('openai');
22
const { HttpsProxyAgent } = require('https-proxy-agent');
3-
const { getResponseSender, ImageDetailCost, ImageDetail } = require('librechat-data-provider');
3+
const {
4+
getResponseSender,
5+
validateVisionModel,
6+
ImageDetailCost,
7+
ImageDetail,
8+
} = require('librechat-data-provider');
49
const { encoding_for_model: encodingForModel, get_encoding: getEncoding } = require('tiktoken');
510
const {
6-
getModelMaxTokens,
7-
genAzureChatCompletion,
811
extractBaseURL,
912
constructAzureURL,
13+
getModelMaxTokens,
14+
genAzureChatCompletion,
1015
} = require('~/utils');
11-
const { encodeAndFormat, validateVisionModel } = require('~/server/services/Files/images');
16+
const { encodeAndFormat } = require('~/server/services/Files/images/encode');
1217
const { truncateText, formatMessage, CUT_OFF_PROMPT } = require('./prompts');
1318
const { handleOpenAIErrors } = require('./tools/util');
1419
const spendTokens = require('~/models/spendTokens');
@@ -630,6 +635,7 @@ class OpenAIClient extends BaseClient {
630635
context,
631636
tokenBuffer,
632637
initialMessageCount,
638+
conversationId,
633639
}) {
634640
const modelOptions = {
635641
modelName: modelName ?? model,
@@ -677,7 +683,7 @@ class OpenAIClient extends BaseClient {
677683
callbacks: runManager.createCallbacks({
678684
context,
679685
tokenBuffer,
680-
conversationId: this.conversationId,
686+
conversationId: this.conversationId ?? conversationId,
681687
initialMessageCount,
682688
}),
683689
});
@@ -693,12 +699,13 @@ class OpenAIClient extends BaseClient {
693699
*
694700
* @param {Object} params - The parameters for the conversation title generation.
695701
* @param {string} params.text - The user's input.
702+
* @param {string} [params.conversationId] - The current conversationId, if not already defined on client initialization.
696703
* @param {string} [params.responseText=''] - The AI's immediate response to the user.
697704
*
698705
* @returns {Promise<string | 'New Chat'>} A promise that resolves to the generated conversation title.
699706
* In case of failure, it will return the default title, "New Chat".
700707
*/
701-
async titleConvo({ text, responseText = '' }) {
708+
async titleConvo({ text, conversationId, responseText = '' }) {
702709
let title = 'New Chat';
703710
const convo = `||>User:
704711
"${truncateText(text)}"
@@ -758,7 +765,12 @@ ${convo}
758765

759766
try {
760767
this.abortController = new AbortController();
761-
const llm = this.initializeLLM({ ...modelOptions, context: 'title', tokenBuffer: 150 });
768+
const llm = this.initializeLLM({
769+
...modelOptions,
770+
conversationId,
771+
context: 'title',
772+
tokenBuffer: 150,
773+
});
762774
title = await runTitleChain({ llm, text, convo, signal: this.abortController.signal });
763775
} catch (e) {
764776
if (e?.message?.toLowerCase()?.includes('abort')) {

api/app/clients/PluginsClient.js

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const { CallbackManager } = require('langchain/callbacks');
33
const { BufferMemory, ChatMessageHistory } = require('langchain/memory');
44
const { initializeCustomAgent, initializeFunctionsAgent } = require('./agents');
55
const { addImages, buildErrorInput, buildPromptPrefix } = require('./output_parsers');
6+
const { processFileURL } = require('~/server/services/Files/process');
67
const { EModelEndpoint } = require('librechat-data-provider');
78
const { formatLangChainMessages } = require('./prompts');
89
const checkBalance = require('~/models/checkBalance');
@@ -113,6 +114,7 @@ class PluginsClient extends OpenAIClient {
113114
openAIApiKey: this.openAIApiKey,
114115
conversationId: this.conversationId,
115116
fileStrategy: this.options.req.app.locals.fileStrategy,
117+
processFileURL,
116118
message,
117119
},
118120
});

api/app/clients/prompts/formatMessages.spec.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
const { formatMessage, formatLangChainMessages, formatFromLangChain } = require('./formatMessages');
1+
const { Constants } = require('librechat-data-provider');
22
const { HumanMessage, AIMessage, SystemMessage } = require('langchain/schema');
3+
const { formatMessage, formatLangChainMessages, formatFromLangChain } = require('./formatMessages');
34

45
describe('formatMessage', () => {
56
it('formats user message', () => {
@@ -61,7 +62,7 @@ describe('formatMessage', () => {
6162
isCreatedByUser: true,
6263
isEdited: false,
6364
model: null,
64-
parentMessageId: '00000000-0000-0000-0000-000000000000',
65+
parentMessageId: Constants.NO_PARENT,
6566
sender: 'User',
6667
text: 'hi',
6768
tokenCount: 5,

api/app/clients/specs/BaseClient.test.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
const { Constants } = require('librechat-data-provider');
12
const { initializeFakeClient } = require('./FakeClient');
23

34
jest.mock('../../../lib/db/connectDb');
@@ -307,7 +308,7 @@ describe('BaseClient', () => {
307308
const unorderedMessages = [
308309
{ id: '3', parentMessageId: '2', text: 'Message 3' },
309310
{ id: '2', parentMessageId: '1', text: 'Message 2' },
310-
{ id: '1', parentMessageId: '00000000-0000-0000-0000-000000000000', text: 'Message 1' },
311+
{ id: '1', parentMessageId: Constants.NO_PARENT, text: 'Message 1' },
311312
];
312313

313314
it('should return ordered messages based on parentMessageId', () => {
@@ -316,7 +317,7 @@ describe('BaseClient', () => {
316317
parentMessageId: '3',
317318
});
318319
expect(result).toEqual([
319-
{ id: '1', parentMessageId: '00000000-0000-0000-0000-000000000000', text: 'Message 1' },
320+
{ id: '1', parentMessageId: Constants.NO_PARENT, text: 'Message 1' },
320321
{ id: '2', parentMessageId: '1', text: 'Message 2' },
321322
{ id: '3', parentMessageId: '2', text: 'Message 3' },
322323
]);

api/app/clients/specs/PluginsClient.test.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
const crypto = require('crypto');
2+
const { Constants } = require('librechat-data-provider');
13
const { HumanChatMessage, AIChatMessage } = require('langchain/schema');
24
const PluginsClient = require('../PluginsClient');
3-
const crypto = require('crypto');
45

56
jest.mock('~/lib/db/connectDb');
67
jest.mock('~/models/Conversation', () => {
@@ -66,7 +67,7 @@ describe('PluginsClient', () => {
6667
TestAgent.setOptions(opts);
6768
}
6869
const conversationId = opts.conversationId || crypto.randomUUID();
69-
const parentMessageId = opts.parentMessageId || '00000000-0000-0000-0000-000000000000';
70+
const parentMessageId = opts.parentMessageId || Constants.NO_PARENT;
7071
const userMessageId = opts.overrideParentMessageId || crypto.randomUUID();
7172
this.pastMessages = await TestAgent.loadHistory(
7273
conversationId,

api/app/clients/tools/DALL-E.js

+22-10
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ const OpenAI = require('openai');
33
const { v4: uuidv4 } = require('uuid');
44
const { Tool } = require('langchain/tools');
55
const { HttpsProxyAgent } = require('https-proxy-agent');
6+
const { FileContext } = require('librechat-data-provider');
67
const { getImageBasename } = require('~/server/services/Files/images');
7-
const { processFileURL } = require('~/server/services/Files/process');
88
const extractBaseURL = require('~/utils/extractBaseURL');
99
const { logger } = require('~/config');
1010

@@ -14,6 +14,9 @@ class OpenAICreateImage extends Tool {
1414

1515
this.userId = fields.userId;
1616
this.fileStrategy = fields.fileStrategy;
17+
if (fields.processFileURL) {
18+
this.processFileURL = fields.processFileURL.bind(this);
19+
}
1720
let apiKey = fields.DALLE2_API_KEY ?? fields.DALLE_API_KEY ?? this.getApiKey();
1821

1922
const config = { apiKey };
@@ -80,13 +83,21 @@ Guidelines:
8083
}
8184

8285
async _call(input) {
83-
const resp = await this.openai.images.generate({
84-
prompt: this.replaceUnwantedChars(input),
85-
// TODO: Future idea -- could we ask an LLM to extract these arguments from an input that might contain them?
86-
n: 1,
87-
// size: '1024x1024'
88-
size: '512x512',
89-
});
86+
let resp;
87+
88+
try {
89+
resp = await this.openai.images.generate({
90+
prompt: this.replaceUnwantedChars(input),
91+
// TODO: Future idea -- could we ask an LLM to extract these arguments from an input that might contain them?
92+
n: 1,
93+
// size: '1024x1024'
94+
size: '512x512',
95+
});
96+
} catch (error) {
97+
logger.error('[DALL-E] Problem generating the image:', error);
98+
return `Something went wrong when trying to generate the image. The DALL-E API may be unavailable:
99+
Error Message: ${error.message}`;
100+
}
90101

91102
const theImageUrl = resp.data[0].url;
92103

@@ -110,15 +121,16 @@ Guidelines:
110121
});
111122

112123
try {
113-
const result = await processFileURL({
124+
const result = await this.processFileURL({
114125
fileStrategy: this.fileStrategy,
115126
userId: this.userId,
116127
URL: theImageUrl,
117128
fileName: imageName,
118129
basePath: 'images',
130+
context: FileContext.image_generation,
119131
});
120132

121-
this.result = this.wrapInMarkdown(result);
133+
this.result = this.wrapInMarkdown(result.filepath);
122134
} catch (error) {
123135
logger.error('Error while saving the image:', error);
124136
this.result = `Failed to save the image locally. ${error.message}`;

api/app/clients/tools/index.js

+23-16
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,42 @@
1+
const availableTools = require('./manifest.json');
2+
// Basic Tools
3+
const CodeBrew = require('./CodeBrew');
14
const GoogleSearchAPI = require('./GoogleSearch');
5+
const WolframAlphaAPI = require('./Wolfram');
6+
const AzureAiSearch = require('./AzureAiSearch');
27
const OpenAICreateImage = require('./DALL-E');
3-
const DALLE3 = require('./structured/DALLE3');
4-
const StructuredSD = require('./structured/StableDiffusion');
58
const StableDiffusionAPI = require('./StableDiffusion');
6-
const WolframAlphaAPI = require('./Wolfram');
7-
const StructuredWolfram = require('./structured/Wolfram');
89
const SelfReflectionTool = require('./SelfReflection');
9-
const AzureAiSearch = require('./AzureAiSearch');
10-
const StructuredACS = require('./structured/AzureAISearch');
10+
11+
// Structured Tools
12+
const DALLE3 = require('./structured/DALLE3');
1113
const ChatTool = require('./structured/ChatTool');
1214
const E2BTools = require('./structured/E2BTools');
1315
const CodeSherpa = require('./structured/CodeSherpa');
16+
const StructuredSD = require('./structured/StableDiffusion');
17+
const StructuredACS = require('./structured/AzureAISearch');
1418
const CodeSherpaTools = require('./structured/CodeSherpaTools');
15-
const availableTools = require('./manifest.json');
16-
const CodeBrew = require('./CodeBrew');
19+
const StructuredWolfram = require('./structured/Wolfram');
20+
const TavilySearchResults = require('./structured/TavilySearchResults');
1721

1822
module.exports = {
1923
availableTools,
24+
// Basic Tools
25+
CodeBrew,
26+
AzureAiSearch,
2027
GoogleSearchAPI,
28+
WolframAlphaAPI,
2129
OpenAICreateImage,
22-
DALLE3,
2330
StableDiffusionAPI,
24-
StructuredSD,
25-
WolframAlphaAPI,
26-
StructuredWolfram,
2731
SelfReflectionTool,
28-
AzureAiSearch,
29-
StructuredACS,
30-
E2BTools,
32+
// Structured Tools
33+
DALLE3,
3134
ChatTool,
35+
E2BTools,
3236
CodeSherpa,
37+
StructuredSD,
38+
StructuredACS,
3339
CodeSherpaTools,
34-
CodeBrew,
40+
StructuredWolfram,
41+
TavilySearchResults,
3542
};

0 commit comments

Comments
 (0)