feat: Assistants API, General File Support, Side Panel, File Explorer (#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 #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 (#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 <messagedaniel@protonmail.com>

* 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 <81851188+Berry-13@users.noreply.github.com>
This commit is contained in:
Danny Avila 2024-02-13 20:42:27 -05:00 committed by GitHub
parent cd2786441a
commit ecd63eb9f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
316 changed files with 21873 additions and 6315 deletions

View file

@ -0,0 +1,296 @@
import { useFormContext } from 'react-hook-form';
import * as RadioGroup from '@radix-ui/react-radio-group';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import {
AuthTypeEnum,
AuthorizationTypeEnum,
TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import { DialogContent } from '~/components/ui/';
export default function ActionsAuth({
setOpenAuthDialog,
}: {
setOpenAuthDialog: React.Dispatch<React.SetStateAction<boolean>>;
}) {
const { watch, setValue, trigger } = useFormContext();
const type = watch('type');
return (
<DialogContent
role="dialog"
id="radix-:rf5:"
aria-describedby="radix-:rf7:"
aria-labelledby="radix-:rf6:"
data-state="open"
className="left-1/2 col-auto col-start-2 row-auto row-start-2 w-full max-w-md -translate-x-1/2 rounded-xl bg-white pb-0 text-left shadow-xl transition-all dark:bg-gray-900 dark:text-gray-100"
tabIndex={-1}
style={{ pointerEvents: 'auto' }}
>
<div className="flex items-center justify-between border-b border-black/10 px-4 pb-4 pt-5 dark:border-white/10 sm:p-6">
<div className="flex">
<div className="flex items-center">
<div className="flex grow flex-col gap-1">
<h2
id="radix-:rf6:"
className="text-token-text-primary text-lg font-medium leading-6"
>
Authentication
</h2>
</div>
</div>
</div>
</div>
<div className="p-4 sm:p-6 sm:pt-0">
<div className="mb-4">
<label className="mb-1 block text-sm font-medium">Authentication Type</label>
<RadioGroup.Root
defaultValue={AuthTypeEnum.None}
onValueChange={(value) => setValue('type', value)}
value={type}
role="radiogroup"
aria-required="false"
dir="ltr"
className="flex gap-4"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rf8:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.None}
id=":rf8:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
None
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rfa:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthTypeEnum.ServiceHttp}
id=":rfa:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={0}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
API Key
</label>
</div>
<div className="flex items-center gap-2 text-gray-500">
<label htmlFor=":rfc:" className="flex cursor-not-allowed items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
disabled={true}
value={AuthTypeEnum.OAuth}
id=":rfc:"
className="mr-1 flex h-5 w-5 cursor-not-allowed items-center justify-center rounded-full border border-gray-500 bg-gray-300 dark:border-gray-600 dark:bg-gray-900"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
OAuth
</label>
</div>
</RadioGroup.Root>
</div>
{type === 'none' ? null : type === 'service_http' ? <ApiKey /> : <OAuth />}
{/* Cancel/Save */}
<div className="mt-5 flex flex-col gap-3 sm:mt-4 sm:flex-row-reverse">
<button
className="btn btn-dark relative"
onClick={async () => {
const result = await trigger(undefined, { shouldFocus: true });
setValue('saved_auth_fields', result);
setOpenAuthDialog(!result);
}}
>
<div className="flex w-full items-center justify-center gap-2">Save</div>
</button>
<DialogPrimitive.Close className="btn btn-neutral relative">
<div className="flex w-full items-center justify-center gap-2">Cancel</div>
</DialogPrimitive.Close>
</div>
</div>
</DialogContent>
);
}
const ApiKey = () => {
const { register, watch, setValue } = useFormContext();
const authorization_type = watch('authorization_type');
const type = watch('type');
return (
<>
<label className="mb-1 block text-sm font-medium">API Key</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('api_key', { required: type === AuthTypeEnum.ServiceHttp })}
/>
<label className="mb-1 block text-sm font-medium">Auth Type</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('authorization_type', value)}
value={authorization_type}
role="radiogroup"
aria-required="true"
dir="ltr"
className="mb-2 flex gap-6 overflow-hidden rounded-lg"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rfu:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Basic}
id=":rfu:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Basic
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rg0:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Bearer}
id=":rg0:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Bearer
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rg2:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={AuthorizationTypeEnum.Custom}
id=":rg2:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={0}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Custom
</label>
</div>
</RadioGroup.Root>
{authorization_type === AuthorizationTypeEnum.Custom && (
<div className="mt-2">
<label className="mb-1 block text-sm font-medium">Custom Header Name</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
placeholder="X-Api-Key"
{...register('custom_auth_header', {
required: authorization_type === AuthorizationTypeEnum.Custom,
})}
/>
</div>
)}
</>
);
};
const OAuth = () => {
const { register, watch, setValue } = useFormContext();
const token_exchange_method = watch('token_exchange_method');
const type = watch('type');
return (
<>
<label className="mb-1 block text-sm font-medium">Client ID</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('oauth_client_id', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Client Secret</label>
<input
placeholder="<HIDDEN>"
type="password"
autoComplete="off"
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('oauth_client_secret', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Authorization URL</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('authorization_url', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Token URL</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('client_url', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Scope</label>
<input
className="border-token-border-medium mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800"
{...register('scope', { required: type === AuthTypeEnum.OAuth })}
/>
<label className="mb-1 block text-sm font-medium">Token Exchange Method</label>
<RadioGroup.Root
defaultValue={AuthorizationTypeEnum.Basic}
onValueChange={(value) => setValue('token_exchange_method', value)}
value={token_exchange_method}
role="radiogroup"
aria-required="true"
dir="ltr"
tabIndex={0}
style={{ outline: 'none' }}
>
<div className="flex items-center gap-2">
<label htmlFor=":rj1:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={TokenExchangeMethodEnum.DefaultPost}
id=":rj1:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Default (POST request)
</label>
</div>
<div className="flex items-center gap-2">
<label htmlFor=":rj3:" className="flex cursor-pointer items-center gap-1">
<RadioGroup.Item
type="button"
role="radio"
value={TokenExchangeMethodEnum.BasicAuthHeader}
id=":rj3:"
className="mr-1 flex h-5 w-5 items-center justify-center rounded-full border border-gray-500 bg-white dark:border-gray-600 dark:bg-gray-700"
tabIndex={-1}
>
<RadioGroup.Indicator className="h-2 w-2 rounded-full bg-gray-950 dark:bg-white"></RadioGroup.Indicator>
</RadioGroup.Item>
Basic authorization header
</label>
</div>
</RadioGroup.Root>
</>
);
};

View file

@ -0,0 +1,267 @@
import debounce from 'lodash/debounce';
import { useState, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';
import {
validateAndParseOpenAPISpec,
openapiToFunction,
AuthTypeEnum,
} from 'librechat-data-provider';
import type {
ValidationResult,
Action,
FunctionTool,
ActionMetadata,
} from 'librechat-data-provider';
import type { ActionAuthForm } from '~/common';
import type { Spec } from './ActionsTable';
import { ActionsTable, columns } from './ActionsTable';
import { useUpdateAction } from '~/data-provider';
import { cn, removeFocusOutlines } from '~/utils';
import { Spinner } from '~/components/svg';
const debouncedValidation = debounce(
(input: string, callback: (result: ValidationResult) => void) => {
const result = validateAndParseOpenAPISpec(input);
callback(result);
},
800,
);
export default function ActionsInput({
action,
assistant_id,
setAction,
}: {
action?: Action;
assistant_id?: string;
setAction: React.Dispatch<React.SetStateAction<Action | undefined>>;
}) {
const handleResult = (result: ValidationResult) => {
if (!result.status) {
setData(null);
setFunctions(null);
}
setValidationResult(result);
};
const { handleSubmit, reset } = useFormContext<ActionAuthForm>();
const [validationResult, setValidationResult] = useState<null | ValidationResult>(null);
const [inputValue, setInputValue] = useState('');
const [data, setData] = useState<Spec[] | null>(null);
const [functions, setFunctions] = useState<FunctionTool[] | null>(null);
useEffect(() => {
if (!action?.metadata?.raw_spec) {
return;
}
setInputValue(action.metadata.raw_spec);
debouncedValidation(action.metadata.raw_spec, handleResult);
}, [action?.metadata?.raw_spec]);
useEffect(() => {
if (!validationResult || !validationResult.status || !validationResult.spec) {
return;
}
const { functionSignatures, requestBuilders } = openapiToFunction(validationResult.spec);
const specs = Object.entries(requestBuilders).map(([name, props]) => {
return {
name,
method: props.method,
path: props.path,
domain: props.domain,
};
});
setData(specs);
setValidationResult(null);
setFunctions(functionSignatures.map((f) => f.toObjectTool()));
}, [validationResult]);
const updateAction = useUpdateAction({
onSuccess(data) {
reset();
setAction(data[2]);
},
});
const saveAction = handleSubmit((authFormData) => {
console.log('authFormData', authFormData);
if (!assistant_id) {
// alert user?
return;
}
if (!functions) {
return;
}
if (!data) {
return;
}
let { metadata = {} } = action ?? {};
const action_id = action?.action_id;
metadata.raw_spec = inputValue;
const parsedUrl = new URL(data[0].domain);
const domain = parsedUrl.hostname;
if (!domain) {
// alert user?
return;
}
metadata.domain = domain;
const { type, saved_auth_fields } = authFormData;
const removeSensitiveFields = (obj: ActionMetadata) => {
delete obj.auth;
delete obj.api_key;
delete obj.oauth_client_id;
delete obj.oauth_client_secret;
};
if (saved_auth_fields && type === AuthTypeEnum.ServiceHttp) {
metadata = {
...metadata,
api_key: authFormData.api_key,
auth: {
type,
authorization_type: authFormData.authorization_type,
custom_auth_header: authFormData.custom_auth_header,
},
};
} else if (saved_auth_fields && type === AuthTypeEnum.OAuth) {
metadata = {
...metadata,
auth: {
type,
authorization_url: authFormData.authorization_url,
client_url: authFormData.client_url,
scope: authFormData.scope,
token_exchange_method: authFormData.token_exchange_method,
},
oauth_client_id: authFormData.oauth_client_id,
oauth_client_secret: authFormData.oauth_client_secret,
};
} else if (saved_auth_fields) {
removeSensitiveFields(metadata);
metadata.auth = {
type,
};
} else {
removeSensitiveFields(metadata);
}
updateAction.mutate({
action_id,
metadata,
functions,
assistant_id,
});
});
const handleInputChange: React.ChangeEventHandler<HTMLTextAreaElement> = (event) => {
const newValue = event.target.value;
setInputValue(newValue);
if (!newValue) {
setData(null);
setFunctions(null);
return setValidationResult(null);
}
debouncedValidation(newValue, handleResult);
};
return (
<>
<div className="">
<div className="mb-1 flex flex-wrap items-center justify-between gap-4">
<label className="text-token-text-primary whitespace-nowrap font-medium">Schema</label>
<div className="flex items-center gap-2">
{/* <button className="btn btn-neutral border-token-border-light relative h-8 min-w-[100px] rounded-lg font-medium">
<div className="flex w-full items-center justify-center text-xs">Import from URL</div>
</button> */}
<select
onChange={(e) => console.log(e.target.value)}
className="border-token-border-medium h-8 min-w-[100px] rounded-lg border bg-transparent px-2 py-0 text-sm"
>
<option value="label">Examples</option>
<option value="0">Weather (JSON)</option>
<option value="1">Pet Store (YAML)</option>
<option value="2">Blank Template</option>
</select>
</div>
</div>
<div className="border-token-border-light mb-4 overflow-hidden rounded-lg border">
<div className="relative">
<textarea
value={inputValue}
onChange={handleInputChange}
spellCheck="false"
placeholder="Enter your OpenAPI schema here"
className={cn(
'text-token-text-primary block h-96 w-full border-none bg-transparent p-2 font-mono text-xs',
removeFocusOutlines,
)}
/>
{/* TODO: format input button */}
</div>
{validationResult && validationResult.message !== 'OpenAPI spec is valid.' && (
<div className="border-token-border-light border-t p-2 text-red-500">
{validationResult.message.split('\n').map((line: string, i: number) => (
<div key={i}>{line}</div>
))}
</div>
)}
</div>
</div>
{!!data && (
<div>
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">Available actions</label>
</div>
<ActionsTable columns={columns} data={data} />
</div>
)}
<div className="mt-4">
<div className="mb-1.5 flex items-center">
<span className="" data-state="closed">
<label className="text-token-text-primary block font-medium">Privacy policy</label>
</span>
</div>
<div className="rounded-md border border-gray-300 px-3 py-2 shadow-none focus-within:border-gray-800 focus-within:ring-1 focus-within:ring-gray-800 dark:bg-gray-700 dark:focus-within:border-white dark:focus-within:ring-white">
<label
htmlFor="privacyPolicyUrl"
className="block text-xs font-medium text-gray-900 dark:text-gray-100"
/>
<div className="relative">
<input
name="privacyPolicyUrl"
id="privacyPolicyUrl"
className="block w-full border-0 p-0 text-gray-900 placeholder-gray-500 shadow-none outline-none focus-within:shadow-none focus-within:outline-none focus-within:ring-0 focus:border-none focus:ring-0 dark:bg-gray-700 dark:text-gray-100 sm:text-sm"
placeholder="https://api.example-weather-app.com/privacy"
// value=""
/>
</div>
</div>
</div>
<div className="flex items-center justify-end">
<button
disabled={!functions || !functions.length}
onClick={saveAction}
className="focus:shadow-outline mt-1 flex min-w-[100px] items-center justify-center rounded bg-green-500 px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500 focus:outline-none focus:ring-0 disabled:bg-green-400"
type="button"
>
{/* TODO: Add localization */}
{updateAction.isLoading ? (
<Spinner className="icon-md" />
) : action?.action_id ? (
'Update'
) : (
'Create'
)}
</button>
</div>
</>
);
}

View file

@ -0,0 +1,178 @@
import { useEffect, useState } from 'react';
import { useForm, FormProvider } from 'react-hook-form';
import {
AuthTypeEnum,
AuthorizationTypeEnum,
TokenExchangeMethodEnum,
} from 'librechat-data-provider';
import type { AssistantPanelProps, ActionAuthForm } from '~/common';
import { Dialog, DialogTrigger } from '~/components/ui';
import { useDeleteAction } from '~/data-provider';
import { NewTrashIcon } from '~/components/svg';
import ActionsInput from './ActionsInput';
import ActionsAuth from './ActionsAuth';
import { Panel } from '~/common';
export default function ActionsPanel({
// activePanel,
action,
setAction,
setActivePanel,
assistant_id,
}: AssistantPanelProps) {
const [openAuthDialog, setOpenAuthDialog] = useState(false);
const deleteAction = useDeleteAction({
onSuccess: () => {
setActivePanel(Panel.builder);
setAction(undefined);
},
});
const methods = useForm<ActionAuthForm>({
defaultValues: {
/* General */
type: AuthTypeEnum.None,
saved_auth_fields: false,
/* API key */
api_key: '',
authorization_type: AuthorizationTypeEnum.Basic,
custom_auth_header: '',
/* OAuth */
oauth_client_id: '',
oauth_client_secret: '',
authorization_url: '',
client_url: '',
scope: '',
token_exchange_method: TokenExchangeMethodEnum.DefaultPost,
},
});
const { reset, watch } = methods;
const type = watch('type');
useEffect(() => {
if (action?.metadata?.auth) {
reset({
type: action.metadata.auth.type || AuthTypeEnum.None,
saved_auth_fields: false,
api_key: action.metadata.api_key ?? '',
authorization_type: action.metadata.auth.authorization_type || AuthorizationTypeEnum.Basic,
oauth_client_id: action.metadata.oauth_client_id ?? '',
oauth_client_secret: action.metadata.oauth_client_secret ?? '',
authorization_url: action.metadata.auth.authorization_url ?? '',
client_url: action.metadata.auth.client_url ?? '',
scope: action.metadata.auth.scope ?? '',
token_exchange_method:
action.metadata.auth.token_exchange_method ?? TokenExchangeMethodEnum.DefaultPost,
});
}
}, [action, reset]);
return (
<FormProvider {...methods}>
<form className="h-full grow overflow-hidden">
<div className="h-full overflow-auto px-2 pb-12 text-sm">
<div className="relative flex flex-col items-center px-16 py-6 text-center">
<div className="absolute left-0 top-6">
<button
type="button"
className="btn btn-neutral relative"
onClick={() => {
setActivePanel(Panel.builder);
setAction(undefined);
}}
>
<div className="flex w-full items-center justify-center gap-2">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-md"
>
<path
d="M15 5L8 12L15 19"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
></path>
</svg>
</div>
</button>
</div>
{!!action && (
<div className="absolute right-0 top-6">
<button
type="button"
disabled={!assistant_id || !action.action_id}
className="btn btn-neutral relative text-red-500"
onClick={() => {
if (!assistant_id) {
return prompt('No assistant_id found, is the assistant created?');
}
const confirmed = confirm('Are you sure you want to delete this action?');
if (confirmed) {
deleteAction.mutate({
action_id: action.action_id,
assistant_id,
});
}
}}
>
<div className="flex w-full items-center justify-center gap-2">
<NewTrashIcon className="icon-md text-red-500" />
</div>
</button>
</div>
)}
<div className="text-xl font-medium">{(action ? 'Edit' : 'Add') + ' ' + 'actions'}</div>
<div className="text-token-text-tertiary text-sm">
{/* TODO: use App title */}
Let your Assistant retrieve information or take actions outside of LibreChat.
</div>
{/* <div className="text-sm text-token-text-tertiary">
<a href="https://help.openai.com/en/articles/8554397-creating-a-gpt" target="_blank" rel="noreferrer" className="font-medium">Learn more.</a>
</div> */}
</div>
<Dialog open={openAuthDialog} onOpenChange={setOpenAuthDialog}>
<DialogTrigger asChild>
<div className="relative mb-6">
<div className="mb-1.5 flex items-center">
<label className="text-token-text-primary block font-medium">
Authentication
</label>
</div>
<div className="border-token-border-medium flex rounded-lg border text-sm hover:cursor-pointer">
<div className="h-9 grow px-3 py-2">{type}</div>
<div className="bg-token-border-medium w-px"></div>
<button type="button" color="neutral" className="flex items-center gap-2 px-3">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-sm"
>
<path
d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92002 3.98596L9.49644 4.70605C8.96184 5.61487 7.98938 6.17632 6.93501 6.18489L6.09967 6.19168C5.39096 6.19744 4.73823 6.57783 4.38386 7.19161L4.02776 7.80841C3.67339 8.42219 3.67032 9.17767 4.01969 9.7943L4.43151 10.5212C4.95127 11.4386 4.95127 12.5615 4.43151 13.4788L4.01969 14.2057C3.67032 14.8224 3.67339 15.5778 4.02776 16.1916L4.38386 16.8084C4.73823 17.4222 5.39096 17.8026 6.09966 17.8083L6.93502 17.8151C7.98939 17.8237 8.96185 18.3851 9.49645 19.294L9.92002 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
<circle cx="12" cy="12" r="2.5" stroke="currentColor" strokeWidth="2" />
</svg>
</button>
</div>
</div>
</DialogTrigger>
<ActionsAuth setOpenAuthDialog={setOpenAuthDialog} />
</Dialog>
<ActionsInput action={action} assistant_id={assistant_id} setAction={setAction} />
</div>
</form>
</FormProvider>
);
}

View file

@ -0,0 +1,54 @@
import type { ColumnDef } from '@tanstack/react-table';
export type Spec = {
name: string;
method: string;
path: string;
domain: string;
};
export const fakeData: Spec[] = [
{
name: 'listPets',
method: 'get',
path: '/pets',
domain: 'petstore.swagger.io',
},
{
name: 'createPets',
method: 'post',
path: '/pets',
domain: 'petstore.swagger.io',
},
{
name: 'showPetById',
method: 'get',
path: '/pets/{petId}',
domain: 'petstore.swagger.io',
},
];
export const columns: ColumnDef<Spec>[] = [
{
header: 'Name',
accessorKey: 'name',
},
{
header: 'Method',
accessorKey: 'method',
},
{
header: 'Path',
accessorKey: 'path',
},
// {
// header: '',
// accessorKey: 'action',
// // eslint-disable-next-line @typescript-eslint/no-unused-vars
// cell: ({ row: _row }) => (
// <button className="btn relative btn-neutral h-8 rounded-lg border-token-border-light font-medium">
// <div className="flex w-full gap-2 items-center justify-center">Test</div>
// </button>
// ),
// },
];

View file

@ -0,0 +1,47 @@
import { useReactTable, flexRender, getCoreRowModel } from '@tanstack/react-table';
import type { ColumnDef } from '@tanstack/react-table';
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
}
export default function DataTable<TData, TValue>({ columns, data }: DataTableProps<TData, TValue>) {
const table = useReactTable({
columns,
data,
getCoreRowModel: getCoreRowModel(),
});
return (
<table className="w-full text-sm">
<thead>
{table.getHeaderGroups().map((headerGroup, i) => (
<tr
key={i}
className="border-token-border-light text-token-text-tertiary border-b text-left text-xs"
>
{headerGroup.headers.map((header, j) => (
<th key={j} className="py-1 font-normal">
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row, i) => (
<tr key={i} className="border-token-border-light border-b">
{row.getVisibleCells().map((cell, j) => (
<td key={j} className="py-2">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}

View file

@ -0,0 +1,2 @@
export { default as ActionsTable } from './Table';
export * from './Columns';

View file

@ -0,0 +1,33 @@
import type { Action } from 'librechat-data-provider';
import GearIcon from '~/components/svg/GearIcon';
export default function AssistantAction({
action,
onClick,
}: {
action: Action;
onClick: () => void;
}) {
return (
<div>
<div
onClick={onClick}
className="border-token-border-medium flex w-full rounded-lg border text-sm hover:cursor-pointer"
>
<div
className="h-9 grow px-3 py-2"
style={{ textOverflow: 'ellipsis', wordBreak: 'break-all', overflow: 'hidden' }}
>
{action.metadata.domain}
</div>
<div className="w-px bg-gray-300 dark:bg-gray-600" />
<button
type="button"
className="flex h-9 w-9 min-w-9 items-center justify-center rounded-lg rounded-l-none"
>
<GearIcon className="icon-sm" />
</button>
</div>
</div>
);
}

View file

@ -0,0 +1,204 @@
import * as Popover from '@radix-ui/react-popover';
import { useState, useEffect, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import {
fileConfig as defaultFileConfig,
QueryKeys,
defaultOrderQuery,
mergeFileConfig,
} from 'librechat-data-provider';
import type { UseMutationResult } from '@tanstack/react-query';
import type {
Metadata,
AssistantListResponse,
Assistant,
AssistantCreateParams,
} from 'librechat-data-provider';
import { useUploadAssistantAvatarMutation, useGetFileConfig } from '~/data-provider';
import { AssistantAvatar, NoImage, AvatarMenu } from './Images';
import { useToastContext } from '~/Providers';
// import { Spinner } from '~/components/svg';
import { useLocalize } from '~/hooks';
// import { cn } from '~/utils/';
function Avatar({
assistant_id,
metadata,
createMutation,
}: {
assistant_id: string | null;
metadata: null | Metadata;
createMutation: UseMutationResult<Assistant, Error, AssistantCreateParams>;
}) {
// console.log('Avatar', assistant_id, metadata, createMutation);
const queryClient = useQueryClient();
const [menuOpen, setMenuOpen] = useState(false);
const [progress, setProgress] = useState<number>(1);
const [input, setInput] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const lastSeenCreatedId = useRef<string | null>(null);
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
select: (data) => mergeFileConfig(data),
});
const localize = useLocalize();
const { showToast } = useToastContext();
const { mutate: uploadAvatar } = useUploadAssistantAvatarMutation({
onMutate: () => {
setProgress(0.4);
},
onSuccess: (data, vars) => {
if (!vars.postCreation) {
showToast({ message: localize('com_ui_upload_success') });
} else if (lastSeenCreatedId.current !== createMutation.data?.id) {
lastSeenCreatedId.current = createMutation.data?.id ?? '';
}
setInput(null);
setPreviewUrl(data.metadata?.avatar as string | null);
const res = queryClient.getQueryData<AssistantListResponse>([
QueryKeys.assistants,
defaultOrderQuery,
]);
if (!res?.data || !res) {
return;
}
const assistants =
res.data.map((assistant) => {
if (assistant.id === assistant_id) {
return {
...assistant,
...data,
};
}
return assistant;
}) ?? [];
queryClient.setQueryData<AssistantListResponse>([QueryKeys.assistants, defaultOrderQuery], {
...res,
data: assistants,
});
setProgress(1);
},
onError: (error) => {
console.error('Error:', error);
setInput(null);
setPreviewUrl(null);
showToast({ message: localize('com_ui_upload_error'), status: 'error' });
setProgress(1);
},
});
useEffect(() => {
if (input) {
const reader = new FileReader();
reader.onloadend = () => {
setPreviewUrl(reader.result as string);
};
reader.readAsDataURL(input);
}
}, [input]);
useEffect(() => {
setPreviewUrl((metadata?.avatar as string | undefined) ?? null);
}, [metadata]);
useEffect(() => {
/** Experimental: Condition to prime avatar upload before Assistant Creation
* - If the createMutation state Id was last seen (current) and the createMutation is successful
* we can assume that the avatar upload has already been initiated and we can skip the upload
*
* The mutation state is not reset until the user deliberately selects a new assistant or an assistant is deleted
*
* This prevents the avatar from being uploaded multiple times before the user selects a new assistant
* while allowing the user to upload to prime the avatar and other values before the assistant is created.
*/
const sharedUploadCondition = !!(
createMutation.isSuccess &&
input &&
previewUrl &&
previewUrl?.includes('base64')
);
if (sharedUploadCondition && lastSeenCreatedId.current === createMutation.data?.id) {
return;
}
if (sharedUploadCondition && createMutation.data.id) {
console.log('[AssistantAvatar] Uploading Avatar after Assistant Creation');
const formData = new FormData();
formData.append('file', input, input.name);
formData.append('assistant_id', createMutation.data.id);
if (typeof createMutation.data?.metadata === 'object') {
formData.append('metadata', JSON.stringify(createMutation.data?.metadata));
}
uploadAvatar({
assistant_id: createMutation.data.id,
postCreation: true,
formData,
});
}
}, [createMutation.data, createMutation.isSuccess, input, previewUrl, uploadAvatar]);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
const file = event.target.files?.[0];
if (fileConfig.avatarSizeLimit && file && file.size <= fileConfig.avatarSizeLimit) {
if (!file) {
console.error('No file selected');
return;
}
setInput(file);
setMenuOpen(false);
if (!assistant_id) {
// wait for successful form submission before uploading avatar
console.log('[AssistantAvatar] No assistant_id, will wait until form submission + upload');
return;
}
const formData = new FormData();
formData.append('file', file, file.name);
formData.append('assistant_id', assistant_id);
if (typeof metadata === 'object') {
formData.append('metadata', JSON.stringify(metadata));
}
uploadAvatar({
assistant_id,
formData,
});
} else {
showToast({
message: localize('com_ui_upload_invalid'),
status: 'error',
});
}
setMenuOpen(false);
};
return (
<Popover.Root open={menuOpen} onOpenChange={setMenuOpen}>
<div className="flex w-full items-center justify-center gap-4">
<Popover.Trigger asChild>
<button type="button" className="h-20 w-20">
{previewUrl ? <AssistantAvatar url={previewUrl} progress={progress} /> : <NoImage />}
</button>
</Popover.Trigger>
</div>
{<AvatarMenu handleFileChange={handleFileChange} />}
</Popover.Root>
);
}
export default Avatar;

View file

@ -0,0 +1,464 @@
import { useState, useMemo, useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useGetModelsQuery } from 'librechat-data-provider/react-query';
import { useForm, FormProvider, Controller, useWatch } from 'react-hook-form';
import {
Tools,
QueryKeys,
EModelEndpoint,
actionDelimiter,
supportsRetrieval,
defaultAssistantFormValues,
} from 'librechat-data-provider';
import type { FunctionTool, TPlugin } from 'librechat-data-provider';
import type { AssistantForm, AssistantPanelProps } from '~/common';
import { useCreateAssistantMutation, useUpdateAssistantMutation } from '~/data-provider';
import { SelectDropDown, Checkbox, QuestionMark } from '~/components/ui';
import { useAssistantsMapContext, useToastContext } from '~/Providers';
import { useSelectAssistant, useLocalize } from '~/hooks';
import { ToolSelectDialog } from '~/components/Tools';
import AssistantAvatar from './AssistantAvatar';
import AssistantSelect from './AssistantSelect';
import AssistantAction from './AssistantAction';
import ContextButton from './ContextButton';
import AssistantTool from './AssistantTool';
import { Spinner } from '~/components/svg';
import { cn, cardStyle } from '~/utils/';
import Knowledge from './Knowledge';
import { Panel } from '~/common';
const labelClass = 'mb-2 block text-xs font-bold text-gray-700 dark:text-gray-400';
const inputClass =
'focus:shadow-outline w-full appearance-none rounded-md border px-3 py-2 text-sm leading-tight text-gray-700 dark:text-white shadow focus:border-green-500 focus:outline-none focus:ring-0 dark:bg-gray-800 dark:border-gray-700/80';
export default function AssistantPanel({
// index = 0,
setAction,
actions = [],
setActivePanel,
assistant_id: current_assistant_id,
setCurrentAssistantId,
}: AssistantPanelProps) {
const queryClient = useQueryClient();
const modelsQuery = useGetModelsQuery();
const assistantMap = useAssistantsMapContext();
const [showToolDialog, setShowToolDialog] = useState(false);
const allTools = queryClient.getQueryData<TPlugin[]>([QueryKeys.tools]) ?? [];
const { onSelect: onSelectAssistant } = useSelectAssistant();
const { showToast } = useToastContext();
const localize = useLocalize();
const methods = useForm<AssistantForm>({
defaultValues: defaultAssistantFormValues,
});
const { control, handleSubmit, reset, setValue, getValues } = methods;
const assistant_id = useWatch({ control, name: 'id' });
const assistant = useWatch({ control, name: 'assistant' });
const functions = useWatch({ control, name: 'functions' });
const model = useWatch({ control, name: 'model' });
useEffect(() => {
if (model && !supportsRetrieval.has(model)) {
setValue('retrieval', false);
}
}, [model, setValue]);
/* Mutations */
const update = useUpdateAssistantMutation({
onSuccess: (data) => {
showToast({
message: `${localize('com_assistants_update_success')} ${
data.name ?? localize('com_ui_assistant')
}`,
});
},
onError: (err) => {
const error = err as Error;
showToast({
message: `${localize('com_assistants_update_error')}${
error?.message ? ` ${localize('com_ui_error')}: ${error?.message}` : ''
}`,
status: 'error',
});
},
});
const create = useCreateAssistantMutation({
onSuccess: (data) => {
setCurrentAssistantId(data.id);
showToast({
message: `${localize('com_assistants_create_success')} ${
data.name ?? localize('com_ui_assistant')
}`,
});
},
onError: (err) => {
const error = err as Error;
showToast({
message: `${localize('com_assistants_create_error')}${
error?.message ? ` ${localize('com_ui_error')}: ${error?.message}` : ''
}`,
status: 'error',
});
},
});
const files = useMemo(() => {
if (typeof assistant === 'string') {
return [];
}
return assistant.files;
}, [assistant]);
const onSubmit = (data: AssistantForm) => {
const tools: Array<FunctionTool | string> = [...functions].map((functionName) => {
if (!functionName.includes(actionDelimiter)) {
return functionName;
} else {
const assistant = assistantMap?.[assistant_id];
const tool = assistant?.tools?.find((tool) => tool.function?.name === functionName);
if (assistant && tool) {
return tool;
}
}
return functionName;
});
console.log(data);
if (data.code_interpreter) {
tools.push({ type: Tools.code_interpreter });
}
if (data.retrieval) {
tools.push({ type: Tools.retrieval });
}
const {
name,
description,
instructions,
model,
// file_ids, // TODO: add file handling here
} = data;
if (assistant_id) {
update.mutate({
assistant_id,
data: {
name,
description,
instructions,
model,
tools,
},
});
return;
}
create.mutate({
name,
description,
instructions,
model,
tools,
});
};
return (
<FormProvider {...methods}>
<form
onSubmit={handleSubmit(onSubmit)}
className="h-auto w-full flex-shrink-0 overflow-x-hidden"
>
<div className="flex w-full flex-wrap">
<Controller
name="assistant"
control={control}
render={({ field }) => (
<AssistantSelect
reset={reset}
value={field.value}
setCurrentAssistantId={setCurrentAssistantId}
selectedAssistant={current_assistant_id ?? null}
createMutation={create}
/>
)}
/>
{/* Select Button */}
{assistant_id && (
<button
className="btn btn-primary focus:shadow-outline mx-2 mt-1 h-[40px] rounded bg-green-500 px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500 focus:outline-none focus:ring-0"
type="button"
disabled={!assistant_id}
onClick={(e) => {
e.preventDefault();
onSelectAssistant(assistant_id);
}}
>
{localize('com_ui_select')}
</button>
)}
</div>
<div className="h-auto bg-white px-4 pb-8 pt-3 dark:bg-transparent">
{/* Avatar & Name */}
<div className="mb-4">
<AssistantAvatar
createMutation={create}
assistant_id={assistant_id ?? null}
metadata={assistant?.['metadata'] ?? null}
/>
<label className={labelClass} htmlFor="name">
{localize('com_ui_name')}
</label>
<Controller
name="name"
control={control}
render={({ field }) => (
<input
{...field}
value={field.value ?? ''}
{...{ max: 256 }}
className={inputClass}
id="name"
type="text"
placeholder={localize('com_assistants_name_placeholder')}
/>
)}
/>
<Controller
name="id"
control={control}
render={({ field }) => (
<p className="h-3 text-xs italic text-gray-600">{field.value ?? ''}</p>
)}
/>
</div>
{/* Description */}
<div className="mb-4">
<label className={labelClass} htmlFor="description">
{localize('com_ui_description')}
</label>
<Controller
name="description"
control={control}
render={({ field }) => (
<input
{...field}
value={field.value ?? ''}
{...{ max: 512 }}
className={inputClass}
id="description"
type="text"
placeholder={localize('com_assistants_description_placeholder')}
/>
)}
/>
</div>
{/* Instructions */}
<div className="mb-6">
<label className={labelClass} htmlFor="instructions">
{localize('com_ui_instructions')}
</label>
<Controller
name="instructions"
control={control}
render={({ field }) => (
<textarea
{...field}
value={field.value ?? ''}
{...{ max: 32768 }}
className="focus:shadow-outline min-h-[150px] w-full resize-none resize-y appearance-none rounded-md border px-3 py-2 text-sm leading-tight text-gray-700 shadow focus:border-green-500 focus:outline-none focus:ring-0 dark:border-gray-700/80 dark:bg-gray-800 dark:text-white"
id="instructions"
placeholder={localize('com_assistants_instructions_placeholder')}
rows={3}
/>
)}
/>
</div>
{/* Model */}
<div className="mb-6">
<label className={labelClass} htmlFor="model">
{localize('com_ui_model')}
</label>
<Controller
name="model"
control={control}
render={({ field }) => (
<SelectDropDown
emptyTitle={true}
value={field.value}
setValue={field.onChange}
availableValues={modelsQuery.data?.[EModelEndpoint.assistants] ?? []}
showAbove={false}
showLabel={false}
className={cn(
cardStyle,
'flex h-[40px] w-full flex-none items-center justify-center px-4 hover:cursor-pointer',
)}
/>
)}
/>
</div>
{/* Knowledge */}
<Knowledge assistant_id={assistant_id} files={files} />
{/* Capabilities */}
<div className="mb-6">
<div className="mb-1.5 flex items-center">
<span>
<label className="text-token-text-primary block font-medium">Capabilities</label>
</span>
</div>
<div className="flex flex-col items-start gap-2">
<div className="flex items-center">
<Controller
name={'code_interpreter'}
control={control}
render={({ field }) => (
<Checkbox
{...field}
checked={field.value}
onCheckedChange={field.onChange}
className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"
value={field?.value?.toString()}
/>
)}
/>
<label
className="form-check-label text-token-text-primary w-full cursor-pointer"
htmlFor="code_interpreter"
onClick={() =>
setValue('code_interpreter', !getValues('code_interpreter'), {
shouldDirty: true,
})
}
>
<div className="flex items-center">
{localize('com_assistants_code_interpreter')}
<QuestionMark />
</div>
</label>
</div>
<div className="flex items-center">
<Controller
name={'retrieval'}
control={control}
render={({ field }) => (
<Checkbox
{...field}
checked={field.value}
disabled={!supportsRetrieval.has(model)}
onCheckedChange={field.onChange}
className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"
value={field?.value?.toString()}
/>
)}
/>
<label
className={cn(
'form-check-label text-token-text-primary w-full',
!supportsRetrieval.has(model) ? 'cursor-no-drop opacity-50' : 'cursor-pointer',
)}
htmlFor="retrieval"
onClick={() =>
supportsRetrieval.has(model) &&
setValue('retrieval', !getValues('retrieval'), { shouldDirty: true })
}
>
{localize('com_assistants_retrieval')}
</label>
</div>
</div>
</div>
{/* Tools */}
<div className="mb-6">
<label className={labelClass}>{localize('com_assistants_tools_section')}</label>
<div className="space-y-1">
{functions.map((func) => (
<AssistantTool
key={func}
tool={func}
allTools={allTools}
assistant_id={assistant_id}
/>
))}
{actions
.filter((action) => action.assistant_id === assistant_id)
.map((action, i) => {
return (
<AssistantAction key={i} action={action} onClick={() => setAction(action)} />
);
})}
<button
type="button"
onClick={() => setShowToolDialog(true)}
className="btn btn-neutral border-token-border-light relative mx-1 mt-2 h-8 rounded-lg font-medium"
>
<div className="flex w-full items-center justify-center gap-2">
{localize('com_assistants_add_tools')}
</div>
</button>
<button
type="button"
disabled={!assistant_id}
onClick={() => {
if (!assistant_id) {
return showToast({
message: localize('com_assistants_actions_disabled'),
status: 'warning',
});
}
setActivePanel(Panel.actions);
}}
className="btn btn-neutral border-token-border-light relative mt-2 h-8 rounded-lg font-medium"
>
<div className="flex w-full items-center justify-center gap-2">
{localize('com_assistants_add_actions')}
</div>
</button>
</div>
</div>
<div className="flex items-center justify-end gap-2">
{/* Context Button */}
<ContextButton
assistant_id={assistant_id}
setCurrentAssistantId={setCurrentAssistantId}
createMutation={create}
/>
{/* Secondary Select Button */}
{assistant_id && (
<button
className="btn btn-secondary"
type="button"
disabled={!assistant_id}
onClick={(e) => {
e.preventDefault();
onSelectAssistant(assistant_id);
}}
>
{localize('com_ui_select')}
</button>
)}
{/* Submit Button */}
<button
className="btn btn-primary focus:shadow-outline flex w-[90px] items-center justify-center px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500"
type="submit"
>
{create.isLoading || update.isLoading ? (
<Spinner className="icon-md" />
) : assistant_id ? (
localize('com_ui_save')
) : (
localize('com_ui_create')
)}
</button>
</div>
</div>
<ToolSelectDialog
isOpen={showToolDialog}
setIsOpen={setShowToolDialog}
assistant_id={assistant_id}
/>
</form>
</FormProvider>
);
}

View file

@ -0,0 +1,190 @@
import { Plus } from 'lucide-react';
import { useCallback, useEffect, useRef } from 'react';
import {
defaultAssistantFormValues,
defaultOrderQuery,
FileSources,
} from 'librechat-data-provider';
import type { UseFormReset } from 'react-hook-form';
import type { UseMutationResult } from '@tanstack/react-query';
import type { Assistant, AssistantCreateParams } from 'librechat-data-provider';
import type { AssistantForm, Actions, TAssistantOption, ExtendedFile } from '~/common';
import SelectDropDown from '~/components/ui/SelectDropDown';
import { useListAssistantsQuery } from '~/data-provider';
import { useFileMapContext } from '~/Providers';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils/';
const keys = new Set(['name', 'id', 'description', 'instructions', 'model']);
export default function AssistantSelect({
reset,
value,
selectedAssistant,
setCurrentAssistantId,
createMutation,
}: {
reset: UseFormReset<AssistantForm>;
value: TAssistantOption;
selectedAssistant: string | null;
setCurrentAssistantId: React.Dispatch<React.SetStateAction<string | undefined>>;
createMutation: UseMutationResult<Assistant, Error, AssistantCreateParams>;
}) {
const localize = useLocalize();
const fileMap = useFileMapContext();
const lastSelectedAssistant = useRef<string | null>(null);
const assistants = useListAssistantsQuery(defaultOrderQuery, {
select: (res) =>
res.data.map((_assistant) => {
const assistant = {
..._assistant,
label: _assistant?.name ?? '',
value: _assistant.id,
files: _assistant?.file_ids ? ([] as Array<[string, ExtendedFile]>) : undefined,
};
if (assistant.files && _assistant.file_ids) {
_assistant.file_ids.forEach((file_id) => {
const file = fileMap?.[file_id];
if (file) {
assistant.files?.push([
file_id,
{
file_id: file.file_id,
type: file.type,
filepath: file.filepath,
filename: file.filename,
width: file.width,
height: file.height,
size: file.bytes,
preview: file.filepath,
progress: 1,
source: FileSources.openai,
},
]);
}
});
}
return assistant;
}),
});
const onSelect = useCallback(
(value: string) => {
const assistant = assistants.data?.find((assistant) => assistant.id === value);
createMutation.reset();
if (!assistant) {
setCurrentAssistantId(undefined);
return reset(defaultAssistantFormValues);
}
const update = {
...assistant,
label: assistant?.name ?? '',
value: assistant?.id ?? '',
};
const actions: Actions = {
code_interpreter: false,
retrieval: false,
};
assistant?.tools
?.filter((tool) => tool.type !== 'function')
?.map((tool) => tool.type)
.forEach((tool) => {
actions[tool] = true;
});
const functions =
assistant?.tools
?.filter((tool) => tool.type === 'function')
?.map((tool) => tool.function?.name ?? '') ?? [];
const formValues: Partial<AssistantForm & Actions> = {
functions,
...actions,
assistant: update,
};
Object.entries(assistant).forEach(([name, value]) => {
if (typeof value === 'number') {
return;
} else if (typeof value === 'object') {
return;
}
if (keys.has(name)) {
formValues[name] = value;
}
});
reset(formValues);
setCurrentAssistantId(assistant?.id);
},
[assistants.data, reset, setCurrentAssistantId, createMutation],
);
useEffect(() => {
let timerId: NodeJS.Timeout | null = null;
if (selectedAssistant === lastSelectedAssistant.current) {
return;
}
if (selectedAssistant && assistants.data) {
timerId = setTimeout(() => {
lastSelectedAssistant.current = selectedAssistant;
onSelect(selectedAssistant);
}, 5);
}
return () => {
if (timerId) {
clearTimeout(timerId);
}
};
}, [selectedAssistant, assistants.data, onSelect]);
const createAssistant = localize('com_ui_create') + ' ' + localize('com_ui_assistant');
return (
<SelectDropDown
value={!value ? createAssistant : value}
setValue={onSelect}
availableValues={
assistants.data ?? [
{
label: 'Loading...',
value: '',
},
]
}
iconSide="left"
showAbove={false}
showLabel={false}
emptyTitle={true}
containerClassName="flex-grow"
optionsClass="hover:bg-gray-20/50 dark:border-gray-700"
optionsListClass="rounded-lg shadow-lg dark:bg-black dark:border-gray-700 dark:last:border"
currentValueClass={cn(
'text-md font-semibold text-gray-900 dark:text-white',
value === '' ? 'text-gray-500' : '',
)}
className={cn(
'mt-1 rounded-md dark:border-gray-700 dark:bg-black',
'z-50 flex h-[40px] w-full flex-none items-center justify-center px-4 hover:cursor-pointer hover:border-green-500 focus:border-green-500',
)}
renderOption={() => (
<span className="flex items-center gap-1.5 truncate">
<span className="absolute inset-y-0 left-0 flex items-center pl-2 text-gray-800 dark:text-gray-100">
<Plus className="w-[16px]" />
</span>
<span className={cn('ml-4 flex h-6 items-center gap-1 text-gray-800 dark:text-gray-100')}>
{createAssistant}
</span>
</span>
)}
/>
);
}

View file

@ -0,0 +1,52 @@
import type { TPlugin } from 'librechat-data-provider';
import GearIcon from '~/components/svg/GearIcon';
import { cn } from '~/utils';
export default function AssistantTool({
tool,
allTools,
assistant_id,
}: {
tool: string;
allTools: TPlugin[];
assistant_id?: string;
}) {
const currentTool = allTools.find((t) => t.pluginKey === tool);
if (!currentTool) {
return null;
}
return (
<div>
<div
className={cn(
'border-token-border-medium flex w-full rounded-lg border text-sm hover:cursor-pointer',
!assistant_id ? 'opacity-40' : '',
)}
>
{currentTool.icon && (
<div className="flex h-9 w-9 items-center justify-center overflow-hidden rounded-full">
<div
className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full bg-center bg-no-repeat dark:bg-white/20"
style={{ backgroundImage: `url(${currentTool.icon})`, backgroundSize: 'cover' }}
/>
</div>
)}
<div
className="h-9 grow px-3 py-2"
style={{ textOverflow: 'ellipsis', wordBreak: 'break-all', overflow: 'hidden' }}
>
{currentTool.name}
</div>
<div className="w-px bg-gray-300 dark:bg-gray-600" />
<button
type="button"
className="flex h-9 w-9 min-w-9 items-center justify-center rounded-lg rounded-l-none"
>
<GearIcon className="icon-sm" />
</button>
</div>
</div>
);
}

View file

@ -0,0 +1,147 @@
import * as Popover from '@radix-ui/react-popover';
import type { Assistant, AssistantCreateParams } from 'librechat-data-provider';
import type { UseMutationResult } from '@tanstack/react-query';
import { Dialog, DialogTrigger, Label } from '~/components/ui';
import DialogTemplate from '~/components/ui/DialogTemplate';
import { useDeleteAssistantMutation } from '~/data-provider';
import { useLocalize, useSetIndexOptions } from '~/hooks';
import { cn, removeFocusOutlines } from '~/utils/';
import { NewTrashIcon } from '~/components/svg';
import { useChatContext } from '~/Providers';
export default function ContextButton({
assistant_id,
setCurrentAssistantId,
createMutation,
}: {
assistant_id: string;
setCurrentAssistantId: React.Dispatch<React.SetStateAction<string | undefined>>;
createMutation: UseMutationResult<Assistant, Error, AssistantCreateParams>;
}) {
const localize = useLocalize();
const { conversation } = useChatContext();
const { setOption } = useSetIndexOptions();
const deleteAssistant = useDeleteAssistantMutation({
onSuccess: (_, vars, context) => {
const updatedList = context as Assistant[] | undefined;
if (!updatedList) {
return;
}
if (createMutation.data?.id) {
console.log('[deleteAssistant] resetting createMutation');
createMutation.reset();
}
const firstAssistant = updatedList[0] as Assistant | undefined;
if (!firstAssistant) {
return setOption('assistant_id')('');
}
if (vars.assistant_id === conversation?.assistant_id) {
return setOption('assistant_id')(firstAssistant.id);
}
const currentAssistant = updatedList?.find(
(assistant) => assistant.id === conversation?.assistant_id,
);
if (currentAssistant) {
setCurrentAssistantId(currentAssistant.id);
}
setCurrentAssistantId(firstAssistant.id);
},
});
if (!assistant_id) {
return null;
}
return (
<Dialog>
<Popover.Root>
<Popover.Trigger asChild>
<button
className={cn(
'btn btn-neutral border-token-border-light relative h-9 rounded-lg font-medium',
removeFocusOutlines,
)}
type="button"
>
<div className="flex w-full items-center justify-center gap-2">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="icon-md"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M3 12C3 10.8954 3.89543 10 5 10C6.10457 10 7 10.8954 7 12C7 13.1046 6.10457 14 5 14C3.89543 14 3 13.1046 3 12ZM10 12C10 10.8954 10.8954 10 12 10C13.1046 10 14 10.8954 14 12C14 13.1046 13.1046 14 12 14C10.8954 14 10 13.1046 10 12ZM17 12C17 10.8954 17.8954 10 19 10C20.1046 10 21 10.8954 21 12C21 13.1046 20.1046 14 19 14C17.8954 14 17 13.1046 17 12Z"
fill="currentColor"
/>
</svg>
</div>
</button>
</Popover.Trigger>
<div
style={{
position: 'fixed',
left: ' 0px',
top: ' 0px',
transform: 'translate(1772.8px, 49.6px)',
minWidth: 'max-content',
zIndex: 'auto',
}}
dir="ltr"
>
<Popover.Content
side="top"
role="menu"
className="bg-token-surface-primary min-w-[180px] max-w-xs rounded-lg border border-gray-100 bg-white shadow-lg dark:border-gray-700 dark:bg-black"
style={{ outline: 'none', pointerEvents: 'auto' }}
sideOffset={8}
tabIndex={-1}
align="end"
>
<DialogTrigger asChild>
<Popover.Close
role="menuitem"
className="group m-1.5 flex w-full cursor-pointer gap-2 rounded p-2.5 text-sm text-red-500 hover:bg-black/5 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 dark:hover:bg-white/5"
tabIndex={-1}
>
<NewTrashIcon />
{localize('com_ui_delete') + ' ' + localize('com_ui_assistant')}
</Popover.Close>
</DialogTrigger>
</Popover.Content>
</div>
<DialogTemplate
title={localize('com_ui_delete') + ' ' + localize('com_ui_assistant')}
className="max-w-[450px]"
main={
<>
<div className="flex w-full flex-col items-center gap-2">
<div className="grid w-full items-center gap-2">
<Label htmlFor="delete-assistant" className="text-left text-sm font-medium">
{localize('com_ui_delete_assistant_confirm')}
</Label>
</div>
</div>
</>
}
selection={{
selectHandler: () => deleteAssistant.mutate({ assistant_id }),
selectClasses: 'bg-red-600 hover:bg-red-700 dark:hover:bg-red-800 text-white',
selectText: localize('com_ui_delete'),
}}
/>
</Popover.Root>
</Dialog>
);
}

View file

@ -0,0 +1,133 @@
import { useRef } from 'react';
import * as Popover from '@radix-ui/react-popover';
export function NoImage() {
return (
<div className="border-token-border-medium flex h-full w-full items-center justify-center rounded-full border-2 border-dashed border-black">
<svg
stroke="currentColor"
fill="none"
strokeWidth="2"
viewBox="0 0 24 24"
strokeLinecap="round"
strokeLinejoin="round"
className="text-4xl"
height="1em"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
</div>
);
}
export const AssistantAvatar = ({
url,
progress = 1,
}: {
url?: string;
progress: number; // between 0 and 1
}) => {
const radius = 55; // Radius of the SVG circle
const circumference = 2 * Math.PI * radius;
// Calculate the offset based on the loading progress
const offset = circumference - progress * circumference;
const circleCSSProperties = {
transition: 'stroke-dashoffset 0.3s linear',
};
return (
<div>
<div className="relative overflow-hidden rounded-full">
<img
src={url}
className="bg-token-surface-secondary dark:bg-token-surface-tertiary h-full w-full"
alt="GPT"
width="80"
height="80"
style={{ opacity: progress < 1 ? 0.4 : 1 }}
/>
{progress < 1 && (
<div className="absolute inset-0 flex items-center justify-center bg-black/5 text-white">
<svg width="120" height="120" viewBox="0 0 120 120" className="h-6 w-6">
<circle
className="origin-[50%_50%] -rotate-90 stroke-gray-400"
strokeWidth="10"
fill="transparent"
r="55"
cx="60"
cy="60"
/>
<circle
className="origin-[50%_50%] -rotate-90 transition-[stroke-dashoffset]"
stroke="currentColor"
strokeWidth="10"
strokeDasharray={`${circumference} ${circumference}`}
strokeDashoffset={offset}
fill="transparent"
r="55"
cx="60"
cy="60"
style={circleCSSProperties}
/>
</svg>
</div>
)}
</div>
</div>
);
};
export function AvatarMenu({
handleFileChange,
}: {
handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}) {
const fileInputRef = useRef<HTMLInputElement>(null);
const onItemClick = () => {
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
fileInputRef.current?.click();
};
return (
<Popover.Portal>
<Popover.Content
className="flex min-w-[100px] max-w-xs flex-col rounded-xl border border-gray-400 bg-white shadow-lg dark:border-gray-700 dark:bg-black dark:text-white"
sideOffset={5}
>
<div
role="menuitem"
className="group m-1.5 flex cursor-pointer gap-2 rounded p-2.5 text-sm hover:bg-black/5 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 dark:hover:bg-white/5"
tabIndex={-1}
data-orientation="vertical"
onClick={onItemClick}
>
Upload Photo
</div>
{/* <Popover.Close
role="menuitem"
className="group m-1.5 flex cursor-pointer gap-2 rounded p-2.5 text-sm hover:bg-black/5 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 dark:hover:bg-white/5"
tabIndex={-1}
data-orientation="vertical"
>
Use DALL·E
</Popover.Close> */}
<input
accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp"
multiple={false}
type="file"
style={{ display: 'none' }}
onChange={handleFileChange}
ref={fileInputRef}
tabIndex={-1}
/>
</Popover.Content>
</Popover.Portal>
);
}

View file

@ -0,0 +1,128 @@
import { useState, useRef, useEffect } from 'react';
import {
EModelEndpoint,
retrievalMimeTypes,
fileConfig as defaultFileConfig,
mergeFileConfig,
} from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
import FileRow from '~/components/Chat/Input/Files/FileRow';
import { useGetFileConfig } from '~/data-provider';
import { useFileHandling } from '~/hooks/Files';
import useLocalize from '~/hooks/useLocalize';
import { useChatContext } from '~/Providers';
const CodeInterpreterFiles = ({ children }: { children: React.ReactNode }) => {
const localize = useLocalize();
return (
<div>
<div className="text-token-text-tertiary mb-2 text-xs">
{localize('com_assistants_code_interpreter_files')}
</div>
{/* Files available to Code Interpreter only */}
<div className="flex flex-wrap gap-2">{children}</div>
</div>
);
};
export default function Knowledge({
assistant_id,
files: _files,
}: {
assistant_id: string;
files?: [string, ExtendedFile][];
}) {
const localize = useLocalize();
const { setFilesLoading } = useChatContext();
const fileInputRef = useRef<HTMLInputElement>(null);
const [files, setFiles] = useState<Map<string, ExtendedFile>>(new Map());
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
select: (data) => mergeFileConfig(data),
});
const { handleFileChange } = useFileHandling({
overrideEndpoint: EModelEndpoint.assistants,
additionalMetadata: { assistant_id },
fileSetter: setFiles,
});
useEffect(() => {
if (_files) {
setFiles(new Map(_files));
}
}, [_files]);
const endpointFileConfig = fileConfig.endpoints[EModelEndpoint.assistants];
if (endpointFileConfig?.disabled) {
return null;
}
const handleButtonClick = () => {
// necessary to reset the input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
fileInputRef.current?.click();
};
return (
<div className="mb-6">
<div className="mb-1.5 flex items-center">
<span>
<label className="text-token-text-primary block font-medium">
{assistant_id
? localize('com_assistants_knowledge')
: localize('com_assistants_knowledge_disabled')}
</label>
</span>
</div>
<div className="flex flex-col gap-4">
<div className="text-token-text-tertiary rounded-lg">
{assistant_id ? localize('com_assistants_knowledge_info') : ''}
</div>
{/* Files available to both tools */}
<FileRow
files={files}
setFiles={setFiles}
setFilesLoading={setFilesLoading}
assistant_id={assistant_id}
fileFilter={(file: ExtendedFile) =>
retrievalMimeTypes.some((regex) => regex.test(file.type ?? ''))
}
Wrapper={({ children }) => <div className="flex flex-wrap gap-2">{children}</div>}
/>
<FileRow
files={files}
setFiles={setFiles}
setFilesLoading={setFilesLoading}
assistant_id={assistant_id}
fileFilter={(file: ExtendedFile) =>
!retrievalMimeTypes.some((regex) => regex.test(file.type ?? ''))
}
Wrapper={CodeInterpreterFiles}
/>
<div>
<button
type="button"
disabled={!assistant_id}
className="btn btn-neutral border-token-border-light relative h-8 rounded-lg font-medium"
onClick={handleButtonClick}
>
<div className="flex w-full items-center justify-center gap-2">
<input
multiple={true}
type="file"
style={{ display: 'none' }}
tabIndex={-1}
ref={fileInputRef}
disabled={!assistant_id}
onChange={handleFileChange}
/>
{localize('com_ui_upload_files')}
</div>
</button>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,51 @@
import { useState, useEffect } from 'react';
import type { Action } from 'librechat-data-provider';
import { useGetActionsQuery } from '~/data-provider';
import AssistantPanel from './AssistantPanel';
import { useChatContext } from '~/Providers';
import ActionsPanel from './ActionsPanel';
import { Panel } from '~/common';
export default function PanelSwitch() {
const { conversation, index } = useChatContext();
const [activePanel, setActivePanel] = useState(Panel.builder);
const [currentAssistantId, setCurrentAssistantId] = useState<string | undefined>(
conversation?.assistant_id,
);
const [action, setAction] = useState<Action | undefined>(undefined);
const { data: actions = [] } = useGetActionsQuery();
useEffect(() => {
if (conversation?.assistant_id) {
setCurrentAssistantId(conversation?.assistant_id);
}
}, [conversation?.assistant_id]);
if (activePanel === Panel.actions || action) {
return (
<ActionsPanel
index={index}
action={action}
actions={actions}
setAction={setAction}
activePanel={activePanel}
setActivePanel={setActivePanel}
assistant_id={currentAssistantId}
setCurrentAssistantId={setCurrentAssistantId}
/>
);
} else if (activePanel === Panel.builder) {
return (
<AssistantPanel
index={index}
activePanel={activePanel}
action={action}
actions={actions}
setAction={setAction}
setActivePanel={setActivePanel}
assistant_id={currentAssistantId}
setCurrentAssistantId={setCurrentAssistantId}
/>
);
}
}

View file

@ -0,0 +1,14 @@
import type { TFile } from 'librechat-data-provider';
import { useGetFiles } from '~/data-provider';
import { columns } from './PanelColumns';
import DataTable from './PanelTable';
export default function FilesPanel() {
const { data: files = [] } = useGetFiles<TFile[]>();
return (
<div className="h-auto max-w-full overflow-x-hidden">
<DataTable columns={columns} data={files} />
</div>
);
}

View file

@ -0,0 +1,47 @@
import { ArrowUpDown } from 'lucide-react';
import type { ColumnDef } from '@tanstack/react-table';
import type { TFile } from 'librechat-data-provider';
import PanelFileCell from './PanelFileCell';
import { Button } from '~/components/ui';
import { formatDate } from '~/utils';
export const columns: ColumnDef<TFile>[] = [
{
accessorKey: 'filename',
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
>
Name
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
meta: {
size: '150px',
},
cell: ({ row }) => <PanelFileCell row={row} />,
},
{
accessorKey: 'updatedAt',
meta: {
size: '10%',
},
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
>
Date
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => (
<span className="flex justify-end text-xs">{formatDate(row.original.updatedAt)}</span>
),
},
];

View file

@ -0,0 +1,101 @@
import { useCallback } from 'react';
import {
fileConfig as defaultFileConfig,
mergeFileConfig,
megabyte,
} from 'librechat-data-provider';
import type { Row } from '@tanstack/react-table';
import type { TFile } from 'librechat-data-provider';
import { useFileMapContext, useChatContext, useToastContext } from '~/Providers';
import ImagePreview from '~/components/Chat/Input/Files/ImagePreview';
import FilePreview from '~/components/Chat/Input/Files/FilePreview';
import { useUpdateFiles, useLocalize } from '~/hooks';
import { useGetFileConfig } from '~/data-provider';
import { getFileType } from '~/utils';
export default function PanelFileCell({ row }: { row: Row<TFile> }) {
const localize = useLocalize();
const fileMap = useFileMapContext();
const { showToast } = useToastContext();
const { setFiles, conversation } = useChatContext();
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
select: (data) => mergeFileConfig(data),
});
const { addFile } = useUpdateFiles(setFiles);
const handleFileClick = useCallback(() => {
const file = row.original;
const endpoint = conversation?.endpoint;
const fileData = fileMap?.[file.file_id];
if (!fileData) {
return;
}
if (!endpoint) {
return showToast({ message: localize('com_ui_attach_error'), status: 'error' });
}
const { fileSizeLimit, supportedMimeTypes } =
fileConfig.endpoints[endpoint] ?? fileConfig.endpoints.default;
if (fileData.bytes > fileSizeLimit) {
return showToast({
message: `${localize('com_ui_attach_error_size')} ${
fileSizeLimit / megabyte
} MB (${endpoint})`,
status: 'error',
});
}
const isSupportedMimeType = defaultFileConfig.checkType(file.type, supportedMimeTypes);
if (!isSupportedMimeType) {
return showToast({
message: `${localize('com_ui_attach_error_type')} ${file.type} (${endpoint})`,
status: 'error',
});
}
addFile({
progress: 1,
attached: true,
file_id: fileData.file_id,
filepath: fileData.filepath,
preview: fileData.filepath,
type: fileData.type,
height: fileData.height,
width: fileData.width,
filename: fileData.filename,
source: fileData.source,
size: fileData.bytes,
});
}, [addFile, fileMap, row.original, conversation, localize, showToast, fileConfig.endpoints]);
const file = row.original;
if (file.type?.startsWith('image')) {
return (
<div
onClick={handleFileClick}
className="flex cursor-pointer gap-2 rounded-md dark:hover:bg-gray-900"
>
<ImagePreview
url={file.filepath}
className="h-10 w-10 shrink-0 overflow-hidden rounded-md"
/>
<span className="self-center truncate text-xs">{file.filename}</span>
</div>
);
}
const fileType = getFileType(file.type);
return (
<div
onClick={handleFileClick}
className="flex cursor-pointer gap-2 rounded-md dark:hover:bg-gray-900"
>
{fileType && <FilePreview fileType={fileType} />}
<span className="self-center truncate">{file.filename}</span>
</div>
);
}

View file

@ -0,0 +1,165 @@
import { useState } from 'react';
import { useSetRecoilState } from 'recoil';
import { LucideArrowUpLeft } from 'lucide-react';
import {
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from '@tanstack/react-table';
import type {
ColumnDef,
SortingState,
VisibilityState,
ColumnFiltersState,
} from '@tanstack/react-table';
import type { AugmentedColumnDef } from '~/common';
import {
Button,
Input,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '~/components/ui';
import store from '~/store';
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
}
export default function DataTable<TData, TValue>({ columns, data }: DataTableProps<TData, TValue>) {
const [rowSelection, setRowSelection] = useState({});
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [paginationState, setPagination] = useState({ pageIndex: 0, pageSize: 10 });
const setShowFiles = useSetRecoilState(store.showFiles);
const table = useReactTable({
data,
columns,
onSortingChange: setSorting,
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
getPaginationRowModel: getPaginationRowModel(),
onRowSelectionChange: setRowSelection,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
pagination: paginationState,
},
defaultColumn: {
minSize: 0,
size: 10,
maxSize: 10,
enableResizing: true,
},
});
return (
<>
<div className="flex items-center gap-4 px-2 py-4">
<Input
placeholder="Filter files..."
value={(table.getColumn('filename')?.getFilterValue() as string) ?? ''}
onChange={(event) => table.getColumn('filename')?.setFilterValue(event.target.value)}
className="max-w-xs dark:border-gray-700"
/>
</div>
<div className="overflow-y-auto rounded-md border border-black/10 dark:border-white/10 ">
<Table className="border-separate border-spacing-0 ">
<TableHeader>
{table.getHeaderGroups().map((headerGroup, index) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead
key={header.id}
style={{ width: index === 0 ? '75%' : '25%' }}
className="sticky top-0 h-auto border-b border-black/10 bg-white py-1 text-left font-medium text-gray-700 dark:border-white/10 dark:bg-black dark:text-gray-100"
>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && 'selected'}
className="border-b border-black/10 text-left text-gray-600 dark:border-white/10 dark:text-gray-300 [tr:last-child_&]:border-b-0"
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="p-2 px-4 [tr[data-disabled=true]_&]:opacity-50"
style={{
maxWidth: (cell.column.columnDef as AugmentedColumnDef<TData, TValue>).meta
.size,
}}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-around space-x-2 py-4">
<Button
variant="outline"
size="sm"
onClick={() => setShowFiles(true)}
className="flex gap-2"
>
<LucideArrowUpLeft className="icon-sm" />
Manage Files
</Button>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Next
</Button>
</div>
</div>
</>
);
}

View file

@ -0,0 +1,113 @@
import { useState } from 'react';
import * as AccordionPrimitive from '@radix-ui/react-accordion';
import type { NavLink, NavProps } from '~/common';
import { Accordion, AccordionItem, AccordionContent } from '~/components/ui/Accordion';
import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/Tooltip';
import { buttonVariants } from '~/components/ui/Button';
import { cn, removeFocusOutlines } from '~/utils';
import { useLocalize } from '~/hooks';
export default function Nav({ links, isCollapsed, resize, defaultActive }: NavProps) {
const localize = useLocalize();
const [active, _setActive] = useState<string | undefined>(defaultActive);
const getVariant = (link: NavLink) => (link.id === active ? 'default' : 'ghost');
const setActive = (id: string) => {
localStorage.setItem('side:active-panel', id + '');
_setActive(id);
};
return (
<div
data-collapsed={isCollapsed}
className="bg-token-sidebar-surface-primary group flex-shrink-0 overflow-x-hidden py-2 data-[collapsed=true]:py-2"
>
<div className="h-full">
<div className="flex h-full min-h-0 flex-col">
<div className="flex h-full min-h-0 flex-col opacity-100 transition-opacity">
<div className="scrollbar-trigger relative h-full w-full flex-1 items-start border-white/20">
<nav className="flex h-full w-full flex-col gap-1 px-2 px-3 pb-3.5 group-[[data-collapsed=true]]:justify-center group-[[data-collapsed=true]]:px-2">
{links.map((link, index) => {
const variant = getVariant(link);
return isCollapsed ? (
<Tooltip key={index} delayDuration={0}>
<TooltipTrigger asChild>
<button
className={cn(
buttonVariants({ variant, size: 'icon' }),
removeFocusOutlines,
'h-9 w-9',
variant === 'default'
? 'dark:bg-muted dark:text-muted-foreground dark:hover:bg-muted dark:hover:text-white'
: '',
)}
onClick={() => {
setActive(link.id);
resize && resize(25);
}}
>
<link.icon className="h-4 w-4" />
<span className="sr-only">{link.title}</span>
</button>
</TooltipTrigger>
<TooltipContent side="right" className="flex items-center gap-4">
{localize(link.title)}
{link.label && (
<span className="text-muted-foreground ml-auto">{link.label}</span>
)}
</TooltipContent>
</Tooltip>
) : (
<Accordion
key={index}
type="single"
value={active}
onValueChange={setActive}
collapsible
>
<AccordionItem value={link.id} className="w-full border-none">
<AccordionPrimitive.Header asChild>
<AccordionPrimitive.Trigger asChild>
<button
className={cn(
buttonVariants({ variant, size: 'sm' }),
removeFocusOutlines,
variant === 'default'
? 'dark:bg-muted dark:hover:bg-muted dark:text-white dark:hover:text-white'
: '',
'data-[state=open]:bg-gray-900 data-[state=open]:text-white dark:data-[state=open]:bg-gray-800',
'w-full justify-start rounded-md border dark:border-gray-600',
)}
>
<link.icon className="mr-2 h-4 w-4" />
{localize(link.title)}
{link.label && (
<span
className={cn(
'ml-auto transition-all duration-300 ease-in-out',
variant === 'default' ? 'text-background dark:text-white' : '',
isCollapsed ? 'opacity-0' : 'opacity-100',
)}
>
{link.label}
</span>
)}
</button>
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
<AccordionContent className="w-full dark:text-white">
{link.Component && <link.Component />}
</AccordionContent>
</AccordionItem>
</Accordion>
);
})}
</nav>
</div>
</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,214 @@
import throttle from 'lodash/throttle';
import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
import { useGetEndpointsQuery, useUserKeyQuery } from 'librechat-data-provider/react-query';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { EModelEndpoint, type TEndpointsConfig } from 'librechat-data-provider';
import type { NavLink } from '~/common';
import { ResizableHandleAlt, ResizablePanel, ResizablePanelGroup } from '~/components/ui/Resizable';
import { TooltipProvider, Tooltip } from '~/components/ui/Tooltip';
import { Blocks, AttachmentIcon } from '~/components/svg';
import { useMediaQuery, useLocalStorage } from '~/hooks';
import { Separator } from '~/components/ui/Separator';
import NavToggle from '~/components/Nav/NavToggle';
import PanelSwitch from './Builder/PanelSwitch';
import FilesPanel from './Files/Panel';
import Switcher from './Switcher';
import { cn } from '~/utils';
import Nav from './Nav';
interface SidePanelProps {
defaultLayout?: number[] | undefined;
defaultCollapsed?: boolean;
navCollapsedSize?: number;
children: React.ReactNode;
}
const defaultMinSize = 20;
export default function SidePanel({
defaultLayout = [97, 3],
defaultCollapsed = false,
navCollapsedSize = 3,
children,
}: SidePanelProps) {
const [minSize, setMinSize] = useState(defaultMinSize);
const [isHovering, setIsHovering] = useState(false);
const [newUser, setNewUser] = useLocalStorage('newUser', true);
const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
const [collapsedSize, setCollapsedSize] = useState(navCollapsedSize);
const { data: endpointsConfig = {} as TEndpointsConfig } = useGetEndpointsQuery();
const { data: keyExpiry = { expiresAt: undefined } } = useUserKeyQuery(EModelEndpoint.assistants);
const isSmallScreen = useMediaQuery('(max-width: 767px)');
const panelRef = useRef<ImperativePanelHandle>(null);
const activePanel = localStorage.getItem('side:active-panel');
const defaultActive = activePanel ? activePanel : undefined;
const Links = useMemo(() => {
const links: NavLink[] = [];
const assistants = endpointsConfig?.[EModelEndpoint.assistants];
const userProvidesKey = !!assistants?.userProvide;
const keyProvided = userProvidesKey ? !!keyExpiry?.expiresAt : true;
if (assistants && assistants.disableBuilder !== true && keyProvided) {
links.push({
title: 'com_sidepanel_assistant_builder',
label: '',
icon: Blocks,
id: 'assistants',
Component: PanelSwitch,
});
}
links.push({
title: 'com_sidepanel_attach_files',
label: '',
icon: AttachmentIcon,
id: 'files',
Component: FilesPanel,
});
return links;
}, [endpointsConfig, keyExpiry?.expiresAt]);
// eslint-disable-next-line react-hooks/exhaustive-deps
const throttledSaveLayout = useCallback(
throttle((sizes: number[]) => {
localStorage.setItem('react-resizable-panels:layout', JSON.stringify(sizes));
}, 350),
[],
);
useEffect(() => {
if (isSmallScreen) {
setIsCollapsed(true);
setMinSize(0);
setCollapsedSize(0);
panelRef.current?.collapse();
return;
}
}, [isSmallScreen]);
const toggleNavVisible = () => {
if (newUser) {
setNewUser(false);
}
setIsCollapsed((prev: boolean) => {
if (!prev) {
setMinSize(0);
setCollapsedSize(0);
} else {
setMinSize(defaultMinSize);
setCollapsedSize(3);
}
return !prev;
});
if (!isCollapsed) {
panelRef.current?.collapse();
} else {
panelRef.current?.expand();
}
};
const assistants = endpointsConfig?.[EModelEndpoint.assistants];
const userProvidesKey = !!assistants?.userProvide;
const keyProvided = userProvidesKey ? !!keyExpiry?.expiresAt : true;
return (
<>
<TooltipProvider delayDuration={0}>
<ResizablePanelGroup
direction="horizontal"
onLayout={(sizes: number[]) => throttledSaveLayout(sizes)}
className="transition-width relative h-full w-full flex-1 overflow-auto bg-white dark:bg-gray-800"
>
<ResizablePanel defaultSize={defaultLayout[0]} minSize={30}>
{children}
</ResizablePanel>
<TooltipProvider delayDuration={400}>
<Tooltip>
<div
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
className="relative flex w-px items-center justify-center"
>
<NavToggle
navVisible={!isCollapsed}
isHovering={isHovering}
onToggle={toggleNavVisible}
setIsHovering={setIsHovering}
className={cn(
'fixed top-1/2',
isCollapsed && (minSize === 0 || collapsedSize === 0) ? 'mr-9' : 'mr-16',
)}
translateX={false}
side="right"
/>
</div>
</Tooltip>
</TooltipProvider>
{(!isCollapsed || minSize > 0) && (
<ResizableHandleAlt withHandle className="bg-transparent dark:text-white" />
)}
<ResizablePanel
collapsedSize={collapsedSize}
defaultSize={defaultLayout[1]}
collapsible={true}
minSize={minSize}
maxSize={40}
ref={panelRef}
style={{
overflowY: 'auto',
visibility:
isCollapsed && (minSize === 0 || collapsedSize === 0) ? 'hidden' : 'visible',
transition: 'width 0.2s ease',
}}
onExpand={() => {
setIsCollapsed(false);
localStorage.setItem('react-resizable-panels:collapsed', 'false');
}}
onCollapse={() => {
setIsCollapsed(true);
localStorage.setItem('react-resizable-panels:collapsed', 'true');
}}
className={cn(
'sidenav border-l border-gray-200 bg-white dark:border-gray-800/50 dark:bg-black',
isCollapsed ? 'min-w-[50px]' : 'min-w-[340px] sm:min-w-[352px]',
minSize === 0 ? 'min-w-0' : '',
)}
>
{keyProvided && (
<div
className={cn(
'sticky left-0 right-0 top-0 z-[100] flex h-[52px] flex-wrap items-center justify-center bg-white dark:bg-black',
isCollapsed ? 'h-[52px]' : 'px-2',
)}
>
<Switcher isCollapsed={isCollapsed} />
<Separator className="bg-gray-100/50" />
</div>
)}
<Nav
resize={panelRef.current?.resize}
isCollapsed={isCollapsed}
defaultActive={defaultActive}
links={Links}
/>
</ResizablePanel>
</ResizablePanelGroup>
</TooltipProvider>
<div
className={`nav-mask${!isCollapsed ? ' active' : ''}`}
onClick={() => {
setIsCollapsed(() => {
setCollapsedSize(0);
setMinSize(0);
return false;
});
panelRef.current?.collapse();
}}
/>
</>
);
}

View file

@ -0,0 +1,100 @@
import { useEffect } from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '~/components/ui/Select';
import { EModelEndpoint, defaultOrderQuery } from 'librechat-data-provider';
import { useSetIndexOptions, useSelectAssistant, useLocalize } from '~/hooks';
import { useChatContext, useAssistantsMapContext } from '~/Providers';
import { useListAssistantsQuery } from '~/data-provider';
import Icon from '~/components/Endpoints/Icon';
import { cn } from '~/utils';
interface SwitcherProps {
isCollapsed: boolean;
}
export default function Switcher({ isCollapsed }: SwitcherProps) {
const localize = useLocalize();
const { setOption } = useSetIndexOptions();
const { index, conversation } = useChatContext();
/* `selectedAssistant` must be defined with `null` to cause re-render on update */
const { assistant_id: selectedAssistant = null, endpoint } = conversation ?? {};
const { data: assistants = [] } = useListAssistantsQuery(defaultOrderQuery, {
select: (res) => res.data.map(({ id, name, metadata }) => ({ id, name, metadata })),
});
const assistantMap = useAssistantsMapContext();
const { onSelect } = useSelectAssistant();
useEffect(() => {
if (!selectedAssistant && assistants && assistants.length && assistantMap) {
const assistant_id =
localStorage.getItem(`assistant_id__${index}`) ?? assistants[0]?.id ?? '';
const assistant = assistantMap?.[assistant_id];
if (!assistant) {
return;
}
if (endpoint !== EModelEndpoint.assistants) {
return;
}
setOption('model')(assistant.model);
setOption('assistant_id')(assistant_id);
}
}, [index, assistants, selectedAssistant, assistantMap, endpoint, setOption]);
const currentAssistant = assistantMap?.[selectedAssistant ?? ''];
return (
<Select defaultValue={selectedAssistant as string | undefined} onValueChange={onSelect}>
<SelectTrigger
className={cn(
'flex items-center gap-2 [&>span]:line-clamp-1 [&>span]:flex [&>span]:w-full [&>span]:items-center [&>span]:gap-1 [&>span]:truncate [&_svg]:h-4 [&_svg]:w-4 [&_svg]:shrink-0',
isCollapsed
? 'flex h-9 w-9 shrink-0 items-center justify-center p-0 [&>span]:w-auto [&>svg]:hidden'
: '',
'bg-white',
)}
aria-label={localize('com_sidepanel_select_assistant')}
>
<SelectValue placeholder={localize('com_sidepanel_select_assistant')}>
<div className="assistant-item flex items-center justify-center overflow-hidden rounded-full">
<Icon
isCreatedByUser={false}
endpoint={EModelEndpoint.assistants}
assistantName={currentAssistant?.name ?? ''}
iconURL={(currentAssistant?.metadata?.avatar as string) ?? ''}
/>
</div>
<span className={cn('ml-2', isCollapsed ? 'hidden' : '')}>
{assistants.find((assistant) => assistant.id === selectedAssistant)?.name ??
localize('com_sidepanel_select_assistant')}
</span>
</SelectValue>
</SelectTrigger>
<SelectContent className="bg-white">
{assistants.map((assistant) => (
<SelectItem key={assistant.id} value={assistant.id}>
<div className="[&_svg]:text-foreground flex items-center justify-center gap-3 [&_svg]:h-4 [&_svg]:w-4 [&_svg]:shrink-0 ">
<div className="assistant-item overflow-hidden rounded-full ">
<Icon
isCreatedByUser={false}
endpoint={EModelEndpoint.assistants}
assistantName={assistant.name ?? ''}
iconURL={(assistant.metadata?.avatar as string) ?? ''}
/>
</div>
{assistant.name}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
);
}

View file

@ -0,0 +1,38 @@
export const accounts = [
{
label: 'Alicia Koch',
email: 'alicia@example.com',
icon: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>Vercel</title>
<path d="M24 22.525H0l12-21.05 12 21.05z" fill="currentColor" />
</svg>
),
},
{
label: 'Alicia Koch',
email: 'alicia@gmail.com',
icon: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>Gmail</title>
<path
d="M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z"
fill="currentColor"
/>
</svg>
),
},
{
label: 'Alicia Koch',
email: 'alicia@me.com',
icon: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>iCloud</title>
<path
d="M13.762 4.29a6.51 6.51 0 0 0-5.669 3.332 3.571 3.571 0 0 0-1.558-.36 3.571 3.571 0 0 0-3.516 3A4.918 4.918 0 0 0 0 14.796a4.918 4.918 0 0 0 4.92 4.914 4.93 4.93 0 0 0 .617-.045h14.42c2.305-.272 4.041-2.258 4.043-4.589v-.009a4.594 4.594 0 0 0-3.727-4.508 6.51 6.51 0 0 0-6.511-6.27z"
fill="currentColor"
/>
</svg>
),
},
];

View file

@ -0,0 +1,2 @@
export { default as SidePanel } from './SidePanel';
export { default as SideNav } from './Nav';