LibreChat/client/src/components/SidePanel/Agents/AgentConfig.tsx
Danny Avila 55f5f2d11a
🗓️ feat: Add Special Variables for Prompts & Agents, Prompt UI Improvements (#7123)
* wip: Add Instructions component for agent configuration

*  feat: Implement DropdownPopup for variable insertion in instructions

* refactor: Enhance variable handling by exporting specialVariables and updating Markdown components

* feat: Add special variable support for current date and user in Instructions component

* refactor: Update handleAddVariable to include localized label

* feat: replace special variables in instructions presets

* chore: update parameter type for user in getListAgents function

* refactor: integrate dayjs for date handling and move replaceSpecialVars function to data-provider

* feat: enhance replaceSpecialVars to include day number in current date format

* feat: integrate replaceSpecialVars for processing agent instructions

* feat: add support for current date & time in replaceSpecialVars function

* feat: add iso_datetime support in replaceSpecialVars function

* fix: enforce text parameter to be a required field in replaceSpecialVars function

* feat: add ISO datetime support in translation file

* fix: disable eslint warning for autoFocus in TextareaAutosize component

* feat: add VariablesDropdown component and integrate it into CreatePromptForm and PromptEditor; update translation for special variables

* fix: CategorySelector and related localizations

* fix: add z-index class to LanguageSTTDropdown for proper stacking context

* fix: add max-height and overflow styles to OGDialogContent in VariableDialog and PreviewPrompt components

* fix: update variable detection logic to exclude special variables and improve regex matching

* fix: improve accessibility text for actions menu in ChatGroupItem component

* fix: adjust max-width and height styles for dialog components and improve markdown rendering for light vs. dark, height/widths, etc.

* fix: remove commented-out code for better readability in PromptVariableGfm component

* fix: handle undefined input parameter in setParams function call

* fix: update variable label types to use TSpecialVarLabel for consistency

* fix: remove outdated information from special variables description in translation file

* fix: enhance unused i18next keys detection for special variable keys

* fix: update color classes for consistency/a11y in category and prompt variable components

* fix: update PromptVariableGfm component and special variable styles for consistency

* fix: improve variable highlighting logic in VariableForm component

* fix: update background color classes for consistency in VariableForm component

* fix: add missing ref parameter to Dialog component in OriginalDialog

* refactor: move navigate call for new conversation to after setConversation update

* refactor: move message query hook to client workspace; fix: handle edge case for navigation from finalHandler creating race condition for response message DB save

* chore: bump librechat-data-provider to 0.7.793

* ci: add unit tests for replaceSpecialVars function

* fix: implement getToolkitKey function for image_gen_oai toolkit filtering/including

* ci: enhance dayjs mock for consistent date/time values in tests

* fix: MCP stdio server fail to start when passing env property

* fix: use optional chaining for clientRef dereferencing in AskController and EditController
feat: add context to saveMessage call in streamResponse utility

* fix: only save error messages if the userMessageId was initialized

* refactor: add isNotAppendable check to disable inputs in ChatForm and useTextarea

* feat: enhance error handling in useEventHandlers and update conversation state in useNewConvo

* refactor: prepend underscore to conversationId in newConversation template

* feat: log aborted conversations with minimal messages and use consistent conversationId generation

---------

Co-authored-by: Olivier Schiavo <olivier.schiavo@wengo.com>
Co-authored-by: aka012 <aka012@neowiz.com>
Co-authored-by: jiasheng <jiashengguo@outlook.com>
2025-04-29 03:49:02 -04:00

341 lines
11 KiB
TypeScript

import React, { useState, useMemo, useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Controller, useWatch, useFormContext } from 'react-hook-form';
import { QueryKeys, EModelEndpoint, AgentCapabilities } from 'librechat-data-provider';
import type { TPlugin } from 'librechat-data-provider';
import type { AgentForm, AgentPanelProps, IconComponentTypes } from '~/common';
import { cn, defaultTextProps, removeFocusOutlines, getEndpointField, getIconKey } from '~/utils';
import { useToastContext, useFileMapContext } from '~/Providers';
import Action from '~/components/SidePanel/Builder/Action';
import { ToolSelectDialog } from '~/components/Tools';
import { icons } from '~/hooks/Endpoint/Icons';
import { processAgentOption } from '~/utils';
import Instructions from './Instructions';
import AgentAvatar from './AgentAvatar';
import FileContext from './FileContext';
import { useLocalize } from '~/hooks';
import FileSearch from './FileSearch';
import Artifacts from './Artifacts';
import AgentTool from './AgentTool';
import CodeForm from './Code/Form';
import { Panel } from '~/common';
const labelClass = 'mb-2 text-token-text-primary block font-medium';
const inputClass = cn(
defaultTextProps,
'flex w-full px-3 py-2 border-border-light bg-surface-secondary focus-visible:ring-2 focus-visible:ring-ring-primary',
removeFocusOutlines,
);
export default function AgentConfig({
setAction,
actions = [],
agentsConfig,
createMutation,
setActivePanel,
endpointsConfig,
}: AgentPanelProps) {
const fileMap = useFileMapContext();
const queryClient = useQueryClient();
const allTools = queryClient.getQueryData<TPlugin[]>([QueryKeys.tools]) ?? [];
const { showToast } = useToastContext();
const localize = useLocalize();
const [showToolDialog, setShowToolDialog] = useState(false);
const methods = useFormContext<AgentForm>();
const { control } = methods;
const provider = useWatch({ control, name: 'provider' });
const model = useWatch({ control, name: 'model' });
const agent = useWatch({ control, name: 'agent' });
const tools = useWatch({ control, name: 'tools' });
const agent_id = useWatch({ control, name: 'id' });
const toolsEnabled = useMemo(
() => agentsConfig?.capabilities?.includes(AgentCapabilities.tools) ?? false,
[agentsConfig],
);
const actionsEnabled = useMemo(
() => agentsConfig?.capabilities?.includes(AgentCapabilities.actions) ?? false,
[agentsConfig],
);
const artifactsEnabled = useMemo(
() => agentsConfig?.capabilities?.includes(AgentCapabilities.artifacts) ?? false,
[agentsConfig],
);
const ocrEnabled = useMemo(
() => agentsConfig?.capabilities?.includes(AgentCapabilities.ocr) ?? false,
[agentsConfig],
);
const fileSearchEnabled = useMemo(
() => agentsConfig?.capabilities?.includes(AgentCapabilities.file_search) ?? false,
[agentsConfig],
);
const codeEnabled = useMemo(
() => agentsConfig?.capabilities?.includes(AgentCapabilities.execute_code) ?? false,
[agentsConfig],
);
const context_files = useMemo(() => {
if (typeof agent === 'string') {
return [];
}
if (agent?.id !== agent_id) {
return [];
}
if (agent.context_files) {
return agent.context_files;
}
const _agent = processAgentOption({
agent,
fileMap,
});
return _agent.context_files ?? [];
}, [agent, agent_id, fileMap]);
const knowledge_files = useMemo(() => {
if (typeof agent === 'string') {
return [];
}
if (agent?.id !== agent_id) {
return [];
}
if (agent.knowledge_files) {
return agent.knowledge_files;
}
const _agent = processAgentOption({
agent,
fileMap,
});
return _agent.knowledge_files ?? [];
}, [agent, agent_id, fileMap]);
const code_files = useMemo(() => {
if (typeof agent === 'string') {
return [];
}
if (agent?.id !== agent_id) {
return [];
}
if (agent.code_files) {
return agent.code_files;
}
const _agent = processAgentOption({
agent,
fileMap,
});
return _agent.code_files ?? [];
}, [agent, agent_id, fileMap]);
const handleAddActions = useCallback(() => {
if (!agent_id) {
showToast({
message: localize('com_assistants_actions_disabled'),
status: 'warning',
});
return;
}
setActivePanel(Panel.actions);
}, [agent_id, setActivePanel, showToast, localize]);
const providerValue = typeof provider === 'string' ? provider : provider?.value;
let Icon: IconComponentTypes | null | undefined;
let endpointType: EModelEndpoint | undefined;
let endpointIconURL: string | undefined;
let iconKey: string | undefined;
if (providerValue !== undefined) {
endpointType = getEndpointField(endpointsConfig, providerValue as string, 'type');
endpointIconURL = getEndpointField(endpointsConfig, providerValue as string, 'iconURL');
iconKey = getIconKey({
endpoint: providerValue as string,
endpointsConfig,
endpointType,
endpointIconURL,
});
Icon = icons[iconKey];
}
return (
<>
<div className="h-auto bg-white px-4 pt-3 dark:bg-transparent">
{/* Avatar & Name */}
<div className="mb-4">
<AgentAvatar
agent_id={agent_id}
createMutation={createMutation}
avatar={agent?.['avatar'] ?? null}
/>
<label className={labelClass} htmlFor="name">
{localize('com_ui_name')}
</label>
<Controller
name="name"
control={control}
render={({ field }) => (
<input
{...field}
value={field.value ?? ''}
maxLength={256}
className={inputClass}
id="name"
type="text"
placeholder={localize('com_agents_name_placeholder')}
aria-label="Agent name"
/>
)}
/>
<Controller
name="id"
control={control}
render={({ field }) => (
<p className="h-3 text-xs italic text-text-secondary" aria-live="polite">
{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 ?? ''}
maxLength={512}
className={inputClass}
id="description"
type="text"
placeholder={localize('com_agents_description_placeholder')}
aria-label="Agent description"
/>
)}
/>
</div>
{/* Instructions */}
<Instructions />
{/* Model and Provider */}
<div className="mb-4">
<label className={labelClass} htmlFor="provider">
{localize('com_ui_model')} <span className="text-red-500">*</span>
</label>
<button
type="button"
onClick={() => setActivePanel(Panel.model)}
className="btn btn-neutral border-token-border-light relative h-10 w-full rounded-lg font-medium"
aria-haspopup="true"
aria-expanded="false"
>
<div className="flex w-full items-center gap-2">
{Icon && (
<div className="shadow-stroke relative flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-white text-black dark:bg-white">
<Icon
className="h-2/3 w-2/3"
endpoint={providerValue as string}
endpointType={endpointType}
iconURL={endpointIconURL}
/>
</div>
)}
<span>{model != null && model ? model : localize('com_ui_select_model')}</span>
</div>
</button>
</div>
{(codeEnabled || fileSearchEnabled || artifactsEnabled || ocrEnabled) && (
<div className="mb-4 flex w-full flex-col items-start gap-3">
<label className="text-token-text-primary block font-medium">
{localize('com_assistants_capabilities')}
</label>
{/* Code Execution */}
{codeEnabled && <CodeForm agent_id={agent_id} files={code_files} />}
{/* File Context (OCR) */}
{ocrEnabled && <FileContext agent_id={agent_id} files={context_files} />}
{/* Artifacts */}
{artifactsEnabled && <Artifacts />}
{/* File Search */}
{fileSearchEnabled && <FileSearch agent_id={agent_id} files={knowledge_files} />}
</div>
)}
{/* Agent Tools & Actions */}
<div className="mb-4">
<label className={labelClass}>
{`${toolsEnabled === true ? localize('com_ui_tools') : ''}
${toolsEnabled === true && actionsEnabled === true ? ' + ' : ''}
${actionsEnabled === true ? localize('com_assistants_actions') : ''}`}
</label>
<div className="space-y-2">
{tools?.map((func, i) => (
<AgentTool
key={`${func}-${i}-${agent_id}`}
tool={func}
allTools={allTools}
agent_id={agent_id}
/>
))}
{actions
.filter((action) => action.agent_id === agent_id)
.map((action, i) => (
<Action
key={i}
action={action}
onClick={() => {
setAction(action);
setActivePanel(Panel.actions);
}}
/>
))}
<div className="flex space-x-2">
{(toolsEnabled ?? false) && (
<button
type="button"
onClick={() => setShowToolDialog(true)}
className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"
aria-haspopup="dialog"
>
<div className="flex w-full items-center justify-center gap-2">
{localize('com_assistants_add_tools')}
</div>
</button>
)}
{(actionsEnabled ?? false) && (
<button
type="button"
disabled={!agent_id}
onClick={handleAddActions}
className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"
aria-haspopup="dialog"
>
<div className="flex w-full items-center justify-center gap-2">
{localize('com_assistants_add_actions')}
</div>
</button>
)}
</div>
</div>
</div>
</div>
<ToolSelectDialog
isOpen={showToolDialog}
setIsOpen={setShowToolDialog}
toolsFormKey="tools"
endpoint={EModelEndpoint.agents}
/>
</>
);
}