LibreChat/client/src/components/SidePanel/Agents/AgentSelect.tsx
Danny Avila 7c9c7e530b
⏲️ feat: Defer Loading MCP Tools (#11270)
* WIP: code ptc

* refactor: tool classification and calling logic

* 🔧 fix: Update @librechat/agents dependency to version 3.0.68

* chore: import order and correct renamed tool name for tool search

* refactor: streamline tool classification logic for local and programmatic tools

* feat: add per-tool configuration options for agents, including deferred loading and allowed callers

- Introduced `tool_options` in agent forms to manage tool behavior.
- Updated tool classification logic to prioritize agent-level configurations.
- Enhanced UI components to support tool deferral functionality.
- Added localization strings for new tool options and actions.

* feat: enhance agent schema with per-tool options for configuration

- Added `tool_options` schema to support per-tool configurations, including `defer_loading` and `allowed_callers`.
- Updated agent data model to incorporate new tool options, ensuring flexibility in tool behavior management.
- Modified type definitions to reflect the new `tool_options` structure for agents.

* feat: add tool_options parameter to loadTools and initializeAgent for enhanced agent configuration

* chore: update @librechat/agents dependency to version 3.0.71 and enhance agent tool loading logic

- Updated the @librechat/agents package to version 3.0.71 across multiple files.
- Added support for handling deferred loading of tools in agent initialization and execution processes.
- Improved the extraction of discovered tools from message history to optimize tool loading behavior.

* chore: update @librechat/agents dependency to version 3.0.72

* chore: update @librechat/agents dependency to version 3.0.75

* refactor: simplify tool defer loading logic in MCPTool component

- Removed local state management for deferred tools, relying on form state instead.
- Updated related functions to directly use form values for checking and toggling defer loading.
- Cleaned up code by eliminating unnecessary optimistic updates and local state dependencies.

* chore: remove deprecated localization strings for tool deferral in translation.json

- Eliminated unused strings related to deferred loading descriptions in the English translation file.
- Streamlined localization to reflect recent changes in tool loading logic.

* refactor: improve tool defer loading handling in MCPTool component

- Enhanced the logic for managing deferred loading of tools by simplifying the update process for tool options.
- Ensured that the state reflects the correct loading behavior based on the new deferred loading conditions.
- Cleaned up the code to remove unnecessary complexity in handling tool options.

* refactor: update agent mocks in callbacks test to use actual implementations

- Modified the agent mocks in the callbacks test to include actual implementations from the @librechat/agents module.
- This change enhances the accuracy of the tests by ensuring they reflect the real behavior of the agent functions.
2026-01-28 17:44:30 -05:00

227 lines
6.6 KiB
TypeScript

import { EarthIcon } from 'lucide-react';
import { ControlCombobox } from '@librechat/client';
import { useCallback, useEffect, useRef } from 'react';
import { useFormContext, Controller } from 'react-hook-form';
import { AgentCapabilities, defaultAgentFormValues } from 'librechat-data-provider';
import type { UseMutationResult, QueryObserverResult } from '@tanstack/react-query';
import type { Agent, AgentCreateParams } from 'librechat-data-provider';
import type { TAgentCapabilities, AgentForm } from '~/common';
import { cn, createProviderOption, processAgentOption, getDefaultAgentFormValues } from '~/utils';
import { useLocalize, useAgentDefaultPermissionLevel } from '~/hooks';
import { useListAgentsQuery } from '~/data-provider';
const keys = new Set(Object.keys(defaultAgentFormValues));
export default function AgentSelect({
agentQuery,
selectedAgentId = null,
setCurrentAgentId,
createMutation,
}: {
selectedAgentId: string | null;
agentQuery: QueryObserverResult<Agent>;
setCurrentAgentId: React.Dispatch<React.SetStateAction<string | undefined>>;
createMutation: UseMutationResult<Agent, Error, AgentCreateParams>;
}) {
const localize = useLocalize();
const lastSelectedAgent = useRef<string | null>(null);
const { control, reset } = useFormContext();
const permissionLevel = useAgentDefaultPermissionLevel();
const { data: agents = null } = useListAgentsQuery(
{ requiredPermission: permissionLevel },
{
select: (res) =>
res.data.map((agent) =>
processAgentOption({
agent: {
...agent,
name: agent.name || agent.id,
},
}),
),
},
);
const resetAgentForm = useCallback(
(fullAgent: Agent) => {
const isGlobal = fullAgent.isPublic ?? false;
const update = {
...fullAgent,
provider: createProviderOption(fullAgent.provider),
label: fullAgent.name ?? '',
value: fullAgent.id || '',
icon: isGlobal ? <EarthIcon className={'icon-lg text-green-400'} /> : null,
};
const capabilities: TAgentCapabilities = {
[AgentCapabilities.web_search]: false,
[AgentCapabilities.file_search]: false,
[AgentCapabilities.execute_code]: false,
[AgentCapabilities.end_after_tools]: false,
[AgentCapabilities.hide_sequential_outputs]: false,
};
const agentTools: string[] = [];
(fullAgent.tools ?? []).forEach((tool) => {
if (capabilities[tool] !== undefined) {
capabilities[tool] = true;
return;
}
agentTools.push(tool);
});
const formValues: Partial<AgentForm & TAgentCapabilities> = {
...capabilities,
agent: update,
model: update.model,
tools: agentTools,
// Ensure the category is properly set for the form
category: fullAgent.category || 'general',
// Make sure support_contact is properly loaded
support_contact: fullAgent.support_contact,
avatar_file: null,
avatar_preview: fullAgent.avatar?.filepath ?? '',
avatar_action: null,
};
Object.entries(fullAgent).forEach(([name, value]) => {
if (name === 'model_parameters') {
formValues[name] = value;
return;
}
if (capabilities[name] !== undefined) {
formValues[name] = value;
return;
}
if (
name === 'agent_ids' &&
Array.isArray(value) &&
value.every((item) => typeof item === 'string')
) {
formValues[name] = value;
return;
}
if (name === 'edges' && Array.isArray(value)) {
formValues[name] = value;
return;
}
if (name === 'tool_options' && typeof value === 'object' && value !== null) {
formValues[name] = value;
return;
}
if (!keys.has(name)) {
return;
}
if (name === 'recursion_limit' && typeof value === 'number') {
formValues[name] = value;
return;
}
if (typeof value !== 'number' && typeof value !== 'object') {
formValues[name] = value;
}
});
reset(formValues);
},
[reset],
);
const onSelect = useCallback(
(selectedId: string) => {
const agentExists = !!(selectedId
? (agents ?? []).find((agent) => agent.id === selectedId)
: undefined);
createMutation.reset();
if (!agentExists) {
setCurrentAgentId(undefined);
return reset(getDefaultAgentFormValues());
}
setCurrentAgentId(selectedId);
const agent = agentQuery.data;
if (!agent) {
console.warn('Agent not found');
return;
}
resetAgentForm(agent);
},
[agents, createMutation, setCurrentAgentId, agentQuery.data, resetAgentForm, reset],
);
useEffect(() => {
if (agentQuery.data && agentQuery.isSuccess) {
resetAgentForm(agentQuery.data);
}
}, [agentQuery.data, agentQuery.isSuccess, resetAgentForm]);
useEffect(() => {
let timerId: NodeJS.Timeout | null = null;
if (selectedAgentId === lastSelectedAgent.current) {
return;
}
if (selectedAgentId != null && selectedAgentId !== '' && agents) {
timerId = setTimeout(() => {
lastSelectedAgent.current = selectedAgentId;
onSelect(selectedAgentId);
}, 5);
}
return () => {
if (timerId) {
clearTimeout(timerId);
}
};
}, [selectedAgentId, agents, onSelect]);
const createAgent = localize('com_ui_create_new_agent');
return (
<Controller
name="agent"
control={control}
render={({ field }) => (
<ControlCombobox
containerClassName="px-0"
selectedValue={(field?.value?.value ?? '') + ''}
displayValue={field?.value?.label ?? ''}
selectPlaceholder={field?.value?.value ?? createAgent}
iconSide="right"
searchPlaceholder={localize('com_agents_search_name')}
SelectIcon={field?.value?.icon}
setValue={onSelect}
items={
agents?.map((agent) => ({
label: agent.name ?? '',
value: agent.id ?? '',
icon: agent.icon,
})) ?? [
{
label: 'Loading...',
value: '',
},
]
}
className={cn(
'z-50 flex h-[40px] w-full flex-none items-center justify-center truncate rounded-md bg-transparent font-bold',
)}
ariaLabel={localize('com_ui_agent')}
isCollapsed={false}
showCarat={true}
/>
)}
/>
);
}