LibreChat/api/models/Agent.js

679 lines
22 KiB
JavaScript
Raw Normal View History

🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
const mongoose = require('mongoose');
const crypto = require('node:crypto');
🏗️ refactor: Extract DB layers to `data-schemas` for shared use (#7650) * refactor: move model definitions and database-related methods to packages/data-schemas * ci: update tests due to new DB structure fix: disable mocking `librechat-data-provider` feat: Add schema exports to data-schemas package - Introduced a new schema module that exports various schemas including action, agent, and user schemas. - Updated index.ts to include the new schema exports for better modularity and organization. ci: fix appleStrategy tests fix: Agent.spec.js ci: refactor handleTools tests to use MongoMemoryServer for in-memory database fix: getLogStores imports ci: update banViolation tests to use MongoMemoryServer and improve session mocking test: refactor samlStrategy tests to improve mock configurations and user handling ci: fix crypto mock in handleText tests for improved accuracy ci: refactor spendTokens tests to improve model imports and setup ci: refactor Message model tests to use MongoMemoryServer and improve database interactions * refactor: streamline IMessage interface and move feedback properties to types/message.ts * refactor: use exported initializeRoles from `data-schemas`, remove api workspace version (this serves as an example of future migrations that still need to happen) * refactor: update model imports to use destructuring from `~/db/models` for consistency and clarity * refactor: remove unused mongoose imports from model files for cleaner code * refactor: remove unused mongoose imports from Share, Prompt, and Transaction model files for cleaner code * refactor: remove unused import in Transaction model for cleaner code * ci: update deploy workflow to reference new Docker Dev Branch Images Build and add new workflow for building Docker images on dev branch * chore: cleanup imports
2025-05-30 22:18:13 -04:00
const { logger } = require('@librechat/data-schemas');
const { SystemRoles, Tools, actionDelimiter } = require('librechat-data-provider');
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
const { GLOBAL_PROJECT_NAME, EPHEMERAL_AGENT_ID, mcp_delimiter } =
require('librechat-data-provider').Constants;
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const { CONFIG_STORE, STARTUP_CONFIG } = require('librechat-data-provider').CacheKeys;
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
const {
getProjectByName,
addAgentIdsToProject,
removeAgentIdsFromProject,
removeAgentFromAllProjects,
} = require('./Project');
🪐 feat: MCP OAuth 2.0 Discovery Support (#7924) * chore: Update @modelcontextprotocol/sdk to version 1.12.3 in package.json and package-lock.json - Bump version of @modelcontextprotocol/sdk to 1.12.3 to incorporate recent updates. - Update dependencies for ajv and cross-spawn to their latest versions. - Add ajv as a new dependency in the sdk module. - Include json-schema-traverse as a new dependency in the sdk module. * feat: @librechat/auth * feat: Add crypto module exports to auth package - Introduced a new crypto module by creating index.ts in the crypto directory. - Updated the main index.ts of the auth package to export from the new crypto module. * feat: Update package dependencies and build scripts for auth package - Added @librechat/auth as a dependency in package.json and package-lock.json. - Updated build scripts to include the auth package in both frontend and bun build processes. - Removed unused mongoose and openid-client dependencies from package-lock.json for cleaner dependency management. * refactor: Migrate crypto utility functions to @librechat/auth - Replaced local crypto utility imports with the new @librechat/auth package across multiple files. - Removed the obsolete crypto.js file and its exports. - Updated relevant services and models to utilize the new encryption and decryption methods from @librechat/auth. * feat: Enhance OAuth token handling and update dependencies in auth package * chore: Remove Token model and TokenService due to restructuring of OAuth handling - Deleted the Token.js model and TokenService.js, which were responsible for managing OAuth tokens. - This change is part of a broader refactor to streamline OAuth token management and improve code organization. * refactor: imports from '@librechat/auth' to '@librechat/api' and add OAuth token handling functionality * refactor: Simplify logger usage in MCP and FlowStateManager classes * chore: fix imports * feat: Add OAuth configuration schema to MCP with token exchange method support * feat: FIRST PASS Implement MCP OAuth flow with token management and error handling - Added a new route for handling OAuth callbacks and token retrieval. - Integrated OAuth token storage and retrieval mechanisms. - Enhanced MCP connection to support automatic OAuth flow initiation on 401 errors. - Implemented dynamic client registration and metadata discovery for OAuth. - Updated MCPManager to manage OAuth tokens and handle authentication requirements. - Introduced comprehensive logging for OAuth processes and error handling. * refactor: Update MCPConnection and MCPManager to utilize new URL handling - Added a `url` property to MCPConnection for better URL management. - Refactored MCPManager to use the new `url` property instead of a deprecated method for OAuth handling. - Changed logging from info to debug level for flow manager and token methods initialization. - Improved comments for clarity on existing tokens and OAuth event listener setup. * refactor: Improve connection timeout error messages in MCPConnection and MCPManager and use initTimeout for connection - Updated the connection timeout error messages to include the duration of the timeout. - Introduced a configurable `connectTimeout` variable in both MCPConnection and MCPManager for better flexibility. * chore: cleanup MCP OAuth Token exchange handling; fix: erroneous use of flowsCache and remove verbose logs * refactor: Update MCPManager and MCPTokenStorage to use TokenMethods for token management - Removed direct token storage handling in MCPManager and replaced it with TokenMethods for better abstraction. - Refactored MCPTokenStorage methods to accept parameters for token operations, enhancing flexibility and readability. - Improved logging messages related to token persistence and retrieval processes. * refactor: Update MCP OAuth handling to use static methods and improve flow management - Refactored MCPOAuthHandler to utilize static methods for initiating and completing OAuth flows, enhancing clarity and reducing instance dependencies. - Updated MCPManager to pass flowManager explicitly to OAuth handling methods, improving flexibility in flow state management. - Enhanced comments and logging for better understanding of OAuth processes and flow state retrieval. * refactor: Integrate token methods into createMCPTool for enhanced token management * refactor: Change logging from info to debug level in MCPOAuthHandler for improved log management * chore: clean up logging * feat: first pass, auth URL from MCP OAuth flow * chore: Improve logging format for OAuth authentication URL display * chore: cleanup mcp manager comments * feat: add connection reconnection logic in MCPManager * refactor: reorganize token storage handling in MCP - Moved token storage logic from MCPManager to a new MCPTokenStorage class for better separation of concerns. - Updated imports to reflect the new token storage structure. - Enhanced methods for storing, retrieving, updating, and deleting OAuth tokens, improving overall token management. * chore: update comment for SYSTEM_USER_ID in MCPManager for clarity * feat: implement refresh token functionality in MCP - Added refresh token handling in MCPManager to support token renewal for both app-level and user-specific connections. - Introduced a refreshTokens function to facilitate token refresh logic. - Enhanced MCPTokenStorage to manage client information and refresh token processes. - Updated logging for better traceability during token operations. * chore: cleanup @librechat/auth * feat: implement MCP server initialization in a separate service - Added a new service to handle the initialization of MCP servers, improving code organization and readability. - Refactored the server startup logic to utilize the new initializeMCP function. - Removed redundant MCP initialization code from the main server file. * fix: don't log auth url for user connections * feat: enhance OAuth flow with success and error handling components - Updated OAuth callback routes to redirect to new success and error pages instead of sending status messages. - Introduced `OAuthSuccess` and `OAuthError` components to provide user feedback during authentication. - Added localization support for success and error messages in the translation files. - Implemented countdown functionality in the success component for a better user experience. * fix: refresh token handling for user connections, add missing URL and methods - add standard enum for system user id and helper for determining app-lvel vs. user-level connections * refactor: update token handling in MCPManager and MCPTokenStorage * fix: improve error logging in OAuth authentication handler * fix: concurrency issues for both login url emission and concurrency of oauth flows for shared flows (same user, same server, multiple calls for same server) * fix: properly fail shared flows for concurrent server calls and prevent duplication of tokens * chore: remove unused auth package directory from update configuration * ci: fix mocks in samlStrategy tests * ci: add mcpConfig to AppService test setup * chore: remove obsolete MCP OAuth implementation documentation * fix: update build script for API to use correct command * chore: bump version of @librechat/api to 1.2.4 * fix: update abort signal handling in createMCPTool function * fix: add optional clientInfo parameter to refreshTokensFunction metadata * refactor: replace app.locals.availableTools with getCachedTools in multiple services and controllers for improved tool management * fix: concurrent refresh token handling issue * refactor: add signal parameter to getUserConnection method for improved abort handling * chore: JSDoc typing for `loadEphemeralAgent` * refactor: update isConnectionActive method to use destructured parameters for improved readability * feat: implement caching for MCP tools to handle app-level disconnects for loading list of tools * ci: fix agent test
2025-06-17 13:50:33 -04:00
const { getCachedTools } = require('~/server/services/Config');
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const getLogStores = require('~/cache/getLogStores');
const { getActions } = require('./Action');
🏗️ refactor: Extract DB layers to `data-schemas` for shared use (#7650) * refactor: move model definitions and database-related methods to packages/data-schemas * ci: update tests due to new DB structure fix: disable mocking `librechat-data-provider` feat: Add schema exports to data-schemas package - Introduced a new schema module that exports various schemas including action, agent, and user schemas. - Updated index.ts to include the new schema exports for better modularity and organization. ci: fix appleStrategy tests fix: Agent.spec.js ci: refactor handleTools tests to use MongoMemoryServer for in-memory database fix: getLogStores imports ci: update banViolation tests to use MongoMemoryServer and improve session mocking test: refactor samlStrategy tests to improve mock configurations and user handling ci: fix crypto mock in handleText tests for improved accuracy ci: refactor spendTokens tests to improve model imports and setup ci: refactor Message model tests to use MongoMemoryServer and improve database interactions * refactor: streamline IMessage interface and move feedback properties to types/message.ts * refactor: use exported initializeRoles from `data-schemas`, remove api workspace version (this serves as an example of future migrations that still need to happen) * refactor: update model imports to use destructuring from `~/db/models` for consistency and clarity * refactor: remove unused mongoose imports from model files for cleaner code * refactor: remove unused mongoose imports from Share, Prompt, and Transaction model files for cleaner code * refactor: remove unused import in Transaction model for cleaner code * ci: update deploy workflow to reference new Docker Dev Branch Images Build and add new workflow for building Docker images on dev branch * chore: cleanup imports
2025-05-30 22:18:13 -04:00
const { Agent } = require('~/db/models');
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
/**
* Create an agent with the provided data.
* @param {Object} agentData - The agent data to create.
* @returns {Promise<Agent>} The created agent document as a plain object.
* @throws {Error} If the agent creation fails.
*/
const createAgent = async (agentData) => {
const { author, ...versionData } = agentData;
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
const timestamp = new Date();
const initialAgentData = {
...agentData,
versions: [
{
...versionData,
createdAt: timestamp,
updatedAt: timestamp,
},
],
};
return (await Agent.create(initialAgentData)).toObject();
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
};
/**
* Get an agent document based on the provided ID.
*
* @param {Object} searchParameter - The search parameters to find the agent to update.
* @param {string} searchParameter.id - The ID of the agent to update.
* @param {string} searchParameter.author - The user ID of the agent's author.
* @returns {Promise<Agent|null>} The agent document as a plain object, or null if not found.
*/
const getAgent = async (searchParameter) => await Agent.findOne(searchParameter).lean();
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
/**
* Load an agent based on the provided ID
*
* @param {Object} params
* @param {ServerRequest} params.req
* @param {string} params.agent_id
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
* @param {string} params.endpoint
* @param {import('@librechat/agents').ClientOptions} [params.model_parameters]
🪐 feat: MCP OAuth 2.0 Discovery Support (#7924) * chore: Update @modelcontextprotocol/sdk to version 1.12.3 in package.json and package-lock.json - Bump version of @modelcontextprotocol/sdk to 1.12.3 to incorporate recent updates. - Update dependencies for ajv and cross-spawn to their latest versions. - Add ajv as a new dependency in the sdk module. - Include json-schema-traverse as a new dependency in the sdk module. * feat: @librechat/auth * feat: Add crypto module exports to auth package - Introduced a new crypto module by creating index.ts in the crypto directory. - Updated the main index.ts of the auth package to export from the new crypto module. * feat: Update package dependencies and build scripts for auth package - Added @librechat/auth as a dependency in package.json and package-lock.json. - Updated build scripts to include the auth package in both frontend and bun build processes. - Removed unused mongoose and openid-client dependencies from package-lock.json for cleaner dependency management. * refactor: Migrate crypto utility functions to @librechat/auth - Replaced local crypto utility imports with the new @librechat/auth package across multiple files. - Removed the obsolete crypto.js file and its exports. - Updated relevant services and models to utilize the new encryption and decryption methods from @librechat/auth. * feat: Enhance OAuth token handling and update dependencies in auth package * chore: Remove Token model and TokenService due to restructuring of OAuth handling - Deleted the Token.js model and TokenService.js, which were responsible for managing OAuth tokens. - This change is part of a broader refactor to streamline OAuth token management and improve code organization. * refactor: imports from '@librechat/auth' to '@librechat/api' and add OAuth token handling functionality * refactor: Simplify logger usage in MCP and FlowStateManager classes * chore: fix imports * feat: Add OAuth configuration schema to MCP with token exchange method support * feat: FIRST PASS Implement MCP OAuth flow with token management and error handling - Added a new route for handling OAuth callbacks and token retrieval. - Integrated OAuth token storage and retrieval mechanisms. - Enhanced MCP connection to support automatic OAuth flow initiation on 401 errors. - Implemented dynamic client registration and metadata discovery for OAuth. - Updated MCPManager to manage OAuth tokens and handle authentication requirements. - Introduced comprehensive logging for OAuth processes and error handling. * refactor: Update MCPConnection and MCPManager to utilize new URL handling - Added a `url` property to MCPConnection for better URL management. - Refactored MCPManager to use the new `url` property instead of a deprecated method for OAuth handling. - Changed logging from info to debug level for flow manager and token methods initialization. - Improved comments for clarity on existing tokens and OAuth event listener setup. * refactor: Improve connection timeout error messages in MCPConnection and MCPManager and use initTimeout for connection - Updated the connection timeout error messages to include the duration of the timeout. - Introduced a configurable `connectTimeout` variable in both MCPConnection and MCPManager for better flexibility. * chore: cleanup MCP OAuth Token exchange handling; fix: erroneous use of flowsCache and remove verbose logs * refactor: Update MCPManager and MCPTokenStorage to use TokenMethods for token management - Removed direct token storage handling in MCPManager and replaced it with TokenMethods for better abstraction. - Refactored MCPTokenStorage methods to accept parameters for token operations, enhancing flexibility and readability. - Improved logging messages related to token persistence and retrieval processes. * refactor: Update MCP OAuth handling to use static methods and improve flow management - Refactored MCPOAuthHandler to utilize static methods for initiating and completing OAuth flows, enhancing clarity and reducing instance dependencies. - Updated MCPManager to pass flowManager explicitly to OAuth handling methods, improving flexibility in flow state management. - Enhanced comments and logging for better understanding of OAuth processes and flow state retrieval. * refactor: Integrate token methods into createMCPTool for enhanced token management * refactor: Change logging from info to debug level in MCPOAuthHandler for improved log management * chore: clean up logging * feat: first pass, auth URL from MCP OAuth flow * chore: Improve logging format for OAuth authentication URL display * chore: cleanup mcp manager comments * feat: add connection reconnection logic in MCPManager * refactor: reorganize token storage handling in MCP - Moved token storage logic from MCPManager to a new MCPTokenStorage class for better separation of concerns. - Updated imports to reflect the new token storage structure. - Enhanced methods for storing, retrieving, updating, and deleting OAuth tokens, improving overall token management. * chore: update comment for SYSTEM_USER_ID in MCPManager for clarity * feat: implement refresh token functionality in MCP - Added refresh token handling in MCPManager to support token renewal for both app-level and user-specific connections. - Introduced a refreshTokens function to facilitate token refresh logic. - Enhanced MCPTokenStorage to manage client information and refresh token processes. - Updated logging for better traceability during token operations. * chore: cleanup @librechat/auth * feat: implement MCP server initialization in a separate service - Added a new service to handle the initialization of MCP servers, improving code organization and readability. - Refactored the server startup logic to utilize the new initializeMCP function. - Removed redundant MCP initialization code from the main server file. * fix: don't log auth url for user connections * feat: enhance OAuth flow with success and error handling components - Updated OAuth callback routes to redirect to new success and error pages instead of sending status messages. - Introduced `OAuthSuccess` and `OAuthError` components to provide user feedback during authentication. - Added localization support for success and error messages in the translation files. - Implemented countdown functionality in the success component for a better user experience. * fix: refresh token handling for user connections, add missing URL and methods - add standard enum for system user id and helper for determining app-lvel vs. user-level connections * refactor: update token handling in MCPManager and MCPTokenStorage * fix: improve error logging in OAuth authentication handler * fix: concurrency issues for both login url emission and concurrency of oauth flows for shared flows (same user, same server, multiple calls for same server) * fix: properly fail shared flows for concurrent server calls and prevent duplication of tokens * chore: remove unused auth package directory from update configuration * ci: fix mocks in samlStrategy tests * ci: add mcpConfig to AppService test setup * chore: remove obsolete MCP OAuth implementation documentation * fix: update build script for API to use correct command * chore: bump version of @librechat/api to 1.2.4 * fix: update abort signal handling in createMCPTool function * fix: add optional clientInfo parameter to refreshTokensFunction metadata * refactor: replace app.locals.availableTools with getCachedTools in multiple services and controllers for improved tool management * fix: concurrent refresh token handling issue * refactor: add signal parameter to getUserConnection method for improved abort handling * chore: JSDoc typing for `loadEphemeralAgent` * refactor: update isConnectionActive method to use destructured parameters for improved readability * feat: implement caching for MCP tools to handle app-level disconnects for loading list of tools * ci: fix agent test
2025-06-17 13:50:33 -04:00
* @returns {Promise<Agent|null>} The agent document as a plain object, or null if not found.
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
*/
🪐 feat: MCP OAuth 2.0 Discovery Support (#7924) * chore: Update @modelcontextprotocol/sdk to version 1.12.3 in package.json and package-lock.json - Bump version of @modelcontextprotocol/sdk to 1.12.3 to incorporate recent updates. - Update dependencies for ajv and cross-spawn to their latest versions. - Add ajv as a new dependency in the sdk module. - Include json-schema-traverse as a new dependency in the sdk module. * feat: @librechat/auth * feat: Add crypto module exports to auth package - Introduced a new crypto module by creating index.ts in the crypto directory. - Updated the main index.ts of the auth package to export from the new crypto module. * feat: Update package dependencies and build scripts for auth package - Added @librechat/auth as a dependency in package.json and package-lock.json. - Updated build scripts to include the auth package in both frontend and bun build processes. - Removed unused mongoose and openid-client dependencies from package-lock.json for cleaner dependency management. * refactor: Migrate crypto utility functions to @librechat/auth - Replaced local crypto utility imports with the new @librechat/auth package across multiple files. - Removed the obsolete crypto.js file and its exports. - Updated relevant services and models to utilize the new encryption and decryption methods from @librechat/auth. * feat: Enhance OAuth token handling and update dependencies in auth package * chore: Remove Token model and TokenService due to restructuring of OAuth handling - Deleted the Token.js model and TokenService.js, which were responsible for managing OAuth tokens. - This change is part of a broader refactor to streamline OAuth token management and improve code organization. * refactor: imports from '@librechat/auth' to '@librechat/api' and add OAuth token handling functionality * refactor: Simplify logger usage in MCP and FlowStateManager classes * chore: fix imports * feat: Add OAuth configuration schema to MCP with token exchange method support * feat: FIRST PASS Implement MCP OAuth flow with token management and error handling - Added a new route for handling OAuth callbacks and token retrieval. - Integrated OAuth token storage and retrieval mechanisms. - Enhanced MCP connection to support automatic OAuth flow initiation on 401 errors. - Implemented dynamic client registration and metadata discovery for OAuth. - Updated MCPManager to manage OAuth tokens and handle authentication requirements. - Introduced comprehensive logging for OAuth processes and error handling. * refactor: Update MCPConnection and MCPManager to utilize new URL handling - Added a `url` property to MCPConnection for better URL management. - Refactored MCPManager to use the new `url` property instead of a deprecated method for OAuth handling. - Changed logging from info to debug level for flow manager and token methods initialization. - Improved comments for clarity on existing tokens and OAuth event listener setup. * refactor: Improve connection timeout error messages in MCPConnection and MCPManager and use initTimeout for connection - Updated the connection timeout error messages to include the duration of the timeout. - Introduced a configurable `connectTimeout` variable in both MCPConnection and MCPManager for better flexibility. * chore: cleanup MCP OAuth Token exchange handling; fix: erroneous use of flowsCache and remove verbose logs * refactor: Update MCPManager and MCPTokenStorage to use TokenMethods for token management - Removed direct token storage handling in MCPManager and replaced it with TokenMethods for better abstraction. - Refactored MCPTokenStorage methods to accept parameters for token operations, enhancing flexibility and readability. - Improved logging messages related to token persistence and retrieval processes. * refactor: Update MCP OAuth handling to use static methods and improve flow management - Refactored MCPOAuthHandler to utilize static methods for initiating and completing OAuth flows, enhancing clarity and reducing instance dependencies. - Updated MCPManager to pass flowManager explicitly to OAuth handling methods, improving flexibility in flow state management. - Enhanced comments and logging for better understanding of OAuth processes and flow state retrieval. * refactor: Integrate token methods into createMCPTool for enhanced token management * refactor: Change logging from info to debug level in MCPOAuthHandler for improved log management * chore: clean up logging * feat: first pass, auth URL from MCP OAuth flow * chore: Improve logging format for OAuth authentication URL display * chore: cleanup mcp manager comments * feat: add connection reconnection logic in MCPManager * refactor: reorganize token storage handling in MCP - Moved token storage logic from MCPManager to a new MCPTokenStorage class for better separation of concerns. - Updated imports to reflect the new token storage structure. - Enhanced methods for storing, retrieving, updating, and deleting OAuth tokens, improving overall token management. * chore: update comment for SYSTEM_USER_ID in MCPManager for clarity * feat: implement refresh token functionality in MCP - Added refresh token handling in MCPManager to support token renewal for both app-level and user-specific connections. - Introduced a refreshTokens function to facilitate token refresh logic. - Enhanced MCPTokenStorage to manage client information and refresh token processes. - Updated logging for better traceability during token operations. * chore: cleanup @librechat/auth * feat: implement MCP server initialization in a separate service - Added a new service to handle the initialization of MCP servers, improving code organization and readability. - Refactored the server startup logic to utilize the new initializeMCP function. - Removed redundant MCP initialization code from the main server file. * fix: don't log auth url for user connections * feat: enhance OAuth flow with success and error handling components - Updated OAuth callback routes to redirect to new success and error pages instead of sending status messages. - Introduced `OAuthSuccess` and `OAuthError` components to provide user feedback during authentication. - Added localization support for success and error messages in the translation files. - Implemented countdown functionality in the success component for a better user experience. * fix: refresh token handling for user connections, add missing URL and methods - add standard enum for system user id and helper for determining app-lvel vs. user-level connections * refactor: update token handling in MCPManager and MCPTokenStorage * fix: improve error logging in OAuth authentication handler * fix: concurrency issues for both login url emission and concurrency of oauth flows for shared flows (same user, same server, multiple calls for same server) * fix: properly fail shared flows for concurrent server calls and prevent duplication of tokens * chore: remove unused auth package directory from update configuration * ci: fix mocks in samlStrategy tests * ci: add mcpConfig to AppService test setup * chore: remove obsolete MCP OAuth implementation documentation * fix: update build script for API to use correct command * chore: bump version of @librechat/api to 1.2.4 * fix: update abort signal handling in createMCPTool function * fix: add optional clientInfo parameter to refreshTokensFunction metadata * refactor: replace app.locals.availableTools with getCachedTools in multiple services and controllers for improved tool management * fix: concurrent refresh token handling issue * refactor: add signal parameter to getUserConnection method for improved abort handling * chore: JSDoc typing for `loadEphemeralAgent` * refactor: update isConnectionActive method to use destructured parameters for improved readability * feat: implement caching for MCP tools to handle app-level disconnects for loading list of tools * ci: fix agent test
2025-06-17 13:50:33 -04:00
const loadEphemeralAgent = async ({ req, agent_id, endpoint, model_parameters: _m }) => {
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
const { model, ...model_parameters } = _m;
/** @type {Record<string, FunctionTool>} */
🪐 feat: MCP OAuth 2.0 Discovery Support (#7924) * chore: Update @modelcontextprotocol/sdk to version 1.12.3 in package.json and package-lock.json - Bump version of @modelcontextprotocol/sdk to 1.12.3 to incorporate recent updates. - Update dependencies for ajv and cross-spawn to their latest versions. - Add ajv as a new dependency in the sdk module. - Include json-schema-traverse as a new dependency in the sdk module. * feat: @librechat/auth * feat: Add crypto module exports to auth package - Introduced a new crypto module by creating index.ts in the crypto directory. - Updated the main index.ts of the auth package to export from the new crypto module. * feat: Update package dependencies and build scripts for auth package - Added @librechat/auth as a dependency in package.json and package-lock.json. - Updated build scripts to include the auth package in both frontend and bun build processes. - Removed unused mongoose and openid-client dependencies from package-lock.json for cleaner dependency management. * refactor: Migrate crypto utility functions to @librechat/auth - Replaced local crypto utility imports with the new @librechat/auth package across multiple files. - Removed the obsolete crypto.js file and its exports. - Updated relevant services and models to utilize the new encryption and decryption methods from @librechat/auth. * feat: Enhance OAuth token handling and update dependencies in auth package * chore: Remove Token model and TokenService due to restructuring of OAuth handling - Deleted the Token.js model and TokenService.js, which were responsible for managing OAuth tokens. - This change is part of a broader refactor to streamline OAuth token management and improve code organization. * refactor: imports from '@librechat/auth' to '@librechat/api' and add OAuth token handling functionality * refactor: Simplify logger usage in MCP and FlowStateManager classes * chore: fix imports * feat: Add OAuth configuration schema to MCP with token exchange method support * feat: FIRST PASS Implement MCP OAuth flow with token management and error handling - Added a new route for handling OAuth callbacks and token retrieval. - Integrated OAuth token storage and retrieval mechanisms. - Enhanced MCP connection to support automatic OAuth flow initiation on 401 errors. - Implemented dynamic client registration and metadata discovery for OAuth. - Updated MCPManager to manage OAuth tokens and handle authentication requirements. - Introduced comprehensive logging for OAuth processes and error handling. * refactor: Update MCPConnection and MCPManager to utilize new URL handling - Added a `url` property to MCPConnection for better URL management. - Refactored MCPManager to use the new `url` property instead of a deprecated method for OAuth handling. - Changed logging from info to debug level for flow manager and token methods initialization. - Improved comments for clarity on existing tokens and OAuth event listener setup. * refactor: Improve connection timeout error messages in MCPConnection and MCPManager and use initTimeout for connection - Updated the connection timeout error messages to include the duration of the timeout. - Introduced a configurable `connectTimeout` variable in both MCPConnection and MCPManager for better flexibility. * chore: cleanup MCP OAuth Token exchange handling; fix: erroneous use of flowsCache and remove verbose logs * refactor: Update MCPManager and MCPTokenStorage to use TokenMethods for token management - Removed direct token storage handling in MCPManager and replaced it with TokenMethods for better abstraction. - Refactored MCPTokenStorage methods to accept parameters for token operations, enhancing flexibility and readability. - Improved logging messages related to token persistence and retrieval processes. * refactor: Update MCP OAuth handling to use static methods and improve flow management - Refactored MCPOAuthHandler to utilize static methods for initiating and completing OAuth flows, enhancing clarity and reducing instance dependencies. - Updated MCPManager to pass flowManager explicitly to OAuth handling methods, improving flexibility in flow state management. - Enhanced comments and logging for better understanding of OAuth processes and flow state retrieval. * refactor: Integrate token methods into createMCPTool for enhanced token management * refactor: Change logging from info to debug level in MCPOAuthHandler for improved log management * chore: clean up logging * feat: first pass, auth URL from MCP OAuth flow * chore: Improve logging format for OAuth authentication URL display * chore: cleanup mcp manager comments * feat: add connection reconnection logic in MCPManager * refactor: reorganize token storage handling in MCP - Moved token storage logic from MCPManager to a new MCPTokenStorage class for better separation of concerns. - Updated imports to reflect the new token storage structure. - Enhanced methods for storing, retrieving, updating, and deleting OAuth tokens, improving overall token management. * chore: update comment for SYSTEM_USER_ID in MCPManager for clarity * feat: implement refresh token functionality in MCP - Added refresh token handling in MCPManager to support token renewal for both app-level and user-specific connections. - Introduced a refreshTokens function to facilitate token refresh logic. - Enhanced MCPTokenStorage to manage client information and refresh token processes. - Updated logging for better traceability during token operations. * chore: cleanup @librechat/auth * feat: implement MCP server initialization in a separate service - Added a new service to handle the initialization of MCP servers, improving code organization and readability. - Refactored the server startup logic to utilize the new initializeMCP function. - Removed redundant MCP initialization code from the main server file. * fix: don't log auth url for user connections * feat: enhance OAuth flow with success and error handling components - Updated OAuth callback routes to redirect to new success and error pages instead of sending status messages. - Introduced `OAuthSuccess` and `OAuthError` components to provide user feedback during authentication. - Added localization support for success and error messages in the translation files. - Implemented countdown functionality in the success component for a better user experience. * fix: refresh token handling for user connections, add missing URL and methods - add standard enum for system user id and helper for determining app-lvel vs. user-level connections * refactor: update token handling in MCPManager and MCPTokenStorage * fix: improve error logging in OAuth authentication handler * fix: concurrency issues for both login url emission and concurrency of oauth flows for shared flows (same user, same server, multiple calls for same server) * fix: properly fail shared flows for concurrent server calls and prevent duplication of tokens * chore: remove unused auth package directory from update configuration * ci: fix mocks in samlStrategy tests * ci: add mcpConfig to AppService test setup * chore: remove obsolete MCP OAuth implementation documentation * fix: update build script for API to use correct command * chore: bump version of @librechat/api to 1.2.4 * fix: update abort signal handling in createMCPTool function * fix: add optional clientInfo parameter to refreshTokensFunction metadata * refactor: replace app.locals.availableTools with getCachedTools in multiple services and controllers for improved tool management * fix: concurrent refresh token handling issue * refactor: add signal parameter to getUserConnection method for improved abort handling * chore: JSDoc typing for `loadEphemeralAgent` * refactor: update isConnectionActive method to use destructured parameters for improved readability * feat: implement caching for MCP tools to handle app-level disconnects for loading list of tools * ci: fix agent test
2025-06-17 13:50:33 -04:00
const availableTools = await getCachedTools({ includeGlobal: true });
🔎 feat: Native Web Search with Citation References (#7516) * WIP: search tool integration * WIP: Add web search capabilities and API key management to agent actions * WIP: web search capability to agent configuration and selection * WIP: Add web search capability to backend agent configuration * WIP: add web search option to default agent form values * WIP: add attachments for web search * feat: add plugin for processing web search citations * WIP: first pass, Citation UI * chore: remove console.log * feat: Add AnimatedTabs component for tabbed UI functionality * refactor: AnimatedTabs component with CSS animations and stable ID generation * WIP example content * feat: SearchContext for managing search results apart from MessageContext * feat: Enhance AnimatedTabs with underline animation and state management * WIP: first pass, Implement dynamic tab functionality in Sources component with search results integration * fix: Update class names for improved styling in Sources and AnimatedTabs components * feat: Improve styling and layout in Sources component with enhanced button and item designs * feat: Refactor Sources component to integrate OGDialog for source display and improve layout * style: Update background color in SourceItem and SourcesGroup components for improved visibility * refactor: Sources component to enhance SourceItem structure and improve favicon handling * style: Adjust font size of domain text in SourceItem for better readability * feat: Add localization for citation source and details in CompositeCitation component * style: add theming to Citation components * feat: Enhance SourceItem component with dialog support and improved hovercard functionality * feat: Add localization for sources tab and image alt text in Sources component * style: Replace divs with spans for better semantic structure in CompositeCitation and Citation components * refactor: Sources component to use useMemo for tab generation and improve performance * chore: bump @librechat/agents to v2.4.318 * chore: update search result types * fix: search results retrieval in ContentParts component, re-render attachments when expected * feat: update sources style/types to use latest search result structure * style: enhance Dialog (expanded) SourceItem component with link wrapping and improved styling * style: update ImageItem component styling for improved title visibility * refactor: remove SourceItemBase component and adjust SourceItem layout for improved styling * chore: linting twcss order * fix: prevent FileAttachment from rendering search attachments * fix: append underscore to responseMessageId for unique identification to prevent mapping of previous latest message's attachments * chore: remove unused parameter 'useSpecs' from loadTools function * chore: twcss order * WIP: WebSearch Tool UI * refactor: add limit parameter to StackedFavicons for customizable source display * refactor: optimize search results memoization by making more granular and separate conerns * refactor: integrated StackedFavicons to WebSearch mid-run * chore: bump @librechat/agents to expose handleToolCallChunks * chore: use typedefs from dedicated file instead of defining them in AgentClient module * WIP: first pass, search progress results * refactor: move createOnSearchResults function to a dedicated search module * chore: bump @librechat/agents to v2.4.320 * WIP: first pass, search results processed UX * refactor: consolidate context variables in createOnSearchResults function * chore: bump @librechat/agents to v2.4.321 * feat: add guidelines for web search tool response formatting in loadTools function * feat: add isLast prop to Part component and update WebSearch logic for improved state handling * style: update Hovercard styles for improved UI consistency * feat: export FaviconImage component for improved accessibility in other modules * refactor: export getCleanDomain function and use FaviconImage in Citation component for improved source representation * refactor: implement SourceHovercard component for consistency and DRY compliance * fix: replace <p> with <span> for snippet and title in SourceItem and SourceHovercard for consistency * style: `not-prose` * style: remove 'not-prose' class for consistency in SourceItem, Citation, and SourceHovercard components, adjust style classes * refactor: `imageUrl` on hover and prevent duplicate sources * refactor: enhance SourcesGroup dialog layout and improve source item presentation * refactor: reorganize Web Components, save in same directory * feat: add 'news' refType to refTypeMap for citation sources * style: adjust Hovercard width for improved layout * refactor: update tool usage guidelines for improved clarity and execution * chore: linting * feat: add Web Search badge with initial permissions and local storage logic * feat: add webSearch support to interface and permissions schemas * feat: implement Web Search API key management and localization updates * feat: refactor Web Search API key handling and integrate new search API key form * fix: remove unnecessary visibility state from FileAttachment component * feat: update WebSearch component to use Globe icon and localized search label * feat: enhance ApiKeyDialog with dropdown for reranker selection and update translations * feat: implement dropdown menus for engine, scraper, and reranker selection in ApiKeyDialog * chore: linting and add unknown instead of `any` type * feat: refactor ApiKeyDialog and useAuthSearchTool for improved API key management * refactor: update ocrSchema to use template literals for default apiKey and baseURL * feat: add web search configuration and utility functions for environment variable extraction * fix: ensure filepath is defined before checking its prefix in useAttachmentHandler * feat: enhance web search functionality with improved configuration and environment variable extraction for authFields * fix: update auth type in TPluginAction and TUpdateUserPlugins to use Partial<Record<string, string>> * feat: implement web search authentication verification and enhance webSearchAuth structure * feat: enhance ephemeral agent handling with new web search capability and type definition * feat: enhance isEphemeralAgent function to include web search selection * feat: refactor verifyWebSearchAuth to improve key handling and authentication checks * feat: implement loadWebSearchAuth function for improved web search authentication handling * feat: enhance web search authentication with new configuration options and refactor related types * refactor: rename search engine to search provider and update related localization keys * feat: update verifyWebSearchAuth to handle multiple authentication types and improve error handling * feat: update ApiKeyDialog to accept authTypes prop and remove isUserProvided check * feat: add tests for extractWebSearchEnvVars and loadWebSearchAuth functions * feat: enhance loadWebSearchAuth to support specific service checks for providers, scrapers, and rerankers * fix: update web search configuration key and adjust auth result handling in loadTools function * feat: add new progress key for repeated web searching and update localization * chore: bump @librechat/agents to 2.4.322 * feat: enhance loadTools function to include ISO time and improve search tool logging * feat: update StackedFavicons to handle negative start index and improve citation attribution styling and text * chore: update .gitignore to categorize AI-related files * fix: mobile responsiveness of sources/citations hovercards * feat: enhance source display with improved line clamping for better readability * chore: bump @librechat/agents to v2.4.33 * feat: add handling for image sources in references mapping * chore: bump librechat-data-provider version to 0.7.84 * chore: bump @librechat/agents version to 2.4.34 * fix: update auth handling to support multiple auth types in tools and allow key configuration in agent panel * chore: remove redundant agent attribution text from search form * fix: web search auth uninstall * refactor: convert CheckboxButton to a forwardRef component and update setValue callback signature * feat: add triggerRef prop to ApiKeyDialog components for improved dialog control * feat: integrate triggerRef in CodeInterpreter and WebSearch components for enhanced dialog management * feat: enhance ApiKeyDialog with additional links for Firecrawl and Jina API key guidance * feat: implement web search configuration handling in ApiKeyDialog and add tests for dropdown visibility * fix: update webSearchConfig reference in config route for correct payload assignment * feat: update ApiKeyDialog to conditionally render sections based on authTypes and modify loadWebSearchAuth to correctly categorize authentication types * feat: refactor ApiKeyDialog and related tests to use SearchCategories and RerankerTypes enums and remove nested ternaries * refactor: move ThinkingButton rendering to improve layout consistency in ContentParts * feat: integrate search context into Markdown component to conditionally include unicodeCitation plugin * chore: bump @librechat/agents to v2.4.35 * chore: remove unused 18n key * ci: add WEB_SEARCH permission testing and update AppService tests for new webSearch configuration * ci: add more comprehensive tests for loadWebSearchAuth to validate authentication handling and authTypes structure * chore: remove debugging console log from web.spec.ts to clean up test output
2025-05-23 00:14:04 -04:00
/** @type {TEphemeralAgent | null} */
const ephemeralAgent = req.body.ephemeralAgent;
const mcpServers = new Set(ephemeralAgent?.mcp);
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
/** @type {string[]} */
const tools = [];
🔎 feat: Native Web Search with Citation References (#7516) * WIP: search tool integration * WIP: Add web search capabilities and API key management to agent actions * WIP: web search capability to agent configuration and selection * WIP: Add web search capability to backend agent configuration * WIP: add web search option to default agent form values * WIP: add attachments for web search * feat: add plugin for processing web search citations * WIP: first pass, Citation UI * chore: remove console.log * feat: Add AnimatedTabs component for tabbed UI functionality * refactor: AnimatedTabs component with CSS animations and stable ID generation * WIP example content * feat: SearchContext for managing search results apart from MessageContext * feat: Enhance AnimatedTabs with underline animation and state management * WIP: first pass, Implement dynamic tab functionality in Sources component with search results integration * fix: Update class names for improved styling in Sources and AnimatedTabs components * feat: Improve styling and layout in Sources component with enhanced button and item designs * feat: Refactor Sources component to integrate OGDialog for source display and improve layout * style: Update background color in SourceItem and SourcesGroup components for improved visibility * refactor: Sources component to enhance SourceItem structure and improve favicon handling * style: Adjust font size of domain text in SourceItem for better readability * feat: Add localization for citation source and details in CompositeCitation component * style: add theming to Citation components * feat: Enhance SourceItem component with dialog support and improved hovercard functionality * feat: Add localization for sources tab and image alt text in Sources component * style: Replace divs with spans for better semantic structure in CompositeCitation and Citation components * refactor: Sources component to use useMemo for tab generation and improve performance * chore: bump @librechat/agents to v2.4.318 * chore: update search result types * fix: search results retrieval in ContentParts component, re-render attachments when expected * feat: update sources style/types to use latest search result structure * style: enhance Dialog (expanded) SourceItem component with link wrapping and improved styling * style: update ImageItem component styling for improved title visibility * refactor: remove SourceItemBase component and adjust SourceItem layout for improved styling * chore: linting twcss order * fix: prevent FileAttachment from rendering search attachments * fix: append underscore to responseMessageId for unique identification to prevent mapping of previous latest message's attachments * chore: remove unused parameter 'useSpecs' from loadTools function * chore: twcss order * WIP: WebSearch Tool UI * refactor: add limit parameter to StackedFavicons for customizable source display * refactor: optimize search results memoization by making more granular and separate conerns * refactor: integrated StackedFavicons to WebSearch mid-run * chore: bump @librechat/agents to expose handleToolCallChunks * chore: use typedefs from dedicated file instead of defining them in AgentClient module * WIP: first pass, search progress results * refactor: move createOnSearchResults function to a dedicated search module * chore: bump @librechat/agents to v2.4.320 * WIP: first pass, search results processed UX * refactor: consolidate context variables in createOnSearchResults function * chore: bump @librechat/agents to v2.4.321 * feat: add guidelines for web search tool response formatting in loadTools function * feat: add isLast prop to Part component and update WebSearch logic for improved state handling * style: update Hovercard styles for improved UI consistency * feat: export FaviconImage component for improved accessibility in other modules * refactor: export getCleanDomain function and use FaviconImage in Citation component for improved source representation * refactor: implement SourceHovercard component for consistency and DRY compliance * fix: replace <p> with <span> for snippet and title in SourceItem and SourceHovercard for consistency * style: `not-prose` * style: remove 'not-prose' class for consistency in SourceItem, Citation, and SourceHovercard components, adjust style classes * refactor: `imageUrl` on hover and prevent duplicate sources * refactor: enhance SourcesGroup dialog layout and improve source item presentation * refactor: reorganize Web Components, save in same directory * feat: add 'news' refType to refTypeMap for citation sources * style: adjust Hovercard width for improved layout * refactor: update tool usage guidelines for improved clarity and execution * chore: linting * feat: add Web Search badge with initial permissions and local storage logic * feat: add webSearch support to interface and permissions schemas * feat: implement Web Search API key management and localization updates * feat: refactor Web Search API key handling and integrate new search API key form * fix: remove unnecessary visibility state from FileAttachment component * feat: update WebSearch component to use Globe icon and localized search label * feat: enhance ApiKeyDialog with dropdown for reranker selection and update translations * feat: implement dropdown menus for engine, scraper, and reranker selection in ApiKeyDialog * chore: linting and add unknown instead of `any` type * feat: refactor ApiKeyDialog and useAuthSearchTool for improved API key management * refactor: update ocrSchema to use template literals for default apiKey and baseURL * feat: add web search configuration and utility functions for environment variable extraction * fix: ensure filepath is defined before checking its prefix in useAttachmentHandler * feat: enhance web search functionality with improved configuration and environment variable extraction for authFields * fix: update auth type in TPluginAction and TUpdateUserPlugins to use Partial<Record<string, string>> * feat: implement web search authentication verification and enhance webSearchAuth structure * feat: enhance ephemeral agent handling with new web search capability and type definition * feat: enhance isEphemeralAgent function to include web search selection * feat: refactor verifyWebSearchAuth to improve key handling and authentication checks * feat: implement loadWebSearchAuth function for improved web search authentication handling * feat: enhance web search authentication with new configuration options and refactor related types * refactor: rename search engine to search provider and update related localization keys * feat: update verifyWebSearchAuth to handle multiple authentication types and improve error handling * feat: update ApiKeyDialog to accept authTypes prop and remove isUserProvided check * feat: add tests for extractWebSearchEnvVars and loadWebSearchAuth functions * feat: enhance loadWebSearchAuth to support specific service checks for providers, scrapers, and rerankers * fix: update web search configuration key and adjust auth result handling in loadTools function * feat: add new progress key for repeated web searching and update localization * chore: bump @librechat/agents to 2.4.322 * feat: enhance loadTools function to include ISO time and improve search tool logging * feat: update StackedFavicons to handle negative start index and improve citation attribution styling and text * chore: update .gitignore to categorize AI-related files * fix: mobile responsiveness of sources/citations hovercards * feat: enhance source display with improved line clamping for better readability * chore: bump @librechat/agents to v2.4.33 * feat: add handling for image sources in references mapping * chore: bump librechat-data-provider version to 0.7.84 * chore: bump @librechat/agents version to 2.4.34 * fix: update auth handling to support multiple auth types in tools and allow key configuration in agent panel * chore: remove redundant agent attribution text from search form * fix: web search auth uninstall * refactor: convert CheckboxButton to a forwardRef component and update setValue callback signature * feat: add triggerRef prop to ApiKeyDialog components for improved dialog control * feat: integrate triggerRef in CodeInterpreter and WebSearch components for enhanced dialog management * feat: enhance ApiKeyDialog with additional links for Firecrawl and Jina API key guidance * feat: implement web search configuration handling in ApiKeyDialog and add tests for dropdown visibility * fix: update webSearchConfig reference in config route for correct payload assignment * feat: update ApiKeyDialog to conditionally render sections based on authTypes and modify loadWebSearchAuth to correctly categorize authentication types * feat: refactor ApiKeyDialog and related tests to use SearchCategories and RerankerTypes enums and remove nested ternaries * refactor: move ThinkingButton rendering to improve layout consistency in ContentParts * feat: integrate search context into Markdown component to conditionally include unicodeCitation plugin * chore: bump @librechat/agents to v2.4.35 * chore: remove unused 18n key * ci: add WEB_SEARCH permission testing and update AppService tests for new webSearch configuration * ci: add more comprehensive tests for loadWebSearchAuth to validate authentication handling and authTypes structure * chore: remove debugging console log from web.spec.ts to clean up test output
2025-05-23 00:14:04 -04:00
if (ephemeralAgent?.execute_code === true) {
tools.push(Tools.execute_code);
}
🤖 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 69b699739671e740820f570ddb83d1caa0dbd6e4. * 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
if (ephemeralAgent?.file_search === true) {
tools.push(Tools.file_search);
}
🔎 feat: Native Web Search with Citation References (#7516) * WIP: search tool integration * WIP: Add web search capabilities and API key management to agent actions * WIP: web search capability to agent configuration and selection * WIP: Add web search capability to backend agent configuration * WIP: add web search option to default agent form values * WIP: add attachments for web search * feat: add plugin for processing web search citations * WIP: first pass, Citation UI * chore: remove console.log * feat: Add AnimatedTabs component for tabbed UI functionality * refactor: AnimatedTabs component with CSS animations and stable ID generation * WIP example content * feat: SearchContext for managing search results apart from MessageContext * feat: Enhance AnimatedTabs with underline animation and state management * WIP: first pass, Implement dynamic tab functionality in Sources component with search results integration * fix: Update class names for improved styling in Sources and AnimatedTabs components * feat: Improve styling and layout in Sources component with enhanced button and item designs * feat: Refactor Sources component to integrate OGDialog for source display and improve layout * style: Update background color in SourceItem and SourcesGroup components for improved visibility * refactor: Sources component to enhance SourceItem structure and improve favicon handling * style: Adjust font size of domain text in SourceItem for better readability * feat: Add localization for citation source and details in CompositeCitation component * style: add theming to Citation components * feat: Enhance SourceItem component with dialog support and improved hovercard functionality * feat: Add localization for sources tab and image alt text in Sources component * style: Replace divs with spans for better semantic structure in CompositeCitation and Citation components * refactor: Sources component to use useMemo for tab generation and improve performance * chore: bump @librechat/agents to v2.4.318 * chore: update search result types * fix: search results retrieval in ContentParts component, re-render attachments when expected * feat: update sources style/types to use latest search result structure * style: enhance Dialog (expanded) SourceItem component with link wrapping and improved styling * style: update ImageItem component styling for improved title visibility * refactor: remove SourceItemBase component and adjust SourceItem layout for improved styling * chore: linting twcss order * fix: prevent FileAttachment from rendering search attachments * fix: append underscore to responseMessageId for unique identification to prevent mapping of previous latest message's attachments * chore: remove unused parameter 'useSpecs' from loadTools function * chore: twcss order * WIP: WebSearch Tool UI * refactor: add limit parameter to StackedFavicons for customizable source display * refactor: optimize search results memoization by making more granular and separate conerns * refactor: integrated StackedFavicons to WebSearch mid-run * chore: bump @librechat/agents to expose handleToolCallChunks * chore: use typedefs from dedicated file instead of defining them in AgentClient module * WIP: first pass, search progress results * refactor: move createOnSearchResults function to a dedicated search module * chore: bump @librechat/agents to v2.4.320 * WIP: first pass, search results processed UX * refactor: consolidate context variables in createOnSearchResults function * chore: bump @librechat/agents to v2.4.321 * feat: add guidelines for web search tool response formatting in loadTools function * feat: add isLast prop to Part component and update WebSearch logic for improved state handling * style: update Hovercard styles for improved UI consistency * feat: export FaviconImage component for improved accessibility in other modules * refactor: export getCleanDomain function and use FaviconImage in Citation component for improved source representation * refactor: implement SourceHovercard component for consistency and DRY compliance * fix: replace <p> with <span> for snippet and title in SourceItem and SourceHovercard for consistency * style: `not-prose` * style: remove 'not-prose' class for consistency in SourceItem, Citation, and SourceHovercard components, adjust style classes * refactor: `imageUrl` on hover and prevent duplicate sources * refactor: enhance SourcesGroup dialog layout and improve source item presentation * refactor: reorganize Web Components, save in same directory * feat: add 'news' refType to refTypeMap for citation sources * style: adjust Hovercard width for improved layout * refactor: update tool usage guidelines for improved clarity and execution * chore: linting * feat: add Web Search badge with initial permissions and local storage logic * feat: add webSearch support to interface and permissions schemas * feat: implement Web Search API key management and localization updates * feat: refactor Web Search API key handling and integrate new search API key form * fix: remove unnecessary visibility state from FileAttachment component * feat: update WebSearch component to use Globe icon and localized search label * feat: enhance ApiKeyDialog with dropdown for reranker selection and update translations * feat: implement dropdown menus for engine, scraper, and reranker selection in ApiKeyDialog * chore: linting and add unknown instead of `any` type * feat: refactor ApiKeyDialog and useAuthSearchTool for improved API key management * refactor: update ocrSchema to use template literals for default apiKey and baseURL * feat: add web search configuration and utility functions for environment variable extraction * fix: ensure filepath is defined before checking its prefix in useAttachmentHandler * feat: enhance web search functionality with improved configuration and environment variable extraction for authFields * fix: update auth type in TPluginAction and TUpdateUserPlugins to use Partial<Record<string, string>> * feat: implement web search authentication verification and enhance webSearchAuth structure * feat: enhance ephemeral agent handling with new web search capability and type definition * feat: enhance isEphemeralAgent function to include web search selection * feat: refactor verifyWebSearchAuth to improve key handling and authentication checks * feat: implement loadWebSearchAuth function for improved web search authentication handling * feat: enhance web search authentication with new configuration options and refactor related types * refactor: rename search engine to search provider and update related localization keys * feat: update verifyWebSearchAuth to handle multiple authentication types and improve error handling * feat: update ApiKeyDialog to accept authTypes prop and remove isUserProvided check * feat: add tests for extractWebSearchEnvVars and loadWebSearchAuth functions * feat: enhance loadWebSearchAuth to support specific service checks for providers, scrapers, and rerankers * fix: update web search configuration key and adjust auth result handling in loadTools function * feat: add new progress key for repeated web searching and update localization * chore: bump @librechat/agents to 2.4.322 * feat: enhance loadTools function to include ISO time and improve search tool logging * feat: update StackedFavicons to handle negative start index and improve citation attribution styling and text * chore: update .gitignore to categorize AI-related files * fix: mobile responsiveness of sources/citations hovercards * feat: enhance source display with improved line clamping for better readability * chore: bump @librechat/agents to v2.4.33 * feat: add handling for image sources in references mapping * chore: bump librechat-data-provider version to 0.7.84 * chore: bump @librechat/agents version to 2.4.34 * fix: update auth handling to support multiple auth types in tools and allow key configuration in agent panel * chore: remove redundant agent attribution text from search form * fix: web search auth uninstall * refactor: convert CheckboxButton to a forwardRef component and update setValue callback signature * feat: add triggerRef prop to ApiKeyDialog components for improved dialog control * feat: integrate triggerRef in CodeInterpreter and WebSearch components for enhanced dialog management * feat: enhance ApiKeyDialog with additional links for Firecrawl and Jina API key guidance * feat: implement web search configuration handling in ApiKeyDialog and add tests for dropdown visibility * fix: update webSearchConfig reference in config route for correct payload assignment * feat: update ApiKeyDialog to conditionally render sections based on authTypes and modify loadWebSearchAuth to correctly categorize authentication types * feat: refactor ApiKeyDialog and related tests to use SearchCategories and RerankerTypes enums and remove nested ternaries * refactor: move ThinkingButton rendering to improve layout consistency in ContentParts * feat: integrate search context into Markdown component to conditionally include unicodeCitation plugin * chore: bump @librechat/agents to v2.4.35 * chore: remove unused 18n key * ci: add WEB_SEARCH permission testing and update AppService tests for new webSearch configuration * ci: add more comprehensive tests for loadWebSearchAuth to validate authentication handling and authTypes structure * chore: remove debugging console log from web.spec.ts to clean up test output
2025-05-23 00:14:04 -04:00
if (ephemeralAgent?.web_search === true) {
tools.push(Tools.web_search);
}
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
if (mcpServers.size > 0) {
for (const toolName of Object.keys(availableTools)) {
if (!toolName.includes(mcp_delimiter)) {
continue;
}
const mcpServer = toolName.split(mcp_delimiter)?.[1];
if (mcpServer && mcpServers.has(mcpServer)) {
tools.push(toolName);
}
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
}
}
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
const instructions = req.body.promptPrefix;
return {
id: agent_id,
instructions,
provider: endpoint,
model_parameters,
model,
tools,
};
};
/**
* Load an agent based on the provided ID
*
* @param {Object} params
* @param {ServerRequest} params.req
* @param {string} params.agent_id
* @param {string} params.endpoint
* @param {import('@librechat/agents').ClientOptions} [params.model_parameters]
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
* @returns {Promise<Agent|null>} The agent document as a plain object, or null if not found.
*/
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
const loadAgent = async ({ req, agent_id, endpoint, model_parameters }) => {
if (!agent_id) {
return null;
}
if (agent_id === EPHEMERAL_AGENT_ID) {
🪐 feat: MCP OAuth 2.0 Discovery Support (#7924) * chore: Update @modelcontextprotocol/sdk to version 1.12.3 in package.json and package-lock.json - Bump version of @modelcontextprotocol/sdk to 1.12.3 to incorporate recent updates. - Update dependencies for ajv and cross-spawn to their latest versions. - Add ajv as a new dependency in the sdk module. - Include json-schema-traverse as a new dependency in the sdk module. * feat: @librechat/auth * feat: Add crypto module exports to auth package - Introduced a new crypto module by creating index.ts in the crypto directory. - Updated the main index.ts of the auth package to export from the new crypto module. * feat: Update package dependencies and build scripts for auth package - Added @librechat/auth as a dependency in package.json and package-lock.json. - Updated build scripts to include the auth package in both frontend and bun build processes. - Removed unused mongoose and openid-client dependencies from package-lock.json for cleaner dependency management. * refactor: Migrate crypto utility functions to @librechat/auth - Replaced local crypto utility imports with the new @librechat/auth package across multiple files. - Removed the obsolete crypto.js file and its exports. - Updated relevant services and models to utilize the new encryption and decryption methods from @librechat/auth. * feat: Enhance OAuth token handling and update dependencies in auth package * chore: Remove Token model and TokenService due to restructuring of OAuth handling - Deleted the Token.js model and TokenService.js, which were responsible for managing OAuth tokens. - This change is part of a broader refactor to streamline OAuth token management and improve code organization. * refactor: imports from '@librechat/auth' to '@librechat/api' and add OAuth token handling functionality * refactor: Simplify logger usage in MCP and FlowStateManager classes * chore: fix imports * feat: Add OAuth configuration schema to MCP with token exchange method support * feat: FIRST PASS Implement MCP OAuth flow with token management and error handling - Added a new route for handling OAuth callbacks and token retrieval. - Integrated OAuth token storage and retrieval mechanisms. - Enhanced MCP connection to support automatic OAuth flow initiation on 401 errors. - Implemented dynamic client registration and metadata discovery for OAuth. - Updated MCPManager to manage OAuth tokens and handle authentication requirements. - Introduced comprehensive logging for OAuth processes and error handling. * refactor: Update MCPConnection and MCPManager to utilize new URL handling - Added a `url` property to MCPConnection for better URL management. - Refactored MCPManager to use the new `url` property instead of a deprecated method for OAuth handling. - Changed logging from info to debug level for flow manager and token methods initialization. - Improved comments for clarity on existing tokens and OAuth event listener setup. * refactor: Improve connection timeout error messages in MCPConnection and MCPManager and use initTimeout for connection - Updated the connection timeout error messages to include the duration of the timeout. - Introduced a configurable `connectTimeout` variable in both MCPConnection and MCPManager for better flexibility. * chore: cleanup MCP OAuth Token exchange handling; fix: erroneous use of flowsCache and remove verbose logs * refactor: Update MCPManager and MCPTokenStorage to use TokenMethods for token management - Removed direct token storage handling in MCPManager and replaced it with TokenMethods for better abstraction. - Refactored MCPTokenStorage methods to accept parameters for token operations, enhancing flexibility and readability. - Improved logging messages related to token persistence and retrieval processes. * refactor: Update MCP OAuth handling to use static methods and improve flow management - Refactored MCPOAuthHandler to utilize static methods for initiating and completing OAuth flows, enhancing clarity and reducing instance dependencies. - Updated MCPManager to pass flowManager explicitly to OAuth handling methods, improving flexibility in flow state management. - Enhanced comments and logging for better understanding of OAuth processes and flow state retrieval. * refactor: Integrate token methods into createMCPTool for enhanced token management * refactor: Change logging from info to debug level in MCPOAuthHandler for improved log management * chore: clean up logging * feat: first pass, auth URL from MCP OAuth flow * chore: Improve logging format for OAuth authentication URL display * chore: cleanup mcp manager comments * feat: add connection reconnection logic in MCPManager * refactor: reorganize token storage handling in MCP - Moved token storage logic from MCPManager to a new MCPTokenStorage class for better separation of concerns. - Updated imports to reflect the new token storage structure. - Enhanced methods for storing, retrieving, updating, and deleting OAuth tokens, improving overall token management. * chore: update comment for SYSTEM_USER_ID in MCPManager for clarity * feat: implement refresh token functionality in MCP - Added refresh token handling in MCPManager to support token renewal for both app-level and user-specific connections. - Introduced a refreshTokens function to facilitate token refresh logic. - Enhanced MCPTokenStorage to manage client information and refresh token processes. - Updated logging for better traceability during token operations. * chore: cleanup @librechat/auth * feat: implement MCP server initialization in a separate service - Added a new service to handle the initialization of MCP servers, improving code organization and readability. - Refactored the server startup logic to utilize the new initializeMCP function. - Removed redundant MCP initialization code from the main server file. * fix: don't log auth url for user connections * feat: enhance OAuth flow with success and error handling components - Updated OAuth callback routes to redirect to new success and error pages instead of sending status messages. - Introduced `OAuthSuccess` and `OAuthError` components to provide user feedback during authentication. - Added localization support for success and error messages in the translation files. - Implemented countdown functionality in the success component for a better user experience. * fix: refresh token handling for user connections, add missing URL and methods - add standard enum for system user id and helper for determining app-lvel vs. user-level connections * refactor: update token handling in MCPManager and MCPTokenStorage * fix: improve error logging in OAuth authentication handler * fix: concurrency issues for both login url emission and concurrency of oauth flows for shared flows (same user, same server, multiple calls for same server) * fix: properly fail shared flows for concurrent server calls and prevent duplication of tokens * chore: remove unused auth package directory from update configuration * ci: fix mocks in samlStrategy tests * ci: add mcpConfig to AppService test setup * chore: remove obsolete MCP OAuth implementation documentation * fix: update build script for API to use correct command * chore: bump version of @librechat/api to 1.2.4 * fix: update abort signal handling in createMCPTool function * fix: add optional clientInfo parameter to refreshTokensFunction metadata * refactor: replace app.locals.availableTools with getCachedTools in multiple services and controllers for improved tool management * fix: concurrent refresh token handling issue * refactor: add signal parameter to getUserConnection method for improved abort handling * chore: JSDoc typing for `loadEphemeralAgent` * refactor: update isConnectionActive method to use destructured parameters for improved readability * feat: implement caching for MCP tools to handle app-level disconnects for loading list of tools * ci: fix agent test
2025-06-17 13:50:33 -04:00
return await loadEphemeralAgent({ req, agent_id, endpoint, model_parameters });
🔦 feat: MCP Support for Non-Agent Endpoints (#6775) * wip: mcp select * refactor: Update useAvailableToolsQuery to support generic data types * feat: Enhance MCPSelect to dynamically load server options and improve MultiSelect component styling * WIP: ephemeral agents * wip: Add null check for MCPSelect and improve MultiSelect focus handling * feat: Pass conversationId prop to MCPSelect in BadgeRow to optimize badge rendering * feat: useApplyNewAgentTemplate hook to manage ephemeral agent upon conversation creation * WIP: eph. agent payload * refactor(OpenAIClient): streamline message processing by replacing content handling with parseTextParts function * feat: enhance applyAgentTemplate function to accept source conversation ID for improved template application * feat(parsers): add skipReasoning parameter to parseTextParts for conditional reasoning handling * WIP: first pass, ephemeral agent backend processing * chore: import order * feat: update loadEphemeralAgent and loadAgent functions to accept model_parameters for enhanced agent configuration * feat: add showMCPServers prop to BadgeRow for conditional rendering of MCPSelect, fix react rule violation * feat: enhance MCPSelect with localized placeholder and custom icon, add renderSelectedValues callback * feat: simplify message processing in AnthropicClient by replacing content handling with parseTextParts function * feat: implement useLocalStorage hook for managing MCP values and update MCPSelect to utilize it * chore: remove chatGPTBrowserSchema from endpoint schemas and update types for improved schema management * chore: remove compactChatGPTSchema from endpoint schemas and update types for better schema management * refactor: rename schemas for clarity and improve schema management * feat: extend model detection to include 'codestral' alongside 'mistral' * feat: add endpointType parameter to buildOptions and initializeClient functions * fix: update condition for handling completion in BaseClient to include agents client * refactor: simplify payload parsing logic in AgentClient and remove unused providerParsers * refactor: change useSetRecoilState to useRecoilState for better state management in MCPSelect component * refactor: streamline chat route handlers by consolidating middleware and improving endpoint structure * style: update MCPSelect and MultiSelect components for improved layout in mobile view * v0.7.790 * feat: add getMessageMapMethod to process message text and content in GoogleClient * chore: include LAST_MCP_ key prefix in clearLocalStorage function for proper teardown on logout
2025-04-07 19:16:56 -04:00
}
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const agent = await getAgent({
id: agent_id,
});
🔧 refactor: Consolidate Logging, Model Selection & Actions Optimizations, Minor Fixes (#6553) * 🔧 feat: Enhance logging configuration for production and debug environments * 🔒 feat: Implement encryption and decryption functions for sensitive values in ActionService with URL encoding/decoding * refactor: optimize action service for agent tools * refactor: optimize action processing for Assistants API * fix: handle case where agent is not found in loadAgent function * refactor: improve error handling in API calls by throwing new Error with logAxiosError output * chore: bump @librechat/agents to 2.3.95, fixes "Invalid tool call structure: No preceding AIMessage with tool_call_ids" * refactor: enhance error logging in logAxiosError function to include response status * refactor: remove unused useModelSelection hook from Endpoint * refactor: add support for assistants in useSelectorEffects hook * refactor: replace string easing with imported easings in Landing component * chore: remove duplicate translation * refactor: update model selection logic and improve localization for UI elements * refactor: replace endpoint value checks with helper functions for agents and assistants * refactor: optimize display value logic and utilize useMemo for performance improvements * refactor: clean up imports and optimize display/icon value logic in endpoint components, fix spec selection * refactor: enhance error logging in axios utility to include stack traces for better debugging * refactor: update logging configuration to use DEBUG_LOGGING and streamline log level handling * refactor: adjust className for export menu button to improve layout consistency and remove unused title prop from ShareButton * refactor: update import path for logAxiosError utility to improve module organization and clarity * refactor: implement debounced search value setter in ModelSelectorContext for improved performance
2025-03-26 14:10:52 -04:00
if (!agent) {
return null;
}
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
agent.version = agent.versions ? agent.versions.length : 0;
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
if (agent.author.toString() === req.user.id) {
return agent;
}
if (!agent.projectIds) {
return null;
}
const cache = getLogStores(CONFIG_STORE);
/** @type {TStartupConfig} */
const cachedStartupConfig = await cache.get(STARTUP_CONFIG);
let { instanceProjectId } = cachedStartupConfig ?? {};
if (!instanceProjectId) {
instanceProjectId = (await getProjectByName(GLOBAL_PROJECT_NAME, '_id'))._id.toString();
}
for (const projectObjectId of agent.projectIds) {
const projectId = projectObjectId.toString();
if (projectId === instanceProjectId) {
return agent;
}
}
};
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
/**
* Check if a version already exists in the versions array, excluding timestamp and author fields
* @param {Object} updateData - The update data to compare
* @param {Object} currentData - The current agent data
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
* @param {Array} versions - The existing versions array
* @param {string} [actionsHash] - Hash of current action metadata
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
* @returns {Object|null} - The matching version if found, null otherwise
*/
const isDuplicateVersion = (updateData, currentData, versions, actionsHash = null) => {
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
if (!versions || versions.length === 0) {
return null;
}
const excludeFields = [
'_id',
'id',
'createdAt',
'updatedAt',
'author',
'updatedBy',
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
'created_at',
'updated_at',
'__v',
'versions',
'actionsHash', // Exclude actionsHash from direct comparison
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
];
const { $push, $pull, $addToSet, ...directUpdates } = updateData;
if (Object.keys(directUpdates).length === 0 && !actionsHash) {
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
return null;
}
const wouldBeVersion = { ...currentData, ...directUpdates };
const lastVersion = versions[versions.length - 1];
if (actionsHash && lastVersion.actionsHash !== actionsHash) {
return null;
}
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
const allFields = new Set([...Object.keys(wouldBeVersion), ...Object.keys(lastVersion)]);
const importantFields = Array.from(allFields).filter((field) => !excludeFields.includes(field));
let isMatch = true;
for (const field of importantFields) {
if (!wouldBeVersion[field] && !lastVersion[field]) {
continue;
}
if (Array.isArray(wouldBeVersion[field]) && Array.isArray(lastVersion[field])) {
if (wouldBeVersion[field].length !== lastVersion[field].length) {
isMatch = false;
break;
}
// Special handling for projectIds (MongoDB ObjectIds)
if (field === 'projectIds') {
const wouldBeIds = wouldBeVersion[field].map((id) => id.toString()).sort();
const versionIds = lastVersion[field].map((id) => id.toString()).sort();
if (!wouldBeIds.every((id, i) => id === versionIds[i])) {
isMatch = false;
break;
}
}
// Handle arrays of objects like tool_kwargs
else if (typeof wouldBeVersion[field][0] === 'object' && wouldBeVersion[field][0] !== null) {
const sortedWouldBe = [...wouldBeVersion[field]].map((item) => JSON.stringify(item)).sort();
const sortedVersion = [...lastVersion[field]].map((item) => JSON.stringify(item)).sort();
if (!sortedWouldBe.every((item, i) => item === sortedVersion[i])) {
isMatch = false;
break;
}
} else {
const sortedWouldBe = [...wouldBeVersion[field]].sort();
const sortedVersion = [...lastVersion[field]].sort();
if (!sortedWouldBe.every((item, i) => item === sortedVersion[i])) {
isMatch = false;
break;
}
}
} else if (field === 'model_parameters') {
const wouldBeParams = wouldBeVersion[field] || {};
const lastVersionParams = lastVersion[field] || {};
if (JSON.stringify(wouldBeParams) !== JSON.stringify(lastVersionParams)) {
isMatch = false;
break;
}
} else if (wouldBeVersion[field] !== lastVersion[field]) {
isMatch = false;
break;
}
}
return isMatch ? lastVersion : null;
};
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
/**
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
* Update an agent with new data without overwriting existing
* properties, or create a new agent if it doesn't exist.
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
* When an agent is updated, a copy of the current state will be saved to the versions array.
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
*
* @param {Object} searchParameter - The search parameters to find the agent to update.
* @param {string} searchParameter.id - The ID of the agent to update.
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
* @param {string} [searchParameter.author] - The user ID of the agent's author.
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
* @param {Object} updateData - An object containing the properties to update.
* @param {Object} [options] - Optional configuration object.
* @param {string} [options.updatingUserId] - The ID of the user performing the update (used for tracking non-author updates).
* @param {boolean} [options.forceVersion] - Force creation of a new version even if no fields changed.
* @param {boolean} [options.skipVersioning] - Skip version creation entirely (useful for isolated operations like sharing).
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
* @returns {Promise<Agent>} The updated or newly created agent document as a plain object.
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
* @throws {Error} If the update would create a duplicate version
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
*/
const updateAgent = async (searchParameter, updateData, options = {}) => {
const { updatingUserId = null, forceVersion = false, skipVersioning = false } = options;
const mongoOptions = { new: true, upsert: false };
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
const currentAgent = await Agent.findOne(searchParameter);
if (currentAgent) {
const { __v, _id, id, versions, author, ...versionData } = currentAgent.toObject();
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
const { $push, $pull, $addToSet, ...directUpdates } = updateData;
let actionsHash = null;
// Generate actions hash if agent has actions
if (currentAgent.actions && currentAgent.actions.length > 0) {
// Extract action IDs from the format "domain_action_id"
const actionIds = currentAgent.actions
.map((action) => {
const parts = action.split(actionDelimiter);
return parts[1]; // Get just the action ID part
})
.filter(Boolean);
if (actionIds.length > 0) {
try {
const actions = await getActions(
{
action_id: { $in: actionIds },
},
true,
); // Include sensitive data for hash
actionsHash = await generateActionMetadataHash(currentAgent.actions, actions);
} catch (error) {
logger.error('Error fetching actions for hash generation:', error);
}
}
}
const shouldCreateVersion =
!skipVersioning &&
(forceVersion || Object.keys(directUpdates).length > 0 || $push || $pull || $addToSet);
if (shouldCreateVersion) {
const duplicateVersion = isDuplicateVersion(updateData, versionData, versions, actionsHash);
if (duplicateVersion && !forceVersion) {
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
const error = new Error(
'Duplicate version: This would create a version identical to an existing one',
);
error.statusCode = 409;
error.details = {
duplicateVersion,
versionIndex: versions.findIndex(
(v) => JSON.stringify(duplicateVersion) === JSON.stringify(v),
),
};
throw error;
}
}
const versionEntry = {
...versionData,
...directUpdates,
updatedAt: new Date(),
};
// Include actions hash in version if available
if (actionsHash) {
versionEntry.actionsHash = actionsHash;
}
// Always store updatedBy field to track who made the change
if (updatingUserId) {
versionEntry.updatedBy = new mongoose.Types.ObjectId(updatingUserId);
}
if (shouldCreateVersion) {
updateData.$push = {
...($push || {}),
versions: versionEntry,
};
}
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
}
return Agent.findOneAndUpdate(searchParameter, updateData, mongoOptions).lean();
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
};
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
/**
* Modifies an agent with the resource file id.
* @param {object} params
* @param {ServerRequest} params.req
* @param {string} params.agent_id
* @param {string} params.tool_resource
* @param {string} params.file_id
* @returns {Promise<Agent>} The updated agent.
*/
const addAgentResourceFile = async ({ req, agent_id, tool_resource, file_id }) => {
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const searchParameter = { id: agent_id };
let agent = await getAgent(searchParameter);
if (!agent) {
throw new Error('Agent not found for adding resource file');
}
const fileIdsPath = `tool_resources.${tool_resource}.file_ids`;
await Agent.updateOne(
{
id: agent_id,
[`${fileIdsPath}`]: { $exists: false },
},
{
$set: {
[`${fileIdsPath}`]: [],
},
},
);
const updateData = {
$addToSet: {
tools: tool_resource,
[fileIdsPath]: file_id,
},
};
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const updatedAgent = await updateAgent(searchParameter, updateData, {
updatingUserId: req?.user?.id,
});
if (updatedAgent) {
return updatedAgent;
} else {
throw new Error('Agent not found for adding resource file');
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
}
};
/**
* Removes multiple resource files from an agent using atomic operations.
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
* @param {object} params
* @param {string} params.agent_id
🎉 feat: Code Interpreter API and Agents Release (#4860) * feat: Code Interpreter API & File Search Agent Uploads chore: add back code files wip: first pass, abstract key dialog refactor: influence checkbox on key changes refactor: update localization keys for 'execute code' to 'run code' wip: run code button refactor: add throwError parameter to loadAuthValues and getUserPluginAuthValue functions feat: first pass, API tool calling fix: handle missing toolId in callTool function and return 404 for non-existent tools feat: show code outputs fix: improve error handling in callTool function and log errors fix: handle potential null value for filepath in attachment destructuring fix: normalize language before rendering and prevent null return fix: add loading indicator in RunCode component while executing code feat: add support for conditional code execution in Markdown components feat: attachments refactor: remove bash fix: pass abort signal to graph/run refactor: debounce and rate limit tool call refactor: increase debounce delay for execute function feat: set code output attachments feat: image attachments refactor: apply message context refactor: pass `partIndex` feat: toolCall schema/model/methods feat: block indexing feat: get tool calls chore: imports chore: typing chore: condense type imports feat: get tool calls fix: block indexing chore: typing refactor: update tool calls mapping to support multiple results fix: add unique key to nav link for rendering wip: first pass, tool call results refactor: update query cache from successful tool call mutation style: improve result switcher styling chore: note on using \`.toObject()\` feat: add agent_id field to conversation schema chore: typing refactor: rename agentMap to agentsMap for consistency feat: Agent Name as chat input placeholder chore: bump agents 📦 chore: update @langchain dependencies to latest versions to match agents package 📦 chore: update @librechat/agents dependency to version 1.8.0 fix: Aborting agent stream removes sender; fix(bedrock): completion removes preset name label refactor: remove direct file parameter to use req.file, add `processAgentFileUpload` for image uploads feat: upload menu feat: prime message_file resources feat: implement conversation access validation in chat route refactor: remove file parameter from processFileUpload and use req.file instead feat: add savedMessageIds set to track saved message IDs in BaseClient, to prevent unnecessary double-write to db feat: prevent duplicate message saves by checking savedMessageIds in AgentController refactor: skip legacy RAG API handling for agents feat: add files field to convoSchema refactor: update request type annotations from Express.Request to ServerRequest in file processing functions feat: track conversation files fix: resendFiles, addPreviousAttachments handling feat: add ID validation for session_id and file_id in download route feat: entity_id for code file uploads/downloads fix: code file edge cases feat: delete related tool calls feat: add stream rate handling for LLM configuration feat: enhance system content with attached file information fix: improve error logging in resource priming function * WIP: PoC, sequential agents WIP: PoC Sequential Agents, first pass content data + bump agents package fix: package-lock WIP: PoC, o1 support, refactor bufferString feat: convertJsonSchemaToZod fix: form issues and schema defining erroneous model fix: max length issue on agent form instructions, limit conversation messages to sequential agents feat: add abort signal support to createRun function and AgentClient feat: PoC, hide prior sequential agent steps fix: update parameter naming from config to metadata in event handlers for clarity, add model to usage data refactor: use only last contentData, track model for usage data chore: bump agents package fix: content parts issue refactor: filter contentParts to include tool calls and relevant indices feat: show function calls refactor: filter context messages to exclude tool calls when no tools are available to the agent fix: ensure tool call content is not undefined in formatMessages feat: add agent_id field to conversationPreset schema feat: hide sequential agents feat: increase upload toast duration to 10 seconds * refactor: tool context handling & update Code API Key Dialog feat: toolContextMap chore: skipSpecs -> useSpecs ci: fix handleTools tests feat: API Key Dialog * feat: Agent Permissions Admin Controls feat: replace label with button for prompt permission toggle feat: update agent permissions feat: enable experimental agents and streamline capability configuration feat: implement access control for agents and enhance endpoint menu items feat: add welcome message for agent selection in localization feat: add agents permission to access control and update version to 0.7.57 * fix: update types in useAssistantListMap and useMentions hooks for better null handling * feat: mention agents * fix: agent tool resource race conditions when deleting agent tool resource files * feat: add error handling for code execution with user feedback * refactor: rename AdminControls to AdminSettings for clarity * style: add gap to button in AdminSettings for improved layout * refactor: separate agent query hooks and check access to enable fetching * fix: remove unused provider from agent initialization options, creates issue with custom endpoints * refactor: remove redundant/deprecated modelOptions from AgentClient processes * chore: update @librechat/agents to version 1.8.5 in package.json and package-lock.json * fix: minor styling issues + agent panel uniformity * fix: agent edge cases when set endpoint is no longer defined * refactor: remove unused cleanup function call from AppService * fix: update link in ApiKeyDialog to point to pricing page * fix: improve type handling and layout calculations in SidePanel component * fix: add missing localization string for agent selection in SidePanel * chore: form styling and localizations for upload filesearch/code interpreter * fix: model selection placeholder logic in AgentConfig component * style: agent capabilities * fix: add localization for provider selection and improve dropdown styling in ModelPanel * refactor: use gpt-4o-mini > gpt-3.5-turbo * fix: agents configuration for loadDefaultInterface and update related tests * feat: DALLE Agents support
2024-12-04 15:48:13 -05:00
* @param {Array<{tool_resource: string, file_id: string}>} params.files
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
* @returns {Promise<Agent>} The updated agent.
* @throws {Error} If the agent is not found or update fails.
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
*/
🎉 feat: Code Interpreter API and Agents Release (#4860) * feat: Code Interpreter API & File Search Agent Uploads chore: add back code files wip: first pass, abstract key dialog refactor: influence checkbox on key changes refactor: update localization keys for 'execute code' to 'run code' wip: run code button refactor: add throwError parameter to loadAuthValues and getUserPluginAuthValue functions feat: first pass, API tool calling fix: handle missing toolId in callTool function and return 404 for non-existent tools feat: show code outputs fix: improve error handling in callTool function and log errors fix: handle potential null value for filepath in attachment destructuring fix: normalize language before rendering and prevent null return fix: add loading indicator in RunCode component while executing code feat: add support for conditional code execution in Markdown components feat: attachments refactor: remove bash fix: pass abort signal to graph/run refactor: debounce and rate limit tool call refactor: increase debounce delay for execute function feat: set code output attachments feat: image attachments refactor: apply message context refactor: pass `partIndex` feat: toolCall schema/model/methods feat: block indexing feat: get tool calls chore: imports chore: typing chore: condense type imports feat: get tool calls fix: block indexing chore: typing refactor: update tool calls mapping to support multiple results fix: add unique key to nav link for rendering wip: first pass, tool call results refactor: update query cache from successful tool call mutation style: improve result switcher styling chore: note on using \`.toObject()\` feat: add agent_id field to conversation schema chore: typing refactor: rename agentMap to agentsMap for consistency feat: Agent Name as chat input placeholder chore: bump agents 📦 chore: update @langchain dependencies to latest versions to match agents package 📦 chore: update @librechat/agents dependency to version 1.8.0 fix: Aborting agent stream removes sender; fix(bedrock): completion removes preset name label refactor: remove direct file parameter to use req.file, add `processAgentFileUpload` for image uploads feat: upload menu feat: prime message_file resources feat: implement conversation access validation in chat route refactor: remove file parameter from processFileUpload and use req.file instead feat: add savedMessageIds set to track saved message IDs in BaseClient, to prevent unnecessary double-write to db feat: prevent duplicate message saves by checking savedMessageIds in AgentController refactor: skip legacy RAG API handling for agents feat: add files field to convoSchema refactor: update request type annotations from Express.Request to ServerRequest in file processing functions feat: track conversation files fix: resendFiles, addPreviousAttachments handling feat: add ID validation for session_id and file_id in download route feat: entity_id for code file uploads/downloads fix: code file edge cases feat: delete related tool calls feat: add stream rate handling for LLM configuration feat: enhance system content with attached file information fix: improve error logging in resource priming function * WIP: PoC, sequential agents WIP: PoC Sequential Agents, first pass content data + bump agents package fix: package-lock WIP: PoC, o1 support, refactor bufferString feat: convertJsonSchemaToZod fix: form issues and schema defining erroneous model fix: max length issue on agent form instructions, limit conversation messages to sequential agents feat: add abort signal support to createRun function and AgentClient feat: PoC, hide prior sequential agent steps fix: update parameter naming from config to metadata in event handlers for clarity, add model to usage data refactor: use only last contentData, track model for usage data chore: bump agents package fix: content parts issue refactor: filter contentParts to include tool calls and relevant indices feat: show function calls refactor: filter context messages to exclude tool calls when no tools are available to the agent fix: ensure tool call content is not undefined in formatMessages feat: add agent_id field to conversationPreset schema feat: hide sequential agents feat: increase upload toast duration to 10 seconds * refactor: tool context handling & update Code API Key Dialog feat: toolContextMap chore: skipSpecs -> useSpecs ci: fix handleTools tests feat: API Key Dialog * feat: Agent Permissions Admin Controls feat: replace label with button for prompt permission toggle feat: update agent permissions feat: enable experimental agents and streamline capability configuration feat: implement access control for agents and enhance endpoint menu items feat: add welcome message for agent selection in localization feat: add agents permission to access control and update version to 0.7.57 * fix: update types in useAssistantListMap and useMentions hooks for better null handling * feat: mention agents * fix: agent tool resource race conditions when deleting agent tool resource files * feat: add error handling for code execution with user feedback * refactor: rename AdminControls to AdminSettings for clarity * style: add gap to button in AdminSettings for improved layout * refactor: separate agent query hooks and check access to enable fetching * fix: remove unused provider from agent initialization options, creates issue with custom endpoints * refactor: remove redundant/deprecated modelOptions from AgentClient processes * chore: update @librechat/agents to version 1.8.5 in package.json and package-lock.json * fix: minor styling issues + agent panel uniformity * fix: agent edge cases when set endpoint is no longer defined * refactor: remove unused cleanup function call from AppService * fix: update link in ApiKeyDialog to point to pricing page * fix: improve type handling and layout calculations in SidePanel component * fix: add missing localization string for agent selection in SidePanel * chore: form styling and localizations for upload filesearch/code interpreter * fix: model selection placeholder logic in AgentConfig component * style: agent capabilities * fix: add localization for provider selection and improve dropdown styling in ModelPanel * refactor: use gpt-4o-mini > gpt-3.5-turbo * fix: agents configuration for loadDefaultInterface and update related tests * feat: DALLE Agents support
2024-12-04 15:48:13 -05:00
const removeAgentResourceFiles = async ({ agent_id, files }) => {
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const searchParameter = { id: agent_id };
// Group files to remove by resource
🎉 feat: Code Interpreter API and Agents Release (#4860) * feat: Code Interpreter API & File Search Agent Uploads chore: add back code files wip: first pass, abstract key dialog refactor: influence checkbox on key changes refactor: update localization keys for 'execute code' to 'run code' wip: run code button refactor: add throwError parameter to loadAuthValues and getUserPluginAuthValue functions feat: first pass, API tool calling fix: handle missing toolId in callTool function and return 404 for non-existent tools feat: show code outputs fix: improve error handling in callTool function and log errors fix: handle potential null value for filepath in attachment destructuring fix: normalize language before rendering and prevent null return fix: add loading indicator in RunCode component while executing code feat: add support for conditional code execution in Markdown components feat: attachments refactor: remove bash fix: pass abort signal to graph/run refactor: debounce and rate limit tool call refactor: increase debounce delay for execute function feat: set code output attachments feat: image attachments refactor: apply message context refactor: pass `partIndex` feat: toolCall schema/model/methods feat: block indexing feat: get tool calls chore: imports chore: typing chore: condense type imports feat: get tool calls fix: block indexing chore: typing refactor: update tool calls mapping to support multiple results fix: add unique key to nav link for rendering wip: first pass, tool call results refactor: update query cache from successful tool call mutation style: improve result switcher styling chore: note on using \`.toObject()\` feat: add agent_id field to conversation schema chore: typing refactor: rename agentMap to agentsMap for consistency feat: Agent Name as chat input placeholder chore: bump agents 📦 chore: update @langchain dependencies to latest versions to match agents package 📦 chore: update @librechat/agents dependency to version 1.8.0 fix: Aborting agent stream removes sender; fix(bedrock): completion removes preset name label refactor: remove direct file parameter to use req.file, add `processAgentFileUpload` for image uploads feat: upload menu feat: prime message_file resources feat: implement conversation access validation in chat route refactor: remove file parameter from processFileUpload and use req.file instead feat: add savedMessageIds set to track saved message IDs in BaseClient, to prevent unnecessary double-write to db feat: prevent duplicate message saves by checking savedMessageIds in AgentController refactor: skip legacy RAG API handling for agents feat: add files field to convoSchema refactor: update request type annotations from Express.Request to ServerRequest in file processing functions feat: track conversation files fix: resendFiles, addPreviousAttachments handling feat: add ID validation for session_id and file_id in download route feat: entity_id for code file uploads/downloads fix: code file edge cases feat: delete related tool calls feat: add stream rate handling for LLM configuration feat: enhance system content with attached file information fix: improve error logging in resource priming function * WIP: PoC, sequential agents WIP: PoC Sequential Agents, first pass content data + bump agents package fix: package-lock WIP: PoC, o1 support, refactor bufferString feat: convertJsonSchemaToZod fix: form issues and schema defining erroneous model fix: max length issue on agent form instructions, limit conversation messages to sequential agents feat: add abort signal support to createRun function and AgentClient feat: PoC, hide prior sequential agent steps fix: update parameter naming from config to metadata in event handlers for clarity, add model to usage data refactor: use only last contentData, track model for usage data chore: bump agents package fix: content parts issue refactor: filter contentParts to include tool calls and relevant indices feat: show function calls refactor: filter context messages to exclude tool calls when no tools are available to the agent fix: ensure tool call content is not undefined in formatMessages feat: add agent_id field to conversationPreset schema feat: hide sequential agents feat: increase upload toast duration to 10 seconds * refactor: tool context handling & update Code API Key Dialog feat: toolContextMap chore: skipSpecs -> useSpecs ci: fix handleTools tests feat: API Key Dialog * feat: Agent Permissions Admin Controls feat: replace label with button for prompt permission toggle feat: update agent permissions feat: enable experimental agents and streamline capability configuration feat: implement access control for agents and enhance endpoint menu items feat: add welcome message for agent selection in localization feat: add agents permission to access control and update version to 0.7.57 * fix: update types in useAssistantListMap and useMentions hooks for better null handling * feat: mention agents * fix: agent tool resource race conditions when deleting agent tool resource files * feat: add error handling for code execution with user feedback * refactor: rename AdminControls to AdminSettings for clarity * style: add gap to button in AdminSettings for improved layout * refactor: separate agent query hooks and check access to enable fetching * fix: remove unused provider from agent initialization options, creates issue with custom endpoints * refactor: remove redundant/deprecated modelOptions from AgentClient processes * chore: update @librechat/agents to version 1.8.5 in package.json and package-lock.json * fix: minor styling issues + agent panel uniformity * fix: agent edge cases when set endpoint is no longer defined * refactor: remove unused cleanup function call from AppService * fix: update link in ApiKeyDialog to point to pricing page * fix: improve type handling and layout calculations in SidePanel component * fix: add missing localization string for agent selection in SidePanel * chore: form styling and localizations for upload filesearch/code interpreter * fix: model selection placeholder logic in AgentConfig component * style: agent capabilities * fix: add localization for provider selection and improve dropdown styling in ModelPanel * refactor: use gpt-4o-mini > gpt-3.5-turbo * fix: agents configuration for loadDefaultInterface and update related tests * feat: DALLE Agents support
2024-12-04 15:48:13 -05:00
const filesByResource = files.reduce((acc, { tool_resource, file_id }) => {
if (!acc[tool_resource]) {
acc[tool_resource] = [];
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
}
acc[tool_resource].push(file_id);
🎉 feat: Code Interpreter API and Agents Release (#4860) * feat: Code Interpreter API & File Search Agent Uploads chore: add back code files wip: first pass, abstract key dialog refactor: influence checkbox on key changes refactor: update localization keys for 'execute code' to 'run code' wip: run code button refactor: add throwError parameter to loadAuthValues and getUserPluginAuthValue functions feat: first pass, API tool calling fix: handle missing toolId in callTool function and return 404 for non-existent tools feat: show code outputs fix: improve error handling in callTool function and log errors fix: handle potential null value for filepath in attachment destructuring fix: normalize language before rendering and prevent null return fix: add loading indicator in RunCode component while executing code feat: add support for conditional code execution in Markdown components feat: attachments refactor: remove bash fix: pass abort signal to graph/run refactor: debounce and rate limit tool call refactor: increase debounce delay for execute function feat: set code output attachments feat: image attachments refactor: apply message context refactor: pass `partIndex` feat: toolCall schema/model/methods feat: block indexing feat: get tool calls chore: imports chore: typing chore: condense type imports feat: get tool calls fix: block indexing chore: typing refactor: update tool calls mapping to support multiple results fix: add unique key to nav link for rendering wip: first pass, tool call results refactor: update query cache from successful tool call mutation style: improve result switcher styling chore: note on using \`.toObject()\` feat: add agent_id field to conversation schema chore: typing refactor: rename agentMap to agentsMap for consistency feat: Agent Name as chat input placeholder chore: bump agents 📦 chore: update @langchain dependencies to latest versions to match agents package 📦 chore: update @librechat/agents dependency to version 1.8.0 fix: Aborting agent stream removes sender; fix(bedrock): completion removes preset name label refactor: remove direct file parameter to use req.file, add `processAgentFileUpload` for image uploads feat: upload menu feat: prime message_file resources feat: implement conversation access validation in chat route refactor: remove file parameter from processFileUpload and use req.file instead feat: add savedMessageIds set to track saved message IDs in BaseClient, to prevent unnecessary double-write to db feat: prevent duplicate message saves by checking savedMessageIds in AgentController refactor: skip legacy RAG API handling for agents feat: add files field to convoSchema refactor: update request type annotations from Express.Request to ServerRequest in file processing functions feat: track conversation files fix: resendFiles, addPreviousAttachments handling feat: add ID validation for session_id and file_id in download route feat: entity_id for code file uploads/downloads fix: code file edge cases feat: delete related tool calls feat: add stream rate handling for LLM configuration feat: enhance system content with attached file information fix: improve error logging in resource priming function * WIP: PoC, sequential agents WIP: PoC Sequential Agents, first pass content data + bump agents package fix: package-lock WIP: PoC, o1 support, refactor bufferString feat: convertJsonSchemaToZod fix: form issues and schema defining erroneous model fix: max length issue on agent form instructions, limit conversation messages to sequential agents feat: add abort signal support to createRun function and AgentClient feat: PoC, hide prior sequential agent steps fix: update parameter naming from config to metadata in event handlers for clarity, add model to usage data refactor: use only last contentData, track model for usage data chore: bump agents package fix: content parts issue refactor: filter contentParts to include tool calls and relevant indices feat: show function calls refactor: filter context messages to exclude tool calls when no tools are available to the agent fix: ensure tool call content is not undefined in formatMessages feat: add agent_id field to conversationPreset schema feat: hide sequential agents feat: increase upload toast duration to 10 seconds * refactor: tool context handling & update Code API Key Dialog feat: toolContextMap chore: skipSpecs -> useSpecs ci: fix handleTools tests feat: API Key Dialog * feat: Agent Permissions Admin Controls feat: replace label with button for prompt permission toggle feat: update agent permissions feat: enable experimental agents and streamline capability configuration feat: implement access control for agents and enhance endpoint menu items feat: add welcome message for agent selection in localization feat: add agents permission to access control and update version to 0.7.57 * fix: update types in useAssistantListMap and useMentions hooks for better null handling * feat: mention agents * fix: agent tool resource race conditions when deleting agent tool resource files * feat: add error handling for code execution with user feedback * refactor: rename AdminControls to AdminSettings for clarity * style: add gap to button in AdminSettings for improved layout * refactor: separate agent query hooks and check access to enable fetching * fix: remove unused provider from agent initialization options, creates issue with custom endpoints * refactor: remove redundant/deprecated modelOptions from AgentClient processes * chore: update @librechat/agents to version 1.8.5 in package.json and package-lock.json * fix: minor styling issues + agent panel uniformity * fix: agent edge cases when set endpoint is no longer defined * refactor: remove unused cleanup function call from AppService * fix: update link in ApiKeyDialog to point to pricing page * fix: improve type handling and layout calculations in SidePanel component * fix: add missing localization string for agent selection in SidePanel * chore: form styling and localizations for upload filesearch/code interpreter * fix: model selection placeholder logic in AgentConfig component * style: agent capabilities * fix: add localization for provider selection and improve dropdown styling in ModelPanel * refactor: use gpt-4o-mini > gpt-3.5-turbo * fix: agents configuration for loadDefaultInterface and update related tests * feat: DALLE Agents support
2024-12-04 15:48:13 -05:00
return acc;
}, {});
// Step 1: Atomically remove file IDs using $pull
const pullOps = {};
const resourcesToCheck = new Set();
for (const [resource, fileIds] of Object.entries(filesByResource)) {
const fileIdsPath = `tool_resources.${resource}.file_ids`;
pullOps[fileIdsPath] = { $in: fileIds };
resourcesToCheck.add(resource);
}
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const updatePullData = { $pull: pullOps };
const agentAfterPull = await Agent.findOneAndUpdate(searchParameter, updatePullData, {
new: true,
}).lean();
if (!agentAfterPull) {
// Agent might have been deleted concurrently, or never existed.
// Check if it existed before trying to throw.
const agentExists = await getAgent(searchParameter);
if (!agentExists) {
throw new Error('Agent not found for removing resource files');
}
// If it existed but findOneAndUpdate returned null, something else went wrong.
throw new Error('Failed to update agent during file removal (pull step)');
}
// Return the agent state directly after the $pull operation.
// Skipping the $unset step for now to simplify and test core $pull atomicity.
// Empty arrays might remain, but the removal itself should be correct.
return agentAfterPull;
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
};
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
/**
* Deletes an agent based on the provided ID.
*
* @param {Object} searchParameter - The search parameters to find the agent to delete.
* @param {string} searchParameter.id - The ID of the agent to delete.
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
* @param {string} [searchParameter.author] - The user ID of the agent's author.
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
* @returns {Promise<void>} Resolves when the agent has been successfully deleted.
*/
const deleteAgent = async (searchParameter) => {
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
const agent = await Agent.findOneAndDelete(searchParameter);
if (agent) {
await removeAgentFromAllProjects(agent.id);
}
return agent;
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
};
/**
* Get all agents.
* @param {Object} searchParameter - The search parameters to find matching agents.
* @param {string} searchParameter.author - The user ID of the agent's author.
* @returns {Promise<Object>} A promise that resolves to an object containing the agents data and pagination info.
*/
const getListAgents = async (searchParameter) => {
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
const { author, ...otherParams } = searchParameter;
let query = Object.assign({ author }, otherParams);
const globalProject = await getProjectByName(GLOBAL_PROJECT_NAME, ['agentIds']);
if (globalProject && (globalProject.agentIds?.length ?? 0) > 0) {
const globalQuery = { id: { $in: globalProject.agentIds }, ...otherParams };
delete globalQuery.author;
query = { $or: [globalQuery, query] };
}
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const agents = (
await Agent.find(query, {
id: 1,
_id: 0,
name: 1,
avatar: 1,
author: 1,
projectIds: 1,
description: 1,
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
isCollaborative: 1,
}).lean()
).map((agent) => {
if (agent.author?.toString() !== author) {
delete agent.author;
}
if (agent.author) {
agent.author = agent.author.toString();
}
return agent;
});
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
const hasMore = agents.length > 0;
const firstId = agents.length > 0 ? agents[0].id : null;
const lastId = agents.length > 0 ? agents[agents.length - 1].id : null;
return {
data: agents,
has_more: hasMore,
first_id: firstId,
last_id: lastId,
};
};
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
/**
* Updates the projects associated with an agent, adding and removing project IDs as specified.
* This function also updates the corresponding projects to include or exclude the agent ID.
*
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
* @param {Object} params - Parameters for updating the agent's projects.
🗓️ 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
* @param {MongoUser} params.user - Parameters for updating the agent's projects.
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
* @param {string} params.agentId - The ID of the agent to update.
* @param {string[]} [params.projectIds] - Array of project IDs to add to the agent.
* @param {string[]} [params.removeProjectIds] - Array of project IDs to remove from the agent.
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
* @returns {Promise<MongoAgent>} The updated agent document.
* @throws {Error} If there's an error updating the agent or projects.
*/
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const updateAgentProjects = async ({ user, agentId, projectIds, removeProjectIds }) => {
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
const updateOps = {};
if (removeProjectIds && removeProjectIds.length > 0) {
for (const projectId of removeProjectIds) {
await removeAgentIdsFromProject(projectId, [agentId]);
}
updateOps.$pull = { projectIds: { $in: removeProjectIds } };
}
if (projectIds && projectIds.length > 0) {
for (const projectId of projectIds) {
await addAgentIdsToProject(projectId, [agentId]);
}
updateOps.$addToSet = { projectIds: { $each: projectIds } };
}
if (Object.keys(updateOps).length === 0) {
return await getAgent({ id: agentId });
}
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
const updateQuery = { id: agentId, author: user.id };
if (user.role === SystemRoles.ADMIN) {
delete updateQuery.author;
}
const updatedAgent = await updateAgent(updateQuery, updateOps, {
updatingUserId: user.id,
skipVersioning: true,
});
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
if (updatedAgent) {
return updatedAgent;
}
if (updateOps.$addToSet) {
for (const projectId of projectIds) {
await removeAgentIdsFromProject(projectId, [agentId]);
}
} else if (updateOps.$pull) {
for (const projectId of removeProjectIds) {
await addAgentIdsToProject(projectId, [agentId]);
}
}
return await getAgent({ id: agentId });
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
};
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
/**
* Reverts an agent to a specific version in its version history.
* @param {Object} searchParameter - The search parameters to find the agent to revert.
* @param {string} searchParameter.id - The ID of the agent to revert.
* @param {string} [searchParameter.author] - The user ID of the agent's author.
* @param {number} versionIndex - The index of the version to revert to in the versions array.
* @returns {Promise<MongoAgent>} The updated agent document after reverting.
* @throws {Error} If the agent is not found or the specified version does not exist.
*/
const revertAgentVersion = async (searchParameter, versionIndex) => {
const agent = await Agent.findOne(searchParameter);
if (!agent) {
throw new Error('Agent not found');
}
if (!agent.versions || !agent.versions[versionIndex]) {
throw new Error(`Version ${versionIndex} not found`);
}
const revertToVersion = agent.versions[versionIndex];
const updateData = {
...revertToVersion,
};
delete updateData._id;
delete updateData.id;
delete updateData.versions;
delete updateData.author;
delete updateData.updatedBy;
⌛ feat: Agent Version History and Management (#7455) * ✨ feat: Enhance agent update functionality to save current state in versions array - Updated the `updateAgent` function to push the current agent's state into a new `versions` array when an agent is updated. - Modified the agent schema to include a `versions` field for storing historical states of agents. * ✨ feat: Add comprehensive CRUD operations for agents in tests - Introduced a new test suite for CRUD operations on agents, including create, read, update, and delete functionalities. - Implemented tests for listing agents by author and updating agent projects. - Enhanced the agent model to support version history tracking during updates. - Ensured proper environment variable management during tests. * ✨ feat: Introduce version tracking for agents and enhance UI components - Added a `version` property to the agent model to track the number of versions. - Updated the `getAgentHandler` to include the agent's version in the response. - Introduced a new `VersionButton` component for navigating to the version panel. - Created a `VersionPanel` component for displaying version-related information. - Updated the UI to conditionally render the version button and panel based on the active state. - Added localization for the new version-related UI elements. * ✨ i18n: Add "version" translation key across multiple languages - Introduced the "com_ui_agent_version" translation key in various language files to support version tracking for agents. - Updated Arabic, Czech, German, English, Spanish, Estonian, Persian, Finnish, French, Hebrew, Hungarian, Indonesian, Italian, Japanese, Korean, Dutch, Polish, Portuguese (Brazil and Portugal), Russian, Swedish, Thai, Turkish, Vietnamese, and Chinese (Simplified and Traditional) translations. * ✨ feat: Update AgentFooter to conditionally render AdminSettings - Modified the logic for displaying buttons in the AgentFooter component to only show them when the active panel is the builder. - Ensured that AdminSettings is displayed only when the user has an admin role and the buttons are visible. * ✨ feat: Enhance AgentPanelSwitch and VersionPanel for improved agent capabilities - Updated AgentPanelSwitch to include a new VersionPanel for displaying version-related information. - Enhanced agentsConfig logic to properly handle agent capabilities. - Modified VersionPanel to improve structure and localization support. - Integrated createAgent mutation for future agent creation functionality. * ✨ feat: Enhance VersionPanel to display agent version history and loading states - Integrated version fetching logic in VersionPanel to retrieve and display agent version history. - Added loading and error handling states to improve user experience. - Updated agent schema to use mixed types for versions, allowing for more flexible version data structures. - Introduced localization support for version-related UI elements. * ✨ feat: Update VersionPanel and AgentPanelSwitch to enhance agent selection and version display - Modified AgentPanelSwitch to pass selectedAgentId to VersionPanel for improved agent context. - Enhanced VersionPanel to handle multiple timestamp formats and display appropriate messages when no agent is selected. - Improved structure and readability of the VersionPanel component by adding a helper function for timestamp retrieval. * ✨ feat: Refactor VersionPanel to utilize localization and improve timestamp handling - Replaced hardcoded text constants with localization support for various UI elements in VersionPanel. - Enhanced the timestamp retrieval function to handle errors gracefully and utilize localized messages for unknown dates. - Improved user feedback by displaying localized messages for agent selection, version errors, and empty states. * ✨ refactor: Clean up VersionPanel by removing unused code and improving timestamp handling * ✨ feat: Implement agent version reverting functionality - Added `revertAgentVersion` method in the Agent model to allow reverting to a previous version of an agent. - Introduced `revertAgentVersionHandler` in the agents controller to handle requests for reverting agent versions. - Updated API routes to include a new endpoint for reverting agent versions. - Enhanced the VersionPanel component to support version restoration with user confirmation and feedback. - Added localization support for success and error messages related to version restoration. * ✨ i18n: Add localization for agent version restoration messages * Simplify VersionPanel by removing unused parameters and enhancing agent ID handling * Refactor Agent model and VersionPanel component to streamline version data handling * Update version handling in Agent model and VersionPanel - Enhanced the Agent model to include an `updatedAt` timestamp when pushing new versions. - Improved the VersionPanel component to sort versions by the `updatedAt` timestamp for better display order. - Added a new localization entry for indicating the active version of an agent. * ✨ i18n: Add localization for active agent version across multiple languages * ✨ feat: Introduce version management components for agent history - Added `isActiveVersion` utility to determine the active version of an agent based on various criteria. - Implemented `VersionContent` and `VersionItem` components to display agent version history, including loading and error states. - Enhanced `VersionPanel` to integrate new components and manage version context effectively. - Added comprehensive tests for version management functionalities to ensure reliability and correctness. * Add unit tests for AgentFooter component * cleanup * Enhance agent version update handling and add unit tests for update operators - Updated the `updateAgent` function to properly handle various update operators ($push, $pull, $addToSet) while maintaining version history. - Modified unit tests to validate the correct behavior of agent updates, including versioning and tool management. * Enhance version comparison logic and update tests for artifacts handling - Modified the `isActiveVersion` utility to include artifacts in the version comparison criteria. - Updated the `VersionPanel` component to support artifacts in the agent state. - Added new unit tests to validate artifacts matching scenarios and edge cases in the `isActiveVersion` function. * Implement duplicate version detection in agent updates and enhance error handling - Added `isDuplicateVersion` function to check for identical versions during agent updates, excluding certain fields. - Updated `updateAgent` function to throw an error if a duplicate version is detected, with detailed error information. - Enhanced the `updateAgentHandler` to return appropriate responses for duplicate version errors. - Modified client-side error handling to display user-friendly messages for duplicate version scenarios. - Added comprehensive unit tests to validate duplicate version detection and error handling across various update scenarios. * Update version title localization to include version number across multiple languages - Modified the `com_ui_agent_version_title` translation key to include a placeholder for the version number in various language files. - Enhanced the `VersionItem` component to utilize the updated localization for displaying version titles dynamically. * Enhance agent version handling and add revert functionality - Updated the `isDuplicateVersion` function to improve version comparison logic, including special handling for `projectIds` and arrays of objects. - Modified the `updateAgent` function to streamline version updates and removed unnecessary checks for test environments. - Introduced a new `revertAgentVersion` function to allow reverting agents to specific versions, with detailed documentation. - Enhanced unit tests to validate duplicate version detection and revert functionality, ensuring robust error handling and version management. * fix CI issues * cleanup * Revert all non-English translations * clean up tests
2025-05-20 15:03:13 -04:00
return Agent.findOneAndUpdate(searchParameter, updateData, { new: true }).lean();
};
/**
* Generates a hash of action metadata for version comparison
* @param {string[]} actionIds - Array of action IDs in format "domain_action_id"
* @param {Action[]} actions - Array of action documents
* @returns {Promise<string>} - SHA256 hash of the action metadata
*/
const generateActionMetadataHash = async (actionIds, actions) => {
if (!actionIds || actionIds.length === 0) {
return '';
}
// Create a map of action_id to metadata for quick lookup
const actionMap = new Map();
actions.forEach((action) => {
actionMap.set(action.action_id, action.metadata);
});
// Sort action IDs for consistent hashing
const sortedActionIds = [...actionIds].sort();
// Build a deterministic string representation of all action metadata
const metadataString = sortedActionIds
.map((actionFullId) => {
// Extract just the action_id part (after the delimiter)
const parts = actionFullId.split(actionDelimiter);
const actionId = parts[1];
const metadata = actionMap.get(actionId);
if (!metadata) {
return `${actionId}:null`;
}
// Sort metadata keys for deterministic output
const sortedKeys = Object.keys(metadata).sort();
const metadataStr = sortedKeys
.map((key) => `${key}:${JSON.stringify(metadata[key])}`)
.join(',');
return `${actionId}:{${metadataStr}}`;
})
.join(';');
// Use Web Crypto API to generate hash
const encoder = new TextEncoder();
const data = encoder.encode(metadataString);
const hashBuffer = await crypto.webcrypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
};
/**
* Load a default agent based on the endpoint
* @param {string} endpoint
* @returns {Agent | null}
*/
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
module.exports = {
getAgent,
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
loadAgent,
createAgent,
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
updateAgent,
deleteAgent,
getListAgents,
revertAgentVersion,
🪨 feat: AWS Bedrock support (#3935) * feat: Add BedrockIcon component to SVG library * feat: EModelEndpoint.bedrock * feat: first pass, bedrock chat. note: AgentClient is returning `agents` as conversation.endpoint * fix: declare endpoint in initialization step * chore: Update @librechat/agents dependency to version 1.4.5 * feat: backend content aggregation for agents/bedrock * feat: abort agent requests * feat: AWS Bedrock icons * WIP: agent provider schema parsing * chore: Update EditIcon props type * refactor(useGenerationsByLatest): make agents and bedrock editable * refactor: non-assistant message content, parts * fix: Bedrock response `sender` * fix: use endpointOption.model_parameters not endpointOption.modelOptions * fix: types for step handler * refactor: Update Agents.ToolCallDelta type * refactor: Remove unnecessary assignment of parentMessageId in AskController * refactor: remove unnecessary assignment of parentMessageId (agent request handler) * fix(bedrock/agents): message regeneration * refactor: dynamic form elements using react-hook-form Controllers * fix: agent icons/labels for messages * fix: agent actions * fix: use of new dynamic tags causing application crash * refactor: dynamic settings touch-ups * refactor: update Slider component to allow custom track class name * refactor: update DynamicSlider component styles * refactor: use Constants value for GLOBAL_PROJECT_NAME (enum) * feat: agent share global methods/controllers * fix: agents query * fix: `getResponseModel` * fix: share prompt a11y issue * refactor: update SharePrompt dialog theme styles * refactor: explicit typing for SharePrompt * feat: add agent roles/permissions * chore: update @librechat/agents dependency to version 1.4.7 for tool_call_ids edge case * fix(Anthropic): messages.X.content.Y.tool_use.input: Input should be a valid dictionary * fix: handle text parts with tool_call_ids and empty text * fix: role initialization * refactor: don't make instructions required * refactor: improve typing of Text part * fix: setShowStopButton for agents route * chore: remove params for now * fix: add streamBuffer and streamRate to help prevent 'Overloaded' errors from Anthropic API * refactor: remove console.log statement in ContentRender component * chore: typing, rename Context to Delete Button * chore(DeleteButton): logging * refactor(Action): make accessible * style(Action): improve a11y again * refactor: remove use/mention of mongoose sessions * feat: first pass, sharing agents * feat: visual indicator for global agent, remove author when serving to non-author * wip: params * chore: fix typing issues * fix(schemas): typing * refactor: improve accessibility of ListCard component and fix console React warning * wip: reset templates for non-legacy new convos * Revert "wip: params" This reverts commit f8067e91d4adf7be9e0d9e914aaae79ac4689b80. * Revert "refactor: dynamic form elements using react-hook-form Controllers" This reverts commit 2150c4815d8c74a978a4b697aa8f54dc11e035d7. * fix(Parameters): types and parameter effect update to only update local state to parameters * refactor: optimize useDebouncedInput hook for better performance * feat: first pass, anthropic bedrock params * chore: paramEndpoints check for endpointType too * fix: maxTokens to use coerceNumber.optional(), * feat: extra chat model params * chore: reduce code repetition * refactor: improve preset title handling in SaveAsPresetDialog component * refactor: improve preset handling in HeaderOptions component * chore: improve typing, replace legacy dialog for SaveAsPresetDialog * feat: save as preset from parameters panel * fix: multi-search in select dropdown when using Option type * refactor: update default showDefault value to false in Dynamic components * feat: Bedrock presets settings * chore: config, fix agents schema, update config version * refactor: update AWS region variable name in bedrock options endpoint to BEDROCK_AWS_DEFAULT_REGION * refactor: update baseEndpointSchema in config.ts to include baseURL property * refactor: update createRun function to include req parameter and set streamRate based on provider * feat: availableRegions via config * refactor: remove unused demo agent controller file * WIP: title * Update @librechat/agents to version 1.5.0 * chore: addTitle.js to handle empty responseText * feat: support images and titles * feat: context token updates * Refactor BaseClient test to use expect.objectContaining * refactor: add model select, remove header options params, move side panel params below prompts * chore: update models list, catch title error * feat: model service for bedrock models (env) * chore: Remove verbose debug log in AgentClient class following stream * feat(bedrock): track token spend; fix: token rates, value key mapping for AWS models * refactor: handle streamRate in `handleLLMNewToken` callback * chore: AWS Bedrock example config in `.env.example` * refactor: Rename bedrockMeta to bedrockGeneral in settings.ts and use for AI21 and Amazon Bedrock providers * refactor: Update `.env.example` with AWS Bedrock model IDs URL and additional notes * feat: titleModel support for bedrock * refactor: Update `.env.example` with additional notes for AWS Bedrock model IDs
2024-09-09 12:06:59 -04:00
updateAgentProjects,
🚧 chore: merge latest dev build (#4288) * fix: agent initialization, add `collectedUsage` handling * style: improve side panel styling * refactor(loadAgent): Optimize order agent project ID retrieval * feat: code execution * fix: typing issues * feat: ExecuteCode content part * refactor: use local state for default collapsed state of analysis content parts * fix: code parsing in ExecuteCode component * chore: bump agents package, export loadAuthValues * refactor: Update handleTools.js to use EnvVar for code execution tool authentication * WIP * feat: download code outputs * fix(useEventHandlers): type issues * feat: backend handling for code outputs * Refactor: Remove console.log statement in Part.tsx * refactor: add attachments to TMessage/messageSchema * WIP: prelim handling for code outputs * feat: attachments rendering * refactor: improve attachments rendering * fix: attachments, nullish edge case, handle attachments from event stream, bump agents package * fix filename download * fix: tool assignment for 'run code' on agent creation * fix: image handling by adding attachments * refactor: prevent agent creation without provider/model * refactor: remove unnecessary space in agent creation success message * refactor: select first model if selecting provider from empty on form * fix: Agent avatar bug * fix: `defaultAgentFormValues` causing boolean typing issue and typeerror * fix: capabilities counting as tools, causing duplication of them * fix: formatted messages edge case where consecutive content text type parts with the latter having tool_call_ids would cause consecutive AI messages to be created. furthermore, content could not be an array for tool_use messages (anthropic limitation) * chore: bump @librechat/agents dependency to version 1.6.9 * feat: bedrock agents * feat: new Agents icon * feat: agent titling * feat: agent landing * refactor: allow sharing agent globally only if user is admin or author * feat: initial AgentPanelSkeleton * feat: AgentPanelSkeleton * feat: collaborative agents * chore: add potential authorName as part of schema * chore: Remove unnecessary console.log statement * WIP: agent model parameters * chore: ToolsDialog typing and tool related localization chnages * refactor: update tool instance type (latest langchain class), and rename google tool to 'google' proper * chore: add back tools * feat: Agent knowledge files upload * refactor: better verbiage for disabled knowledge * chore: debug logs for file deletions * chore: debug logs for file deletions * feat: upload/delete agent knowledge/file-search files * feat: file search UI for agents * feat: first pass, file search tool * chore: update default agent capabilities and info
2024-09-30 17:17:57 -04:00
addAgentResourceFile,
🎉 feat: Code Interpreter API and Agents Release (#4860) * feat: Code Interpreter API & File Search Agent Uploads chore: add back code files wip: first pass, abstract key dialog refactor: influence checkbox on key changes refactor: update localization keys for 'execute code' to 'run code' wip: run code button refactor: add throwError parameter to loadAuthValues and getUserPluginAuthValue functions feat: first pass, API tool calling fix: handle missing toolId in callTool function and return 404 for non-existent tools feat: show code outputs fix: improve error handling in callTool function and log errors fix: handle potential null value for filepath in attachment destructuring fix: normalize language before rendering and prevent null return fix: add loading indicator in RunCode component while executing code feat: add support for conditional code execution in Markdown components feat: attachments refactor: remove bash fix: pass abort signal to graph/run refactor: debounce and rate limit tool call refactor: increase debounce delay for execute function feat: set code output attachments feat: image attachments refactor: apply message context refactor: pass `partIndex` feat: toolCall schema/model/methods feat: block indexing feat: get tool calls chore: imports chore: typing chore: condense type imports feat: get tool calls fix: block indexing chore: typing refactor: update tool calls mapping to support multiple results fix: add unique key to nav link for rendering wip: first pass, tool call results refactor: update query cache from successful tool call mutation style: improve result switcher styling chore: note on using \`.toObject()\` feat: add agent_id field to conversation schema chore: typing refactor: rename agentMap to agentsMap for consistency feat: Agent Name as chat input placeholder chore: bump agents 📦 chore: update @langchain dependencies to latest versions to match agents package 📦 chore: update @librechat/agents dependency to version 1.8.0 fix: Aborting agent stream removes sender; fix(bedrock): completion removes preset name label refactor: remove direct file parameter to use req.file, add `processAgentFileUpload` for image uploads feat: upload menu feat: prime message_file resources feat: implement conversation access validation in chat route refactor: remove file parameter from processFileUpload and use req.file instead feat: add savedMessageIds set to track saved message IDs in BaseClient, to prevent unnecessary double-write to db feat: prevent duplicate message saves by checking savedMessageIds in AgentController refactor: skip legacy RAG API handling for agents feat: add files field to convoSchema refactor: update request type annotations from Express.Request to ServerRequest in file processing functions feat: track conversation files fix: resendFiles, addPreviousAttachments handling feat: add ID validation for session_id and file_id in download route feat: entity_id for code file uploads/downloads fix: code file edge cases feat: delete related tool calls feat: add stream rate handling for LLM configuration feat: enhance system content with attached file information fix: improve error logging in resource priming function * WIP: PoC, sequential agents WIP: PoC Sequential Agents, first pass content data + bump agents package fix: package-lock WIP: PoC, o1 support, refactor bufferString feat: convertJsonSchemaToZod fix: form issues and schema defining erroneous model fix: max length issue on agent form instructions, limit conversation messages to sequential agents feat: add abort signal support to createRun function and AgentClient feat: PoC, hide prior sequential agent steps fix: update parameter naming from config to metadata in event handlers for clarity, add model to usage data refactor: use only last contentData, track model for usage data chore: bump agents package fix: content parts issue refactor: filter contentParts to include tool calls and relevant indices feat: show function calls refactor: filter context messages to exclude tool calls when no tools are available to the agent fix: ensure tool call content is not undefined in formatMessages feat: add agent_id field to conversationPreset schema feat: hide sequential agents feat: increase upload toast duration to 10 seconds * refactor: tool context handling & update Code API Key Dialog feat: toolContextMap chore: skipSpecs -> useSpecs ci: fix handleTools tests feat: API Key Dialog * feat: Agent Permissions Admin Controls feat: replace label with button for prompt permission toggle feat: update agent permissions feat: enable experimental agents and streamline capability configuration feat: implement access control for agents and enhance endpoint menu items feat: add welcome message for agent selection in localization feat: add agents permission to access control and update version to 0.7.57 * fix: update types in useAssistantListMap and useMentions hooks for better null handling * feat: mention agents * fix: agent tool resource race conditions when deleting agent tool resource files * feat: add error handling for code execution with user feedback * refactor: rename AdminControls to AdminSettings for clarity * style: add gap to button in AdminSettings for improved layout * refactor: separate agent query hooks and check access to enable fetching * fix: remove unused provider from agent initialization options, creates issue with custom endpoints * refactor: remove redundant/deprecated modelOptions from AgentClient processes * chore: update @librechat/agents to version 1.8.5 in package.json and package-lock.json * fix: minor styling issues + agent panel uniformity * fix: agent edge cases when set endpoint is no longer defined * refactor: remove unused cleanup function call from AppService * fix: update link in ApiKeyDialog to point to pricing page * fix: improve type handling and layout calculations in SidePanel component * fix: add missing localization string for agent selection in SidePanel * chore: form styling and localizations for upload filesearch/code interpreter * fix: model selection placeholder logic in AgentConfig component * style: agent capabilities * fix: add localization for provider selection and improve dropdown styling in ModelPanel * refactor: use gpt-4o-mini > gpt-3.5-turbo * fix: agents configuration for loadDefaultInterface and update related tests * feat: DALLE Agents support
2024-12-04 15:48:13 -05:00
removeAgentResourceFiles,
generateActionMetadataHash,
🚧 chore: merge latest dev build to main repo (#3844) * agents - phase 1 (#30) * chore: copy assistant files * feat: frontend and data-provider * feat: backend get endpoint test * fix(MessageEndpointIcon): switched to AgentName and AgentAvatar * fix: small fixes * fix: agent endpoint config * fix: show Agent Builder * chore: install agentus * chore: initial scaffolding for agents * fix: updated Assistant logic to Agent Logic for some Agent components * WIP first pass, demo of agent package * WIP: initial backend infra for agents * fix: agent list error * wip: agents routing * chore: Refactor useSSE hook to handle different data events * wip: correctly emit events * chore: Update @librechat/agentus npm dependency to version 1.0.9 * remove comment * first pass: streaming agent text * chore: Remove @librechat/agentus root-level workspace npm dependency * feat: Agent Schema and Model * fix: content handling fixes * fix: content message save * WIP: new content data * fix: run step issue with tool calls * chore: Update @librechat/agentus npm dependency to version 1.1.5 * feat: update controller and agent routes * wip: initial backend tool and tool error handling support * wip: tool chunks * chore: Update @librechat/agentus npm dependency to version 1.1.7 * chore: update tool_call typing, add test conditions and logs * fix: create agent * fix: create agent * first pass: render completed content parts * fix: remove logging, fix step handler typing * chore: Update @librechat/agentus npm dependency to version 1.1.9 * refactor: cleanup maps on unmount * chore: Update BaseClient.js to safely count tokens for string, number, and boolean values * fix: support subsequent messages with tool_calls * chore: export order * fix: select agent * fix: tool call types and handling * chore: switch to anthropic for testing * fix: AgentSelect * refactor: experimental: OpenAIClient to use array for intermediateReply * fix(useSSE): revert old condition for streaming legacy client tokens * fix: lint * revert `agent_id` to `id` * chore: update localization keys for agent-related components * feat: zod schema handling for actions * refactor(actions): if no params, no zodSchema * chore: Update @librechat/agentus npm dependency to version 1.2.1 * feat: first pass, actions * refactor: empty schema for actions without params * feat: Update createRun function to accept additional options * fix: message payload formatting; feat: add more client options * fix: ToolCall component rendering when action has no args but has output * refactor(ToolCall): allow non-stringy args * WIP: first pass, correctly formatted tool_calls between providers * refactor: Remove duplicate import of 'roles' module * refactor: Exclude 'vite.config.ts' from TypeScript compilation * refactor: fix agent related types > - no need to use endpoint/model fields for identifying agent metadata > - add `provider` distinction for agent-configured 'endpoint' - no need for agent-endpoint map - reduce complexity of tools as functions into tools as string[] - fix types related to above changes - reduce unnecessary variables for queries/mutations and corresponding react-query keys * refactor: Add tools and tool_kwargs fields to agent schema * refactor: Remove unused code and update dependencies * refactor: Update updateAgentHandler to use req.body directly * refactor: Update AgentSelect component to use localized hooks * refactor: Update agent schema to include tools and provider fields * refactor(AgentPanel): add scrollbar gutter, add provider field to form, fix agent schema required values * refactor: Update AgentSwitcher component to use selectedAgentId instead of selectedAgent * refactor: Update AgentPanel component to include alternateName import and defaultAgentFormValues * refactor(SelectDropDown): allow setting value as option while still supporting legacy usage (string values only) * refactor: SelectDropdown changes - Only necessary when the available values are objects with label/value fields and the selected value is expected to be a string. * refactor: TypeError issues and handle provider as option * feat: Add placeholder for provider selection in AgentPanel component * refactor: Update agent schema to include author and provider fields * fix: show expected 'create agent' placeholder when creating agent * chore: fix localization strings, hide capabilities form for now * chore: typing * refactor: import order and use compact agents schema for now * chore: typing * refactor: Update AgentForm type to use AgentCapabilities * fix agent form agent selection issues * feat: responsive agent selection * fix: Handle cancelled fetch in useSelectAgent hook * fix: reset agent form on accordion close/open * feat: Add agent_id to default conversation for agents endpoint * feat: agents endpoint request handling * refactor: reset conversation model on agent select * refactor: add `additional_instructions` to conversation schema, organize other fields * chore: casing * chore: types * refactor(loadAgentTools): explicitly pass agent_id, do not pass `model` to loadAgentTools for now, load action sets by agent_id * WIP: initial draft of real agent client initialization * WIP: first pass, anthropic agent requests * feat: remember last selected agent * feat: openai and azure connected * fix: prioritize agent model for runs unless an explicit override model is passed from client * feat: Agent Actions * fix: save agent id to convo * feat: model panel (#29) * feat: model panel * bring back comments * fix: method still null * fix: AgentPanel FormContext * feat: add more parameters * fix: style issues; refactor: Agent Controller * fix: cherry-pick * fix: Update AgentAvatar component to use AssistantIcon instead of BrainCircuit * feat: OGDialog for delete agent; feat(assistant): update Agent types, introduced `model_parameters` * feat: icon and general `model_parameters` update * feat: use react-hook-form better * fix: agent builder form reset issue when switching panels * refactor: modularize agent builder form --------- Co-authored-by: Danny Avila <danny@librechat.ai> * fix: AgentPanel and ModelPanel type issues and use `useFormContext` and `watch` instead of `methods` directly and `useWatch`. * fix: tool call issues due to invalid input (anthropic) of empty string * fix: handle empty text in Part component --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * refactor: remove form ModelPanel and fixed nested ternary expressions in AgentConfig * fix: Model Parameters not saved correctly * refactor: remove console log * feat: avatar upload and get for Agents (#36) Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com> * chore: update to public package * fix: typing, optional chaining * fix: cursor not showing for content parts * chore: conditionally enable agents * ci: fix azure test * ci: fix frontend tests, fix eslint api * refactor: Remove unused errorContentPart variable * continue of the agent message PR (#40) * last fixes * fix: agentMap * pr merge test (#41) * fix: model icon not fetching correctly * remove console logs * feat: agent name * refactor: pass documentsMap as a prop to allow re-render of assistant form * refactor: pass documentsMap as a prop to allow re-render of assistant form * chore: Bump version to 0.7.419 * fix: TypeError: Cannot read properties of undefined (reading 'id') * refactor: update AgentSwitcher component to use ControlCombobox instead of Combobox --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2024-08-31 16:33:51 -04:00
};