LibreChat/packages/data-provider/src/react-query/react-query-service.ts
Danny Avila 01e9b196bc
🤖 feat: Streamline Endpoints to Agent Framework (#8013)
* refactor(buildEndpointOption): Improve error logging in middleware, consolidate `isAgents` builder logic, remove adding `modelsConfig` to `endpointOption`

* refactor: parameter extraction and organization in agent services, minimize redundancy of shared fields across objects, make clear distinction of parameters processed uniquely by LibreChat vs LLM Provider Configs

* refactor(createPayload): streamline all endpoints to agent route

* fix: add `modelLabel` to response sender options for agent initialization

* chore: correct log message context in EditController abort controller cleanup

* chore: remove unused abortRequest hook

* chore: remove unused addToCache module and its dependencies

* refactor: remove AskController and related routes, update endpoint URLs (now all streamlined to agents route)

* chore: remove unused bedrock route and its related imports

* refactor: simplify response sender logic for Google endpoint

* chore: add `modelDisplayLabel` handling for agents endpoint

* feat: add file search capability to ephemeral agents, update code interpreter selection based of file upload, consolidate main upload menu for all endpoints

* feat: implement useToolToggle hook for managing tool toggle state, refactor CodeInterpreter and WebSearch components to utilize new hook

* feat: add ToolsDropdown component to BadgeRow for enhanced tool options

* feat: introduce BadgeRowContext and BadgeRowProvider for managing conversation state, refactor related components to utilize context

* feat: implement useMCPSelect hook for managing MCP selection state, refactor MCPSelect component to utilize new hook

* feat: enhance BadgeRowContext with MCPSelect and tool toggle functionality, refactor related components to utilize updated context and hooks

* refactor: streamline useToolToggle hook by integrating setEphemeralAgent directly into toggle logic and removing redundant setValue function

* refactor: consolidate codeApiKeyForm and searchApiKeyForm from CodeInterpreter and WebSearch to utilize new context properties

* refactor: update CheckboxButton to support controlled state and enhance ToolsDropdown with permission-based toggles for web search and code interpreter

* refactor: conditionally render CheckboxButton in CodeInterpreter and WebSearch components for improved UI responsiveness

* chore: add jotai dependency to package.json and package-lock.json

* chore: update brace-expansion package to version 2.0.2 in package-lock.json due to CVE-2025-5889

* Revert "chore: add jotai dependency to package.json and package-lock.json"

This reverts commit 69b6997396.

* refactor: add pinning functionality to CodeInterpreter and WebSearch components, and enhance ToolsDropdown with pin toggle for web search and code interpreter

* chore: move MCPIcon to correct location, remove duplicate

* fix: update MCP import to use type-only import from librechat-data-provider

* feat: implement MCPSubMenu component and integrate pinning functionality into ToolsDropdown

* fix: cycling to submenu by using parent menu context

* feat: add FileSearch component and integrate it into BadgeRow and ToolsDropdown

* chore: import order

* chore: remove agent specific logic that would block functionality for streamlined endpoints

* chore: linting for `createContextHandlers`

* chore: ensure ToolsDropdown doesn't show up for agents

* chore: ensure tool resource is selected when dragged to UI

* chore: update file search behavior to simulate legacy functionality

* feat: ToolDialogs with multiple trigger references, add settings to tool dropdown

* refactor: simplify web search and code interpreter settings checks

* chore: simplify local storage key for pinned state in useToolToggle

* refactor: reinstate agent check in AttachFileChat component, as individual providers will ahve different file configurations

* ci: increase timeout for MongoDB connection in Agent tests
2025-06-23 09:59:05 -04:00

348 lines
10 KiB
TypeScript

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import type {
UseQueryOptions,
UseMutationResult,
QueryObserverResult,
} from '@tanstack/react-query';
import { Constants, initialModelsConfig } from '../config';
import { defaultOrderQuery } from '../types/assistants';
import * as dataService from '../data-service';
import * as m from '../types/mutations';
import { QueryKeys } from '../keys';
import * as s from '../schemas';
import * as t from '../types';
export const useGetSharedMessages = (
shareId: string,
config?: UseQueryOptions<t.TSharedMessagesResponse>,
): QueryObserverResult<t.TSharedMessagesResponse> => {
return useQuery<t.TSharedMessagesResponse>(
[QueryKeys.sharedMessages, shareId],
() => dataService.getSharedMessages(shareId),
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
...config,
},
);
};
export const useGetSharedLinkQuery = (
conversationId: string,
config?: UseQueryOptions<t.TSharedLinkGetResponse>,
): QueryObserverResult<t.TSharedLinkGetResponse> => {
const queryClient = useQueryClient();
return useQuery<t.TSharedLinkGetResponse>(
[QueryKeys.sharedLinks, conversationId],
() => dataService.getSharedLink(conversationId),
{
enabled:
!!conversationId &&
conversationId !== Constants.NEW_CONVO &&
conversationId !== Constants.PENDING_CONVO,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
onSuccess: (data) => {
queryClient.setQueryData([QueryKeys.sharedLinks, conversationId], {
conversationId: data.conversationId,
shareId: data.shareId,
});
},
...config,
},
);
};
export const useGetConversationByIdQuery = (
id: string,
config?: UseQueryOptions<s.TConversation>,
): QueryObserverResult<s.TConversation> => {
return useQuery<s.TConversation>(
[QueryKeys.conversation, id],
() => dataService.getConversationById(id),
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
...config,
},
);
};
//This isn't ideal because its just a query and we're using mutation, but it was the only way
//to make it work with how the Chat component is structured
export const useGetConversationByIdMutation = (id: string): UseMutationResult<s.TConversation> => {
const queryClient = useQueryClient();
return useMutation(() => dataService.getConversationById(id), {
// onSuccess: (res: s.TConversation) => {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.conversation, id]);
},
});
};
export const useUpdateMessageMutation = (
id: string,
): UseMutationResult<unknown, unknown, t.TUpdateMessageRequest, unknown> => {
const queryClient = useQueryClient();
return useMutation((payload: t.TUpdateMessageRequest) => dataService.updateMessage(payload), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.messages, id]);
},
});
};
export const useUpdateMessageContentMutation = (
conversationId: string,
): UseMutationResult<unknown, unknown, t.TUpdateMessageContent, unknown> => {
const queryClient = useQueryClient();
return useMutation(
(payload: t.TUpdateMessageContent) => dataService.updateMessageContent(payload),
{
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.messages, conversationId]);
},
},
);
};
export const useUpdateUserKeysMutation = (): UseMutationResult<
t.TUser,
unknown,
t.TUpdateUserKeyRequest,
unknown
> => {
const queryClient = useQueryClient();
return useMutation((payload: t.TUpdateUserKeyRequest) => dataService.updateUserKey(payload), {
onSuccess: (data, variables) => {
queryClient.invalidateQueries([QueryKeys.name, variables.name]);
},
});
};
export const useClearConversationsMutation = (): UseMutationResult<unknown> => {
const queryClient = useQueryClient();
return useMutation(() => dataService.clearAllConversations(), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.allConversations]);
},
});
};
export const useRevokeUserKeyMutation = (name: string): UseMutationResult<unknown> => {
const queryClient = useQueryClient();
return useMutation(() => dataService.revokeUserKey(name), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.name, name]);
if (s.isAssistantsEndpoint(name)) {
queryClient.invalidateQueries([QueryKeys.assistants, name, defaultOrderQuery]);
queryClient.invalidateQueries([QueryKeys.assistantDocs]);
queryClient.invalidateQueries([QueryKeys.assistants]);
queryClient.invalidateQueries([QueryKeys.assistant]);
queryClient.invalidateQueries([QueryKeys.actions]);
queryClient.invalidateQueries([QueryKeys.tools]);
}
},
});
};
export const useRevokeAllUserKeysMutation = (): UseMutationResult<unknown> => {
const queryClient = useQueryClient();
return useMutation(() => dataService.revokeAllUserKeys(), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.name]);
queryClient.invalidateQueries([
QueryKeys.assistants,
s.EModelEndpoint.assistants,
defaultOrderQuery,
]);
queryClient.invalidateQueries([
QueryKeys.assistants,
s.EModelEndpoint.azureAssistants,
defaultOrderQuery,
]);
queryClient.invalidateQueries([QueryKeys.assistantDocs]);
queryClient.invalidateQueries([QueryKeys.assistants]);
queryClient.invalidateQueries([QueryKeys.assistant]);
queryClient.invalidateQueries([QueryKeys.actions]);
queryClient.invalidateQueries([QueryKeys.tools]);
},
});
};
export const useGetModelsQuery = (
config?: UseQueryOptions<t.TModelsConfig>,
): QueryObserverResult<t.TModelsConfig> => {
return useQuery<t.TModelsConfig>([QueryKeys.models], () => dataService.getModels(), {
initialData: initialModelsConfig,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
staleTime: Infinity,
...config,
});
};
export const useCreatePresetMutation = (): UseMutationResult<
s.TPreset,
unknown,
s.TPreset,
unknown
> => {
const queryClient = useQueryClient();
return useMutation((payload: s.TPreset) => dataService.createPreset(payload), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.presets]);
},
});
};
export const useDeletePresetMutation = (): UseMutationResult<
m.PresetDeleteResponse,
unknown,
s.TPreset | undefined,
unknown
> => {
const queryClient = useQueryClient();
return useMutation((payload: s.TPreset | undefined) => dataService.deletePreset(payload), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.presets]);
},
});
};
export const useUpdateTokenCountMutation = (): UseMutationResult<
t.TUpdateTokenCountResponse,
unknown,
{ text: string },
unknown
> => {
const queryClient = useQueryClient();
return useMutation(({ text }: { text: string }) => dataService.updateTokenCount(text), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.tokenCount]);
},
});
};
export const useRegisterUserMutation = (
options?: m.RegistrationOptions,
): UseMutationResult<t.TError, unknown, t.TRegisterUser, unknown> => {
const queryClient = useQueryClient();
return useMutation<t.TRegisterUserResponse, t.TError, t.TRegisterUser>(
(payload: t.TRegisterUser) => dataService.register(payload),
{
...options,
onSuccess: (...args) => {
queryClient.invalidateQueries([QueryKeys.user]);
if (options?.onSuccess) {
options.onSuccess(...args);
}
},
},
);
};
export const useUserKeyQuery = (
name: string,
config?: UseQueryOptions<t.TCheckUserKeyResponse>,
): QueryObserverResult<t.TCheckUserKeyResponse> => {
return useQuery<t.TCheckUserKeyResponse>(
[QueryKeys.name, name],
() => {
if (!name) {
return Promise.resolve({ expiresAt: '' });
}
return dataService.userKeyQuery(name);
},
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
retry: false,
...config,
},
);
};
export const useRequestPasswordResetMutation = (): UseMutationResult<
t.TRequestPasswordResetResponse,
unknown,
t.TRequestPasswordReset,
unknown
> => {
return useMutation((payload: t.TRequestPasswordReset) =>
dataService.requestPasswordReset(payload),
);
};
export const useResetPasswordMutation = (): UseMutationResult<
unknown,
unknown,
t.TResetPassword,
unknown
> => {
return useMutation((payload: t.TResetPassword) => dataService.resetPassword(payload));
};
export const useAvailablePluginsQuery = <TData = s.TPlugin[]>(
config?: UseQueryOptions<s.TPlugin[], unknown, TData>,
): QueryObserverResult<TData> => {
return useQuery<s.TPlugin[], unknown, TData>(
[QueryKeys.availablePlugins],
() => dataService.getAvailablePlugins(),
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
...config,
},
);
};
export const useUpdateUserPluginsMutation = (
_options?: m.UpdatePluginAuthOptions,
): UseMutationResult<t.TUser, unknown, t.TUpdateUserPlugins, unknown> => {
const queryClient = useQueryClient();
const { onSuccess, ...options } = _options ?? {};
return useMutation((payload: t.TUpdateUserPlugins) => dataService.updateUserPlugins(payload), {
...options,
onSuccess: (...args) => {
queryClient.invalidateQueries([QueryKeys.user]);
onSuccess?.(...args);
},
});
};
export const useGetCustomConfigSpeechQuery = (
config?: UseQueryOptions<t.TCustomConfigSpeechResponse>,
): QueryObserverResult<t.TCustomConfigSpeechResponse> => {
return useQuery<t.TCustomConfigSpeechResponse>(
[QueryKeys.customConfigSpeech],
() => dataService.getCustomConfigSpeech(),
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
...config,
},
);
};
export const useUpdateFeedbackMutation = (
conversationId: string,
messageId: string,
): UseMutationResult<t.TUpdateFeedbackResponse, Error, t.TUpdateFeedbackRequest> => {
const queryClient = useQueryClient();
return useMutation(
(payload: t.TUpdateFeedbackRequest) =>
dataService.updateFeedback(conversationId, messageId, payload),
{
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.messages, messageId]);
},
},
);
};