crca 1.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- .github/ISSUE_TEMPLATE/bug_report.md +65 -0
- .github/ISSUE_TEMPLATE/feature_request.md +41 -0
- .github/PULL_REQUEST_TEMPLATE.md +20 -0
- .github/workflows/publish-manual.yml +61 -0
- .github/workflows/publish.yml +64 -0
- .gitignore +214 -0
- CRCA.py +4156 -0
- LICENSE +201 -0
- MANIFEST.in +43 -0
- PKG-INFO +5035 -0
- README.md +4959 -0
- __init__.py +17 -0
- branches/CRCA-Q.py +2728 -0
- branches/crca_cg/corposwarm.py +9065 -0
- branches/crca_cg/fix_rancher_docker_creds.ps1 +155 -0
- branches/crca_cg/package.json +5 -0
- branches/crca_cg/test_bolt_integration.py +446 -0
- branches/crca_cg/test_corposwarm_comprehensive.py +773 -0
- branches/crca_cg/test_new_features.py +163 -0
- branches/crca_sd/__init__.py +149 -0
- branches/crca_sd/crca_sd_core.py +770 -0
- branches/crca_sd/crca_sd_governance.py +1325 -0
- branches/crca_sd/crca_sd_mpc.py +1130 -0
- branches/crca_sd/crca_sd_realtime.py +1844 -0
- branches/crca_sd/crca_sd_tui.py +1133 -0
- crca-1.4.0.dist-info/METADATA +5035 -0
- crca-1.4.0.dist-info/RECORD +501 -0
- crca-1.4.0.dist-info/WHEEL +4 -0
- crca-1.4.0.dist-info/licenses/LICENSE +201 -0
- docs/CRCA-Q.md +2333 -0
- examples/config.yaml.example +25 -0
- examples/crca_sd_example.py +513 -0
- examples/data_broker_example.py +294 -0
- examples/logistics_corporation.py +861 -0
- examples/palantir_example.py +299 -0
- examples/policy_bench.py +934 -0
- examples/pridnestrovia-sd.py +705 -0
- examples/pridnestrovia_realtime.py +1902 -0
- prompts/__init__.py +10 -0
- prompts/default_crca.py +101 -0
- pyproject.toml +151 -0
- requirements.txt +76 -0
- schemas/__init__.py +43 -0
- schemas/mcpSchemas.py +51 -0
- schemas/policy.py +458 -0
- templates/__init__.py +38 -0
- templates/base_specialized_agent.py +195 -0
- templates/drift_detection.py +325 -0
- templates/examples/causal_agent_template.py +309 -0
- templates/examples/drag_drop_example.py +213 -0
- templates/examples/logistics_agent_template.py +207 -0
- templates/examples/trading_agent_template.py +206 -0
- templates/feature_mixins.py +253 -0
- templates/graph_management.py +442 -0
- templates/llm_integration.py +194 -0
- templates/module_registry.py +276 -0
- templates/mpc_planner.py +280 -0
- templates/policy_loop.py +1168 -0
- templates/prediction_framework.py +448 -0
- templates/statistical_methods.py +778 -0
- tests/sanity.yml +31 -0
- tests/sanity_check +406 -0
- tests/test_core.py +47 -0
- tests/test_crca_excel.py +166 -0
- tests/test_crca_sd.py +780 -0
- tests/test_data_broker.py +424 -0
- tests/test_palantir.py +349 -0
- tools/__init__.py +38 -0
- tools/actuators.py +437 -0
- tools/bolt.diy/Dockerfile +103 -0
- tools/bolt.diy/app/components/@settings/core/AvatarDropdown.tsx +175 -0
- tools/bolt.diy/app/components/@settings/core/ControlPanel.tsx +345 -0
- tools/bolt.diy/app/components/@settings/core/constants.tsx +108 -0
- tools/bolt.diy/app/components/@settings/core/types.ts +114 -0
- tools/bolt.diy/app/components/@settings/index.ts +12 -0
- tools/bolt.diy/app/components/@settings/shared/components/TabTile.tsx +151 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionForm.tsx +193 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionTestIndicator.tsx +60 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ErrorState.tsx +102 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/LoadingState.tsx +94 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ServiceHeader.tsx +72 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/index.ts +6 -0
- tools/bolt.diy/app/components/@settings/tabs/data/DataTab.tsx +721 -0
- tools/bolt.diy/app/components/@settings/tabs/data/DataVisualization.tsx +384 -0
- tools/bolt.diy/app/components/@settings/tabs/event-logs/EventLogsTab.tsx +1013 -0
- tools/bolt.diy/app/components/@settings/tabs/features/FeaturesTab.tsx +295 -0
- tools/bolt.diy/app/components/@settings/tabs/github/GitHubTab.tsx +281 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubAuthDialog.tsx +173 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubCacheManager.tsx +367 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubConnection.tsx +233 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubErrorBoundary.tsx +105 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubProgressiveLoader.tsx +266 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositoryCard.tsx +121 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositorySelector.tsx +312 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubStats.tsx +291 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubUserProfile.tsx +46 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/shared/GitHubStateIndicators.tsx +264 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/shared/RepositoryCard.tsx +361 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/shared/index.ts +11 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/GitLabTab.tsx +305 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabAuthDialog.tsx +186 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabConnection.tsx +253 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabRepositorySelector.tsx +358 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryCard.tsx +79 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryList.tsx +142 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/StatsDisplay.tsx +91 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/index.ts +4 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerList.tsx +99 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerListItem.tsx +70 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpStatusBadge.tsx +37 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpTab.tsx +239 -0
- tools/bolt.diy/app/components/@settings/tabs/netlify/NetlifyTab.tsx +1393 -0
- tools/bolt.diy/app/components/@settings/tabs/netlify/components/NetlifyConnection.tsx +990 -0
- tools/bolt.diy/app/components/@settings/tabs/netlify/components/index.ts +1 -0
- tools/bolt.diy/app/components/@settings/tabs/notifications/NotificationsTab.tsx +300 -0
- tools/bolt.diy/app/components/@settings/tabs/profile/ProfileTab.tsx +181 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/cloud/CloudProvidersTab.tsx +308 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/ErrorBoundary.tsx +68 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/HealthStatusBadge.tsx +64 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/LoadingSkeleton.tsx +107 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/LocalProvidersTab.tsx +556 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/ModelCard.tsx +106 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/ProviderCard.tsx +120 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/SetupGuide.tsx +671 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/StatusDashboard.tsx +91 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/types.ts +44 -0
- tools/bolt.diy/app/components/@settings/tabs/settings/SettingsTab.tsx +215 -0
- tools/bolt.diy/app/components/@settings/tabs/supabase/SupabaseTab.tsx +1089 -0
- tools/bolt.diy/app/components/@settings/tabs/vercel/VercelTab.tsx +909 -0
- tools/bolt.diy/app/components/@settings/tabs/vercel/components/VercelConnection.tsx +368 -0
- tools/bolt.diy/app/components/@settings/tabs/vercel/components/index.ts +1 -0
- tools/bolt.diy/app/components/@settings/utils/tab-helpers.ts +54 -0
- tools/bolt.diy/app/components/chat/APIKeyManager.tsx +169 -0
- tools/bolt.diy/app/components/chat/Artifact.tsx +296 -0
- tools/bolt.diy/app/components/chat/AssistantMessage.tsx +192 -0
- tools/bolt.diy/app/components/chat/BaseChat.module.scss +47 -0
- tools/bolt.diy/app/components/chat/BaseChat.tsx +522 -0
- tools/bolt.diy/app/components/chat/Chat.client.tsx +670 -0
- tools/bolt.diy/app/components/chat/ChatAlert.tsx +108 -0
- tools/bolt.diy/app/components/chat/ChatBox.tsx +334 -0
- tools/bolt.diy/app/components/chat/CodeBlock.module.scss +10 -0
- tools/bolt.diy/app/components/chat/CodeBlock.tsx +85 -0
- tools/bolt.diy/app/components/chat/DicussMode.tsx +17 -0
- tools/bolt.diy/app/components/chat/ExamplePrompts.tsx +37 -0
- tools/bolt.diy/app/components/chat/FilePreview.tsx +38 -0
- tools/bolt.diy/app/components/chat/GitCloneButton.tsx +327 -0
- tools/bolt.diy/app/components/chat/ImportFolderButton.tsx +141 -0
- tools/bolt.diy/app/components/chat/LLMApiAlert.tsx +109 -0
- tools/bolt.diy/app/components/chat/MCPTools.tsx +129 -0
- tools/bolt.diy/app/components/chat/Markdown.module.scss +171 -0
- tools/bolt.diy/app/components/chat/Markdown.spec.ts +48 -0
- tools/bolt.diy/app/components/chat/Markdown.tsx +252 -0
- tools/bolt.diy/app/components/chat/Messages.client.tsx +102 -0
- tools/bolt.diy/app/components/chat/ModelSelector.tsx +797 -0
- tools/bolt.diy/app/components/chat/NetlifyDeploymentLink.client.tsx +51 -0
- tools/bolt.diy/app/components/chat/ProgressCompilation.tsx +110 -0
- tools/bolt.diy/app/components/chat/ScreenshotStateManager.tsx +33 -0
- tools/bolt.diy/app/components/chat/SendButton.client.tsx +39 -0
- tools/bolt.diy/app/components/chat/SpeechRecognition.tsx +28 -0
- tools/bolt.diy/app/components/chat/StarterTemplates.tsx +38 -0
- tools/bolt.diy/app/components/chat/SupabaseAlert.tsx +199 -0
- tools/bolt.diy/app/components/chat/SupabaseConnection.tsx +339 -0
- tools/bolt.diy/app/components/chat/ThoughtBox.tsx +43 -0
- tools/bolt.diy/app/components/chat/ToolInvocations.tsx +409 -0
- tools/bolt.diy/app/components/chat/UserMessage.tsx +101 -0
- tools/bolt.diy/app/components/chat/VercelDeploymentLink.client.tsx +158 -0
- tools/bolt.diy/app/components/chat/chatExportAndImport/ExportChatButton.tsx +49 -0
- tools/bolt.diy/app/components/chat/chatExportAndImport/ImportButtons.tsx +96 -0
- tools/bolt.diy/app/components/deploy/DeployAlert.tsx +197 -0
- tools/bolt.diy/app/components/deploy/DeployButton.tsx +277 -0
- tools/bolt.diy/app/components/deploy/GitHubDeploy.client.tsx +171 -0
- tools/bolt.diy/app/components/deploy/GitHubDeploymentDialog.tsx +1041 -0
- tools/bolt.diy/app/components/deploy/GitLabDeploy.client.tsx +171 -0
- tools/bolt.diy/app/components/deploy/GitLabDeploymentDialog.tsx +764 -0
- tools/bolt.diy/app/components/deploy/NetlifyDeploy.client.tsx +246 -0
- tools/bolt.diy/app/components/deploy/VercelDeploy.client.tsx +235 -0
- tools/bolt.diy/app/components/editor/codemirror/BinaryContent.tsx +7 -0
- tools/bolt.diy/app/components/editor/codemirror/CodeMirrorEditor.tsx +555 -0
- tools/bolt.diy/app/components/editor/codemirror/EnvMasking.ts +80 -0
- tools/bolt.diy/app/components/editor/codemirror/cm-theme.ts +192 -0
- tools/bolt.diy/app/components/editor/codemirror/indent.ts +68 -0
- tools/bolt.diy/app/components/editor/codemirror/languages.ts +112 -0
- tools/bolt.diy/app/components/git/GitUrlImport.client.tsx +147 -0
- tools/bolt.diy/app/components/header/Header.tsx +42 -0
- tools/bolt.diy/app/components/header/HeaderActionButtons.client.tsx +54 -0
- tools/bolt.diy/app/components/mandate/MandateSubmission.tsx +167 -0
- tools/bolt.diy/app/components/observability/DeploymentStatus.tsx +168 -0
- tools/bolt.diy/app/components/observability/EventTimeline.tsx +119 -0
- tools/bolt.diy/app/components/observability/FileDiffViewer.tsx +121 -0
- tools/bolt.diy/app/components/observability/GovernanceStatus.tsx +197 -0
- tools/bolt.diy/app/components/observability/GovernorMetrics.tsx +246 -0
- tools/bolt.diy/app/components/observability/LogStream.tsx +244 -0
- tools/bolt.diy/app/components/observability/MandateDetails.tsx +201 -0
- tools/bolt.diy/app/components/observability/ObservabilityDashboard.tsx +200 -0
- tools/bolt.diy/app/components/sidebar/HistoryItem.tsx +187 -0
- tools/bolt.diy/app/components/sidebar/Menu.client.tsx +536 -0
- tools/bolt.diy/app/components/sidebar/date-binning.ts +59 -0
- tools/bolt.diy/app/components/txt +1 -0
- tools/bolt.diy/app/components/ui/BackgroundRays/index.tsx +18 -0
- tools/bolt.diy/app/components/ui/BackgroundRays/styles.module.scss +246 -0
- tools/bolt.diy/app/components/ui/Badge.tsx +53 -0
- tools/bolt.diy/app/components/ui/BranchSelector.tsx +270 -0
- tools/bolt.diy/app/components/ui/Breadcrumbs.tsx +101 -0
- tools/bolt.diy/app/components/ui/Button.tsx +46 -0
- tools/bolt.diy/app/components/ui/Card.tsx +55 -0
- tools/bolt.diy/app/components/ui/Checkbox.tsx +32 -0
- tools/bolt.diy/app/components/ui/CloseButton.tsx +49 -0
- tools/bolt.diy/app/components/ui/CodeBlock.tsx +103 -0
- tools/bolt.diy/app/components/ui/Collapsible.tsx +9 -0
- tools/bolt.diy/app/components/ui/ColorSchemeDialog.tsx +378 -0
- tools/bolt.diy/app/components/ui/Dialog.tsx +449 -0
- tools/bolt.diy/app/components/ui/Dropdown.tsx +63 -0
- tools/bolt.diy/app/components/ui/EmptyState.tsx +154 -0
- tools/bolt.diy/app/components/ui/FileIcon.tsx +346 -0
- tools/bolt.diy/app/components/ui/FilterChip.tsx +92 -0
- tools/bolt.diy/app/components/ui/GlowingEffect.tsx +192 -0
- tools/bolt.diy/app/components/ui/GradientCard.tsx +100 -0
- tools/bolt.diy/app/components/ui/IconButton.tsx +84 -0
- tools/bolt.diy/app/components/ui/Input.tsx +22 -0
- tools/bolt.diy/app/components/ui/Label.tsx +20 -0
- tools/bolt.diy/app/components/ui/LoadingDots.tsx +27 -0
- tools/bolt.diy/app/components/ui/LoadingOverlay.tsx +32 -0
- tools/bolt.diy/app/components/ui/PanelHeader.tsx +20 -0
- tools/bolt.diy/app/components/ui/PanelHeaderButton.tsx +36 -0
- tools/bolt.diy/app/components/ui/Popover.tsx +29 -0
- tools/bolt.diy/app/components/ui/Progress.tsx +22 -0
- tools/bolt.diy/app/components/ui/RepositoryStats.tsx +87 -0
- tools/bolt.diy/app/components/ui/ScrollArea.tsx +41 -0
- tools/bolt.diy/app/components/ui/SearchInput.tsx +80 -0
- tools/bolt.diy/app/components/ui/SearchResultItem.tsx +134 -0
- tools/bolt.diy/app/components/ui/Separator.tsx +22 -0
- tools/bolt.diy/app/components/ui/SettingsButton.tsx +35 -0
- tools/bolt.diy/app/components/ui/Slider.tsx +73 -0
- tools/bolt.diy/app/components/ui/StatusIndicator.tsx +90 -0
- tools/bolt.diy/app/components/ui/Switch.tsx +37 -0
- tools/bolt.diy/app/components/ui/Tabs.tsx +52 -0
- tools/bolt.diy/app/components/ui/TabsWithSlider.tsx +112 -0
- tools/bolt.diy/app/components/ui/ThemeSwitch.tsx +29 -0
- tools/bolt.diy/app/components/ui/Tooltip.tsx +122 -0
- tools/bolt.diy/app/components/ui/index.ts +38 -0
- tools/bolt.diy/app/components/ui/use-toast.ts +66 -0
- tools/bolt.diy/app/components/workbench/DiffView.tsx +796 -0
- tools/bolt.diy/app/components/workbench/EditorPanel.tsx +174 -0
- tools/bolt.diy/app/components/workbench/ExpoQrModal.tsx +55 -0
- tools/bolt.diy/app/components/workbench/FileBreadcrumb.tsx +150 -0
- tools/bolt.diy/app/components/workbench/FileTree.tsx +565 -0
- tools/bolt.diy/app/components/workbench/Inspector.tsx +126 -0
- tools/bolt.diy/app/components/workbench/InspectorPanel.tsx +146 -0
- tools/bolt.diy/app/components/workbench/LockManager.tsx +262 -0
- tools/bolt.diy/app/components/workbench/PortDropdown.tsx +91 -0
- tools/bolt.diy/app/components/workbench/Preview.tsx +1049 -0
- tools/bolt.diy/app/components/workbench/ScreenshotSelector.tsx +293 -0
- tools/bolt.diy/app/components/workbench/Search.tsx +257 -0
- tools/bolt.diy/app/components/workbench/Workbench.client.tsx +506 -0
- tools/bolt.diy/app/components/workbench/terminal/Terminal.tsx +131 -0
- tools/bolt.diy/app/components/workbench/terminal/TerminalManager.tsx +68 -0
- tools/bolt.diy/app/components/workbench/terminal/TerminalTabs.tsx +277 -0
- tools/bolt.diy/app/components/workbench/terminal/theme.ts +36 -0
- tools/bolt.diy/app/components/workflow/WorkflowPhase.tsx +109 -0
- tools/bolt.diy/app/components/workflow/WorkflowStatus.tsx +60 -0
- tools/bolt.diy/app/components/workflow/WorkflowTimeline.tsx +150 -0
- tools/bolt.diy/app/entry.client.tsx +7 -0
- tools/bolt.diy/app/entry.server.tsx +80 -0
- tools/bolt.diy/app/root.tsx +156 -0
- tools/bolt.diy/app/routes/_index.tsx +175 -0
- tools/bolt.diy/app/routes/api.bug-report.ts +254 -0
- tools/bolt.diy/app/routes/api.chat.ts +463 -0
- tools/bolt.diy/app/routes/api.check-env-key.ts +41 -0
- tools/bolt.diy/app/routes/api.configured-providers.ts +110 -0
- tools/bolt.diy/app/routes/api.corporate-swarm-status.ts +55 -0
- tools/bolt.diy/app/routes/api.enhancer.ts +137 -0
- tools/bolt.diy/app/routes/api.export-api-keys.ts +44 -0
- tools/bolt.diy/app/routes/api.git-info.ts +69 -0
- tools/bolt.diy/app/routes/api.git-proxy.$.ts +178 -0
- tools/bolt.diy/app/routes/api.github-branches.ts +166 -0
- tools/bolt.diy/app/routes/api.github-deploy.ts +67 -0
- tools/bolt.diy/app/routes/api.github-stats.ts +198 -0
- tools/bolt.diy/app/routes/api.github-template.ts +242 -0
- tools/bolt.diy/app/routes/api.github-user.ts +287 -0
- tools/bolt.diy/app/routes/api.gitlab-branches.ts +143 -0
- tools/bolt.diy/app/routes/api.gitlab-deploy.ts +67 -0
- tools/bolt.diy/app/routes/api.gitlab-projects.ts +105 -0
- tools/bolt.diy/app/routes/api.health.ts +8 -0
- tools/bolt.diy/app/routes/api.llmcall.ts +298 -0
- tools/bolt.diy/app/routes/api.mandate.ts +351 -0
- tools/bolt.diy/app/routes/api.mcp-check.ts +16 -0
- tools/bolt.diy/app/routes/api.mcp-update-config.ts +23 -0
- tools/bolt.diy/app/routes/api.models.$provider.ts +2 -0
- tools/bolt.diy/app/routes/api.models.ts +90 -0
- tools/bolt.diy/app/routes/api.netlify-deploy.ts +240 -0
- tools/bolt.diy/app/routes/api.netlify-user.ts +142 -0
- tools/bolt.diy/app/routes/api.supabase-user.ts +199 -0
- tools/bolt.diy/app/routes/api.supabase.query.ts +92 -0
- tools/bolt.diy/app/routes/api.supabase.ts +56 -0
- tools/bolt.diy/app/routes/api.supabase.variables.ts +32 -0
- tools/bolt.diy/app/routes/api.system.diagnostics.ts +142 -0
- tools/bolt.diy/app/routes/api.system.disk-info.ts +311 -0
- tools/bolt.diy/app/routes/api.system.git-info.ts +332 -0
- tools/bolt.diy/app/routes/api.update.ts +21 -0
- tools/bolt.diy/app/routes/api.vercel-deploy.ts +497 -0
- tools/bolt.diy/app/routes/api.vercel-user.ts +161 -0
- tools/bolt.diy/app/routes/api.workflow-status.$proposalId.ts +309 -0
- tools/bolt.diy/app/routes/chat.$id.tsx +8 -0
- tools/bolt.diy/app/routes/execute.$mandateId.tsx +432 -0
- tools/bolt.diy/app/routes/git.tsx +25 -0
- tools/bolt.diy/app/routes/observability.$mandateId.tsx +50 -0
- tools/bolt.diy/app/routes/webcontainer.connect.$id.tsx +32 -0
- tools/bolt.diy/app/routes/webcontainer.preview.$id.tsx +97 -0
- tools/bolt.diy/app/routes/workflow.$proposalId.tsx +170 -0
- tools/bolt.diy/app/styles/animations.scss +49 -0
- tools/bolt.diy/app/styles/components/code.scss +9 -0
- tools/bolt.diy/app/styles/components/editor.scss +135 -0
- tools/bolt.diy/app/styles/components/resize-handle.scss +30 -0
- tools/bolt.diy/app/styles/components/terminal.scss +3 -0
- tools/bolt.diy/app/styles/components/toast.scss +23 -0
- tools/bolt.diy/app/styles/diff-view.css +72 -0
- tools/bolt.diy/app/styles/index.scss +73 -0
- tools/bolt.diy/app/styles/variables.scss +255 -0
- tools/bolt.diy/app/styles/z-index.scss +37 -0
- tools/bolt.diy/app/types/GitHub.ts +182 -0
- tools/bolt.diy/app/types/GitLab.ts +103 -0
- tools/bolt.diy/app/types/actions.ts +85 -0
- tools/bolt.diy/app/types/artifact.ts +5 -0
- tools/bolt.diy/app/types/context.ts +26 -0
- tools/bolt.diy/app/types/design-scheme.ts +93 -0
- tools/bolt.diy/app/types/global.d.ts +13 -0
- tools/bolt.diy/app/types/mandate.ts +333 -0
- tools/bolt.diy/app/types/model.ts +25 -0
- tools/bolt.diy/app/types/netlify.ts +94 -0
- tools/bolt.diy/app/types/supabase.ts +54 -0
- tools/bolt.diy/app/types/template.ts +8 -0
- tools/bolt.diy/app/types/terminal.ts +9 -0
- tools/bolt.diy/app/types/theme.ts +1 -0
- tools/bolt.diy/app/types/vercel.ts +67 -0
- tools/bolt.diy/app/utils/buffer.ts +29 -0
- tools/bolt.diy/app/utils/classNames.ts +65 -0
- tools/bolt.diy/app/utils/constants.ts +147 -0
- tools/bolt.diy/app/utils/debounce.ts +13 -0
- tools/bolt.diy/app/utils/debugLogger.ts +1284 -0
- tools/bolt.diy/app/utils/diff.spec.ts +11 -0
- tools/bolt.diy/app/utils/diff.ts +117 -0
- tools/bolt.diy/app/utils/easings.ts +3 -0
- tools/bolt.diy/app/utils/fileLocks.ts +96 -0
- tools/bolt.diy/app/utils/fileUtils.ts +121 -0
- tools/bolt.diy/app/utils/folderImport.ts +73 -0
- tools/bolt.diy/app/utils/formatSize.ts +12 -0
- tools/bolt.diy/app/utils/getLanguageFromExtension.ts +24 -0
- tools/bolt.diy/app/utils/githubStats.ts +9 -0
- tools/bolt.diy/app/utils/gitlabStats.ts +54 -0
- tools/bolt.diy/app/utils/logger.ts +162 -0
- tools/bolt.diy/app/utils/markdown.ts +155 -0
- tools/bolt.diy/app/utils/mobile.ts +4 -0
- tools/bolt.diy/app/utils/os.ts +4 -0
- tools/bolt.diy/app/utils/path.ts +19 -0
- tools/bolt.diy/app/utils/projectCommands.ts +197 -0
- tools/bolt.diy/app/utils/promises.ts +19 -0
- tools/bolt.diy/app/utils/react.ts +6 -0
- tools/bolt.diy/app/utils/sampler.ts +49 -0
- tools/bolt.diy/app/utils/selectStarterTemplate.ts +255 -0
- tools/bolt.diy/app/utils/shell.ts +384 -0
- tools/bolt.diy/app/utils/stacktrace.ts +27 -0
- tools/bolt.diy/app/utils/stripIndent.ts +23 -0
- tools/bolt.diy/app/utils/terminal.ts +11 -0
- tools/bolt.diy/app/utils/unreachable.ts +3 -0
- tools/bolt.diy/app/vite-env.d.ts +2 -0
- tools/bolt.diy/assets/entitlements.mac.plist +25 -0
- tools/bolt.diy/assets/icons/icon.icns +0 -0
- tools/bolt.diy/assets/icons/icon.ico +0 -0
- tools/bolt.diy/assets/icons/icon.png +0 -0
- tools/bolt.diy/bindings.js +78 -0
- tools/bolt.diy/bindings.sh +33 -0
- tools/bolt.diy/docker-compose.yaml +145 -0
- tools/bolt.diy/electron/main/index.ts +201 -0
- tools/bolt.diy/electron/main/tsconfig.json +30 -0
- tools/bolt.diy/electron/main/ui/menu.ts +29 -0
- tools/bolt.diy/electron/main/ui/window.ts +54 -0
- tools/bolt.diy/electron/main/utils/auto-update.ts +110 -0
- tools/bolt.diy/electron/main/utils/constants.ts +4 -0
- tools/bolt.diy/electron/main/utils/cookie.ts +40 -0
- tools/bolt.diy/electron/main/utils/reload.ts +35 -0
- tools/bolt.diy/electron/main/utils/serve.ts +71 -0
- tools/bolt.diy/electron/main/utils/store.ts +3 -0
- tools/bolt.diy/electron/main/utils/vite-server.ts +44 -0
- tools/bolt.diy/electron/main/vite.config.ts +44 -0
- tools/bolt.diy/electron/preload/index.ts +22 -0
- tools/bolt.diy/electron/preload/tsconfig.json +7 -0
- tools/bolt.diy/electron/preload/vite.config.ts +31 -0
- tools/bolt.diy/electron-builder.yml +64 -0
- tools/bolt.diy/electron-update.yml +4 -0
- tools/bolt.diy/eslint.config.mjs +57 -0
- tools/bolt.diy/functions/[[path]].ts +12 -0
- tools/bolt.diy/icons/angular.svg +1 -0
- tools/bolt.diy/icons/astro.svg +8 -0
- tools/bolt.diy/icons/chat.svg +1 -0
- tools/bolt.diy/icons/expo-brand.svg +1 -0
- tools/bolt.diy/icons/expo.svg +4 -0
- tools/bolt.diy/icons/logo-text.svg +1 -0
- tools/bolt.diy/icons/logo.svg +4 -0
- tools/bolt.diy/icons/mcp.svg +1 -0
- tools/bolt.diy/icons/nativescript.svg +1 -0
- tools/bolt.diy/icons/netlify.svg +10 -0
- tools/bolt.diy/icons/nextjs.svg +1 -0
- tools/bolt.diy/icons/nuxt.svg +1 -0
- tools/bolt.diy/icons/qwik.svg +1 -0
- tools/bolt.diy/icons/react.svg +1 -0
- tools/bolt.diy/icons/remix.svg +24 -0
- tools/bolt.diy/icons/remotion.svg +1 -0
- tools/bolt.diy/icons/shadcn.svg +21 -0
- tools/bolt.diy/icons/slidev.svg +60 -0
- tools/bolt.diy/icons/solidjs.svg +1 -0
- tools/bolt.diy/icons/stars.svg +1 -0
- tools/bolt.diy/icons/svelte.svg +1 -0
- tools/bolt.diy/icons/typescript.svg +1 -0
- tools/bolt.diy/icons/vite.svg +1 -0
- tools/bolt.diy/icons/vue.svg +1 -0
- tools/bolt.diy/load-context.ts +9 -0
- tools/bolt.diy/notarize.cjs +31 -0
- tools/bolt.diy/package.json +218 -0
- tools/bolt.diy/playwright.config.preview.ts +35 -0
- tools/bolt.diy/pre-start.cjs +26 -0
- tools/bolt.diy/public/apple-touch-icon-precomposed.png +0 -0
- tools/bolt.diy/public/apple-touch-icon.png +0 -0
- tools/bolt.diy/public/favicon.ico +0 -0
- tools/bolt.diy/public/favicon.svg +4 -0
- tools/bolt.diy/public/icons/AmazonBedrock.svg +1 -0
- tools/bolt.diy/public/icons/Anthropic.svg +4 -0
- tools/bolt.diy/public/icons/Cohere.svg +4 -0
- tools/bolt.diy/public/icons/Deepseek.svg +5 -0
- tools/bolt.diy/public/icons/Default.svg +4 -0
- tools/bolt.diy/public/icons/Google.svg +4 -0
- tools/bolt.diy/public/icons/Groq.svg +4 -0
- tools/bolt.diy/public/icons/HuggingFace.svg +4 -0
- tools/bolt.diy/public/icons/Hyperbolic.svg +3 -0
- tools/bolt.diy/public/icons/LMStudio.svg +5 -0
- tools/bolt.diy/public/icons/Mistral.svg +4 -0
- tools/bolt.diy/public/icons/Ollama.svg +4 -0
- tools/bolt.diy/public/icons/OpenAI.svg +4 -0
- tools/bolt.diy/public/icons/OpenAILike.svg +4 -0
- tools/bolt.diy/public/icons/OpenRouter.svg +4 -0
- tools/bolt.diy/public/icons/Perplexity.svg +4 -0
- tools/bolt.diy/public/icons/Together.svg +4 -0
- tools/bolt.diy/public/icons/xAI.svg +5 -0
- tools/bolt.diy/public/inspector-script.js +292 -0
- tools/bolt.diy/public/logo-dark-styled.png +0 -0
- tools/bolt.diy/public/logo-dark.png +0 -0
- tools/bolt.diy/public/logo-light-styled.png +0 -0
- tools/bolt.diy/public/logo-light.png +0 -0
- tools/bolt.diy/public/logo.svg +15 -0
- tools/bolt.diy/public/social_preview_index.jpg +0 -0
- tools/bolt.diy/scripts/clean.js +45 -0
- tools/bolt.diy/scripts/electron-dev.mjs +181 -0
- tools/bolt.diy/scripts/setup-env.sh +41 -0
- tools/bolt.diy/scripts/update-imports.sh +7 -0
- tools/bolt.diy/scripts/update.sh +52 -0
- tools/bolt.diy/services/execution-governor/Dockerfile +41 -0
- tools/bolt.diy/services/execution-governor/config.ts +42 -0
- tools/bolt.diy/services/execution-governor/index.ts +683 -0
- tools/bolt.diy/services/execution-governor/metrics.ts +141 -0
- tools/bolt.diy/services/execution-governor/package.json +31 -0
- tools/bolt.diy/services/execution-governor/priority-queue.ts +139 -0
- tools/bolt.diy/services/execution-governor/tsconfig.json +21 -0
- tools/bolt.diy/services/execution-governor/types.ts +145 -0
- tools/bolt.diy/services/headless-executor/Dockerfile +43 -0
- tools/bolt.diy/services/headless-executor/executor.ts +210 -0
- tools/bolt.diy/services/headless-executor/index.ts +323 -0
- tools/bolt.diy/services/headless-executor/package.json +27 -0
- tools/bolt.diy/services/headless-executor/tsconfig.json +21 -0
- tools/bolt.diy/services/headless-executor/types.ts +38 -0
- tools/bolt.diy/test-workflows.sh +240 -0
- tools/bolt.diy/tests/integration/corporate-swarm.test.ts +208 -0
- tools/bolt.diy/tests/mandates/budget-limited.json +34 -0
- tools/bolt.diy/tests/mandates/complex.json +53 -0
- tools/bolt.diy/tests/mandates/constraint-enforced.json +36 -0
- tools/bolt.diy/tests/mandates/simple.json +35 -0
- tools/bolt.diy/tsconfig.json +37 -0
- tools/bolt.diy/types/istextorbinary.d.ts +15 -0
- tools/bolt.diy/uno.config.ts +279 -0
- tools/bolt.diy/vite-electron.config.ts +76 -0
- tools/bolt.diy/vite.config.ts +112 -0
- tools/bolt.diy/worker-configuration.d.ts +22 -0
- tools/bolt.diy/wrangler.toml +6 -0
- tools/code_generator.py +461 -0
- tools/file_operations.py +465 -0
- tools/mandate_generator.py +337 -0
- tools/mcpClientUtils.py +1216 -0
- tools/sensors.py +285 -0
- utils/Agent_types.py +15 -0
- utils/AnyToStr.py +0 -0
- utils/HHCS.py +277 -0
- utils/__init__.py +30 -0
- utils/agent.py +3627 -0
- utils/aop.py +2948 -0
- utils/canonical.py +143 -0
- utils/conversation.py +1195 -0
- utils/doctrine_versioning +230 -0
- utils/formatter.py +474 -0
- utils/ledger.py +311 -0
- utils/out_types.py +16 -0
- utils/rollback.py +339 -0
- utils/router.py +929 -0
- utils/tui.py +1908 -0
utils/agent.py
ADDED
|
@@ -0,0 +1,3627 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Agent implementation for autonomous task execution.
|
|
3
|
+
|
|
4
|
+
Provides comprehensive agent functionality including LLM integration,
|
|
5
|
+
tool usage, conversation management, multi-modal capabilities, and
|
|
6
|
+
autonomous decision-making with safety and error handling.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import random
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
import traceback
|
|
17
|
+
import uuid
|
|
18
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
19
|
+
from datetime import datetime
|
|
20
|
+
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union
|
|
21
|
+
|
|
22
|
+
# Load environment variables from .env file
|
|
23
|
+
# Note: We don't override here to allow user scripts to control loading order
|
|
24
|
+
try:
|
|
25
|
+
from dotenv import load_dotenv
|
|
26
|
+
import os
|
|
27
|
+
env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
|
|
28
|
+
load_dotenv(dotenv_path=env_path, override=False)
|
|
29
|
+
except ImportError:
|
|
30
|
+
# dotenv not available, skip loading
|
|
31
|
+
pass
|
|
32
|
+
except Exception:
|
|
33
|
+
# .env file might not exist, that's okay
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
import toml
|
|
37
|
+
import yaml
|
|
38
|
+
from litellm import model_list
|
|
39
|
+
from litellm.exceptions import AuthenticationError, BadRequestError, InternalServerError
|
|
40
|
+
from litellm.utils import (get_max_tokens, supports_function_calling,
|
|
41
|
+
supports_parallel_function_calling, supports_vision)
|
|
42
|
+
from loguru import logger
|
|
43
|
+
from pydantic import BaseModel
|
|
44
|
+
|
|
45
|
+
from swarms.agents.ape_agent import auto_generate_prompt
|
|
46
|
+
from swarms.artifacts.main_artifact import Artifact
|
|
47
|
+
from swarms.prompts.agent_system_prompts import AGENT_SYSTEM_PROMPT_3
|
|
48
|
+
from swarms.prompts.max_loop_prompt import generate_reasoning_prompt
|
|
49
|
+
from swarms.prompts.multi_modal_autonomous_instruction_prompt import (
|
|
50
|
+
MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1,
|
|
51
|
+
)
|
|
52
|
+
from swarms.prompts.react_base_prompt import REACT_SYS_PROMPT
|
|
53
|
+
from swarms.prompts.safety_prompt import SAFETY_PROMPT
|
|
54
|
+
from swarms.prompts.tools import tool_sop_prompt
|
|
55
|
+
from swarms.schemas.agent_mcp_errors import (
|
|
56
|
+
AgentMCPConnectionError,
|
|
57
|
+
AgentMCPToolError,
|
|
58
|
+
)
|
|
59
|
+
from swarms.schemas.agent_step_schemas import ManySteps, Step
|
|
60
|
+
from swarms.schemas.base_schemas import (
|
|
61
|
+
AgentChatCompletionResponse,
|
|
62
|
+
)
|
|
63
|
+
from swarms.schemas.conversation_schema import ConversationSchema
|
|
64
|
+
from swarms.schemas.mcp_schemas import (
|
|
65
|
+
MCPConnection,
|
|
66
|
+
MultipleMCPConnections,
|
|
67
|
+
)
|
|
68
|
+
from swarms.structs.agent_roles import agent_roles
|
|
69
|
+
from swarms.structs.conversation import Conversation
|
|
70
|
+
from swarms.structs.ma_utils import set_random_models_for_agents
|
|
71
|
+
from swarms.structs.multi_agent_router import MultiAgentRouter
|
|
72
|
+
from swarms.structs.safe_loading import (
|
|
73
|
+
SafeLoaderUtils,
|
|
74
|
+
SafeStateManager,
|
|
75
|
+
)
|
|
76
|
+
from swarms.structs.transforms import (
|
|
77
|
+
MessageTransforms,
|
|
78
|
+
TransformConfig,
|
|
79
|
+
handle_transforms,
|
|
80
|
+
)
|
|
81
|
+
from swarms.telemetry.main import log_agent_data
|
|
82
|
+
from swarms.tools.base_tool import BaseTool
|
|
83
|
+
from swarms.tools.mcp_client_tools import (
|
|
84
|
+
execute_multiple_tools_on_multiple_mcp_servers_sync,
|
|
85
|
+
execute_tool_call_simple,
|
|
86
|
+
get_mcp_tools_sync,
|
|
87
|
+
get_tools_for_multiple_mcp_servers,
|
|
88
|
+
)
|
|
89
|
+
from swarms.tools.py_func_to_openai_func_str import (
|
|
90
|
+
convert_multiple_functions_to_openai_function_schema,
|
|
91
|
+
)
|
|
92
|
+
from swarms.utils.data_to_text import data_to_text
|
|
93
|
+
from swarms.utils.dynamic_context_window import dynamic_auto_chunking
|
|
94
|
+
from swarms.utils.file_processing import create_file_in_folder
|
|
95
|
+
from swarms.utils.formatter import formatter
|
|
96
|
+
from swarms.utils.generate_keys import generate_api_key
|
|
97
|
+
from swarms.utils.history_output_formatter import (
|
|
98
|
+
history_output_formatter,
|
|
99
|
+
)
|
|
100
|
+
from swarms.utils.index import (
|
|
101
|
+
exists,
|
|
102
|
+
format_data_structure,
|
|
103
|
+
)
|
|
104
|
+
from swarms.utils.litellm_tokenizer import count_tokens
|
|
105
|
+
from swarms.utils.litellm_wrapper import LiteLLM
|
|
106
|
+
from swarms.utils.output_types import OutputType
|
|
107
|
+
from swarms.utils.pdf_to_text import pdf_to_text
|
|
108
|
+
# Marketplace utils not available - optional feature
|
|
109
|
+
try:
|
|
110
|
+
from swarms.utils.swarms_marketplace_utils import (
|
|
111
|
+
add_prompt_to_marketplace,
|
|
112
|
+
)
|
|
113
|
+
except ImportError:
|
|
114
|
+
def add_prompt_to_marketplace(*args, **kwargs):
|
|
115
|
+
"""Placeholder for marketplace functionality when not available."""
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def stop_when_repeats(response: str) -> bool:
|
|
120
|
+
"""Check if response contains stop signal.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
response: Response string to check.
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
True if 'stop' appears in response (case-insensitive).
|
|
127
|
+
"""
|
|
128
|
+
return "stop" in response.lower()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def parse_done_token(response: str) -> bool:
|
|
132
|
+
"""Check if response contains done token.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
response: Response string to check.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
True if '<DONE>' token is present.
|
|
139
|
+
"""
|
|
140
|
+
return "<DONE>" in response
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def agent_id() -> str:
|
|
144
|
+
"""Generate unique agent identifier.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
UUID-based agent identifier string.
|
|
148
|
+
"""
|
|
149
|
+
return f"agent-{uuid.uuid4().hex}"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
ToolUsageType = Union[BaseModel, Dict[str, Any]]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class AgentError(Exception):
|
|
156
|
+
"""Base exception for all agent-related errors."""
|
|
157
|
+
pass
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class AgentInitializationError(AgentError):
|
|
161
|
+
"""Raised when agent initialization fails.
|
|
162
|
+
|
|
163
|
+
Indicates configuration or parameter issues during agent setup.
|
|
164
|
+
"""
|
|
165
|
+
pass
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class AgentRunError(AgentError):
|
|
169
|
+
"""Raised when agent execution encounters an error.
|
|
170
|
+
|
|
171
|
+
Indicates issues with task setup or execution environment.
|
|
172
|
+
"""
|
|
173
|
+
pass
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class AgentLLMError(AgentError):
|
|
177
|
+
"""Raised when LLM operations fail.
|
|
178
|
+
|
|
179
|
+
Indicates model availability or compatibility issues.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
pass
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class AgentToolError(AgentError):
|
|
186
|
+
"""Raised when tool utilization fails.
|
|
187
|
+
|
|
188
|
+
Indicates tool configuration or availability issues.
|
|
189
|
+
"""
|
|
190
|
+
pass
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class AgentMemoryError(AgentError):
|
|
194
|
+
"""Raised when memory operations fail.
|
|
195
|
+
|
|
196
|
+
Indicates memory resource allocation or accessibility issues.
|
|
197
|
+
"""
|
|
198
|
+
pass
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class AgentLLMInitializationError(AgentError):
|
|
202
|
+
"""Raised when LLM initialization fails.
|
|
203
|
+
|
|
204
|
+
Indicates LLM configuration or parameter issues.
|
|
205
|
+
"""
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class AgentToolExecutionError(AgentError):
|
|
210
|
+
"""Raised when tool execution fails.
|
|
211
|
+
|
|
212
|
+
Indicates tool configuration or availability issues during execution.
|
|
213
|
+
"""
|
|
214
|
+
pass
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Agent:
|
|
218
|
+
"""Autonomous agent for LLM-based task execution with tool integration.
|
|
219
|
+
|
|
220
|
+
Connects language models with tools, long-term memory, and document
|
|
221
|
+
processing capabilities. Supports multi-modal inputs, autonomous decision-making,
|
|
222
|
+
and comprehensive error handling.
|
|
223
|
+
|
|
224
|
+
Key Features:
|
|
225
|
+
- LLM integration with multiple model providers
|
|
226
|
+
- Tool usage and function calling
|
|
227
|
+
- Long-term memory management
|
|
228
|
+
- Document ingestion (PDF, TXT, Markdown, JSON, etc.)
|
|
229
|
+
- Multi-modal capabilities (text, vision)
|
|
230
|
+
- Autonomous loop execution with stopping conditions
|
|
231
|
+
- State persistence and recovery
|
|
232
|
+
- Self-healing and error recovery
|
|
233
|
+
|
|
234
|
+
Attributes:
|
|
235
|
+
agent_name: Unique identifier for the agent instance.
|
|
236
|
+
agent_description: Human-readable description of agent purpose.
|
|
237
|
+
system_prompt: System-level instructions for agent behavior.
|
|
238
|
+
tools: List of available tools for agent execution.
|
|
239
|
+
max_loops: Maximum number of execution loops.
|
|
240
|
+
conversation: Conversation history manager.
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
def __init__(
|
|
244
|
+
self,
|
|
245
|
+
id: Optional[str] = agent_id(),
|
|
246
|
+
llm: Optional[Any] = None,
|
|
247
|
+
template: Optional[str] = None,
|
|
248
|
+
max_loops: Optional[Union[int, str]] = 1,
|
|
249
|
+
stopping_condition: Optional[Callable[[str], bool]] = None,
|
|
250
|
+
loop_interval: Optional[int] = 0,
|
|
251
|
+
retry_attempts: Optional[int] = 3,
|
|
252
|
+
retry_interval: Optional[int] = 1,
|
|
253
|
+
return_history: Optional[bool] = False,
|
|
254
|
+
stopping_token: Optional[str] = None,
|
|
255
|
+
dynamic_loops: Optional[bool] = False,
|
|
256
|
+
interactive: Optional[bool] = False,
|
|
257
|
+
dashboard: Optional[bool] = False,
|
|
258
|
+
agent_name: Optional[str] = "swarm-worker-01",
|
|
259
|
+
agent_description: Optional[str] = None,
|
|
260
|
+
system_prompt: Optional[str] = AGENT_SYSTEM_PROMPT_3,
|
|
261
|
+
# TODO: Change to callable, then parse the callable to a string
|
|
262
|
+
tools: List[Callable] = None,
|
|
263
|
+
dynamic_temperature_enabled: Optional[bool] = False,
|
|
264
|
+
sop: Optional[str] = None,
|
|
265
|
+
sop_list: Optional[List[str]] = None,
|
|
266
|
+
saved_state_path: Optional[str] = None,
|
|
267
|
+
autosave: Optional[bool] = False,
|
|
268
|
+
context_length: Optional[int] = 8192,
|
|
269
|
+
transforms: Optional[Union[TransformConfig, dict]] = None,
|
|
270
|
+
user_name: Optional[str] = "Human",
|
|
271
|
+
self_healing_enabled: Optional[bool] = False,
|
|
272
|
+
code_interpreter: Optional[bool] = False,
|
|
273
|
+
multi_modal: Optional[bool] = None,
|
|
274
|
+
pdf_path: Optional[str] = None,
|
|
275
|
+
list_of_pdf: Optional[str] = None,
|
|
276
|
+
tokenizer: Optional[Any] = None,
|
|
277
|
+
long_term_memory: Optional[Union[Callable, Any]] = None,
|
|
278
|
+
fallback_model_name: Optional[str] = None,
|
|
279
|
+
fallback_models: Optional[List[str]] = None,
|
|
280
|
+
preset_stopping_token: Optional[bool] = False,
|
|
281
|
+
traceback: Optional[Any] = None,
|
|
282
|
+
traceback_handlers: Optional[Any] = None,
|
|
283
|
+
streaming_on: Optional[bool] = False,
|
|
284
|
+
stream: Optional[bool] = False,
|
|
285
|
+
docs: List[str] = None,
|
|
286
|
+
docs_folder: Optional[str] = None,
|
|
287
|
+
verbose: Optional[bool] = False,
|
|
288
|
+
parser: Optional[Callable] = None,
|
|
289
|
+
best_of_n: Optional[int] = None,
|
|
290
|
+
callback: Optional[Callable] = None,
|
|
291
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
292
|
+
callbacks: Optional[List[Callable]] = None,
|
|
293
|
+
search_algorithm: Optional[Callable] = None,
|
|
294
|
+
logs_to_filename: Optional[str] = None,
|
|
295
|
+
evaluator: Optional[Callable] = None, # Custom LLM or agent
|
|
296
|
+
stopping_func: Optional[Callable] = None,
|
|
297
|
+
custom_loop_condition: Optional[Callable] = None,
|
|
298
|
+
sentiment_threshold: Optional[
|
|
299
|
+
float
|
|
300
|
+
] = None, # Evaluate on output using an external model
|
|
301
|
+
custom_exit_command: Optional[str] = "exit",
|
|
302
|
+
sentiment_analyzer: Optional[Callable] = None,
|
|
303
|
+
limit_tokens_from_string: Optional[Callable] = None,
|
|
304
|
+
# [Tools]
|
|
305
|
+
custom_tools_prompt: Optional[Callable] = None,
|
|
306
|
+
tool_schema: ToolUsageType = None,
|
|
307
|
+
output_type: OutputType = "str-all-except-first",
|
|
308
|
+
function_calling_type: str = "json",
|
|
309
|
+
output_cleaner: Optional[Callable] = None,
|
|
310
|
+
function_calling_format_type: Optional[str] = "OpenAI",
|
|
311
|
+
list_base_models: Optional[List[BaseModel]] = None,
|
|
312
|
+
metadata_output_type: str = "json",
|
|
313
|
+
state_save_file_type: str = "json",
|
|
314
|
+
chain_of_thoughts: bool = False,
|
|
315
|
+
algorithm_of_thoughts: bool = False,
|
|
316
|
+
tree_of_thoughts: bool = False,
|
|
317
|
+
tool_choice: str = "auto",
|
|
318
|
+
rules: str = None, # type: ignore
|
|
319
|
+
planning: Optional[str] = False,
|
|
320
|
+
planning_prompt: Optional[str] = None,
|
|
321
|
+
custom_planning_prompt: str = None,
|
|
322
|
+
memory_chunk_size: int = 2000,
|
|
323
|
+
agent_ops_on: bool = False,
|
|
324
|
+
log_directory: str = None,
|
|
325
|
+
tool_system_prompt: str = tool_sop_prompt(),
|
|
326
|
+
max_tokens: int = 4096,
|
|
327
|
+
frequency_penalty: float = 0.8,
|
|
328
|
+
presence_penalty: float = 0.6,
|
|
329
|
+
temperature: float = 0.5,
|
|
330
|
+
workspace_dir: str = "agent_workspace",
|
|
331
|
+
timeout: Optional[int] = None,
|
|
332
|
+
# short_memory: Optional[str] = None,
|
|
333
|
+
created_at: float = time.time(),
|
|
334
|
+
return_step_meta: Optional[bool] = False,
|
|
335
|
+
tags: Optional[List[str]] = None,
|
|
336
|
+
step_pool: List[Step] = [],
|
|
337
|
+
print_every_step: Optional[bool] = False,
|
|
338
|
+
time_created: Optional[str] = time.strftime(
|
|
339
|
+
"%Y-%m-%d %H:%M:%S", time.localtime()
|
|
340
|
+
),
|
|
341
|
+
agent_output: ManySteps = None,
|
|
342
|
+
data_memory: Optional[Callable] = None,
|
|
343
|
+
load_yaml_path: str = None,
|
|
344
|
+
auto_generate_prompt: bool = False,
|
|
345
|
+
rag_every_loop: bool = False,
|
|
346
|
+
plan_enabled: bool = False,
|
|
347
|
+
artifacts_on: bool = False,
|
|
348
|
+
artifacts_output_path: str = None,
|
|
349
|
+
artifacts_file_extension: str = None,
|
|
350
|
+
device: str = "cpu",
|
|
351
|
+
all_cores: bool = True,
|
|
352
|
+
device_id: int = 0,
|
|
353
|
+
scheduled_run_date: Optional[datetime] = None,
|
|
354
|
+
do_not_use_cluster_ops: bool = True,
|
|
355
|
+
all_gpus: bool = False,
|
|
356
|
+
model_name: str = None,
|
|
357
|
+
llm_args: dict = None,
|
|
358
|
+
load_state_path: str = None,
|
|
359
|
+
role: agent_roles = "worker",
|
|
360
|
+
print_on: bool = True,
|
|
361
|
+
tools_list_dictionary: Optional[List[Dict[str, Any]]] = None,
|
|
362
|
+
mcp_url: Optional[Union[str, MCPConnection]] = None,
|
|
363
|
+
mcp_urls: List[str] = None,
|
|
364
|
+
react_on: bool = False,
|
|
365
|
+
safety_prompt_on: bool = False,
|
|
366
|
+
random_models_on: bool = False,
|
|
367
|
+
mcp_config: Optional[MCPConnection] = None,
|
|
368
|
+
mcp_configs: Optional[MultipleMCPConnections] = None,
|
|
369
|
+
top_p: Optional[float] = 0.90,
|
|
370
|
+
conversation_schema: Optional[ConversationSchema] = None,
|
|
371
|
+
llm_base_url: Optional[str] = None,
|
|
372
|
+
llm_api_key: Optional[str] = None,
|
|
373
|
+
tool_call_summary: bool = True,
|
|
374
|
+
output_raw_json_from_tool_call: bool = False,
|
|
375
|
+
summarize_multiple_images: bool = False,
|
|
376
|
+
tool_retry_attempts: int = 3,
|
|
377
|
+
reasoning_prompt_on: bool = True,
|
|
378
|
+
dynamic_context_window: bool = True,
|
|
379
|
+
show_tool_execution_output: bool = True,
|
|
380
|
+
reasoning_effort: str = None,
|
|
381
|
+
drop_params: bool = True,
|
|
382
|
+
thinking_tokens: int = None,
|
|
383
|
+
reasoning_enabled: bool = False,
|
|
384
|
+
handoffs: Optional[Union[Sequence[Callable], Any]] = None,
|
|
385
|
+
capabilities: Optional[List[str]] = None,
|
|
386
|
+
mode: Literal["interactive", "fast", "standard"] = "standard",
|
|
387
|
+
publish_to_marketplace: bool = False,
|
|
388
|
+
use_cases: Optional[List[Dict[str, Any]]] = None,
|
|
389
|
+
*args,
|
|
390
|
+
**kwargs,
|
|
391
|
+
):
|
|
392
|
+
# super().__init__(*args, **kwargs)
|
|
393
|
+
self.id = id
|
|
394
|
+
self.llm = llm
|
|
395
|
+
self.template = template
|
|
396
|
+
self.max_loops = max_loops
|
|
397
|
+
self.stopping_condition = stopping_condition
|
|
398
|
+
self.loop_interval = loop_interval
|
|
399
|
+
self.retry_attempts = retry_attempts
|
|
400
|
+
self.retry_interval = retry_interval
|
|
401
|
+
self.task = None
|
|
402
|
+
self.stopping_token = stopping_token
|
|
403
|
+
self.interactive = interactive
|
|
404
|
+
self.dashboard = dashboard
|
|
405
|
+
self.saved_state_path = saved_state_path
|
|
406
|
+
self.return_history = return_history
|
|
407
|
+
self.dynamic_temperature_enabled = dynamic_temperature_enabled
|
|
408
|
+
self.dynamic_loops = dynamic_loops
|
|
409
|
+
self.user_name = user_name
|
|
410
|
+
self.context_length = context_length
|
|
411
|
+
|
|
412
|
+
self.sop = sop
|
|
413
|
+
self.sop_list = sop_list
|
|
414
|
+
self.tools = tools
|
|
415
|
+
self.system_prompt = system_prompt
|
|
416
|
+
self.agent_name = agent_name
|
|
417
|
+
self.agent_description = agent_description
|
|
418
|
+
# self.saved_state_path = f"{self.agent_name}_{generate_api_key(prefix='agent-')}_state.json"
|
|
419
|
+
self.saved_state_path = (
|
|
420
|
+
f"{generate_api_key(prefix='agent-')}_state.json"
|
|
421
|
+
)
|
|
422
|
+
self.autosave = autosave
|
|
423
|
+
self.response_filters = []
|
|
424
|
+
self.self_healing_enabled = self_healing_enabled
|
|
425
|
+
self.code_interpreter = code_interpreter
|
|
426
|
+
self.multi_modal = multi_modal
|
|
427
|
+
self.pdf_path = pdf_path
|
|
428
|
+
self.list_of_pdf = list_of_pdf
|
|
429
|
+
self.tokenizer = tokenizer
|
|
430
|
+
self.long_term_memory = long_term_memory
|
|
431
|
+
self.preset_stopping_token = preset_stopping_token
|
|
432
|
+
self.traceback = traceback
|
|
433
|
+
self.traceback_handlers = traceback_handlers
|
|
434
|
+
self.streaming_on = streaming_on
|
|
435
|
+
self.stream = stream
|
|
436
|
+
self.docs = docs
|
|
437
|
+
self.docs_folder = docs_folder
|
|
438
|
+
self.verbose = verbose
|
|
439
|
+
self.parser = parser
|
|
440
|
+
self.best_of_n = best_of_n
|
|
441
|
+
self.callback = callback
|
|
442
|
+
self.metadata = metadata
|
|
443
|
+
self.callbacks = callbacks
|
|
444
|
+
self.search_algorithm = search_algorithm
|
|
445
|
+
self.logs_to_filename = logs_to_filename
|
|
446
|
+
self.evaluator = evaluator
|
|
447
|
+
self.stopping_func = stopping_func
|
|
448
|
+
self.custom_loop_condition = custom_loop_condition
|
|
449
|
+
self.sentiment_threshold = sentiment_threshold
|
|
450
|
+
self.custom_exit_command = custom_exit_command
|
|
451
|
+
self.sentiment_analyzer = sentiment_analyzer
|
|
452
|
+
self.limit_tokens_from_string = limit_tokens_from_string
|
|
453
|
+
self.tool_schema = tool_schema
|
|
454
|
+
self.output_type = output_type
|
|
455
|
+
self.function_calling_type = function_calling_type
|
|
456
|
+
self.output_cleaner = output_cleaner
|
|
457
|
+
self.function_calling_format_type = (
|
|
458
|
+
function_calling_format_type
|
|
459
|
+
)
|
|
460
|
+
self.list_base_models = list_base_models
|
|
461
|
+
self.metadata_output_type = metadata_output_type
|
|
462
|
+
self.state_save_file_type = state_save_file_type
|
|
463
|
+
self.chain_of_thoughts = chain_of_thoughts
|
|
464
|
+
self.algorithm_of_thoughts = algorithm_of_thoughts
|
|
465
|
+
self.tree_of_thoughts = tree_of_thoughts
|
|
466
|
+
self.tool_choice = tool_choice
|
|
467
|
+
self.planning = planning
|
|
468
|
+
self.planning_prompt = planning_prompt
|
|
469
|
+
self.custom_planning_prompt = custom_planning_prompt
|
|
470
|
+
self.rules = rules
|
|
471
|
+
self.custom_tools_prompt = custom_tools_prompt
|
|
472
|
+
self.memory_chunk_size = memory_chunk_size
|
|
473
|
+
self.agent_ops_on = agent_ops_on
|
|
474
|
+
self.log_directory = log_directory
|
|
475
|
+
self.tool_system_prompt = tool_system_prompt
|
|
476
|
+
self.max_tokens = max_tokens
|
|
477
|
+
self.frequency_penalty = frequency_penalty
|
|
478
|
+
self.presence_penalty = presence_penalty
|
|
479
|
+
self.temperature = temperature
|
|
480
|
+
self.workspace_dir = workspace_dir
|
|
481
|
+
self.timeout = timeout
|
|
482
|
+
self.created_at = created_at
|
|
483
|
+
self.return_step_meta = return_step_meta
|
|
484
|
+
self.tags = tags
|
|
485
|
+
self.use_cases = use_cases
|
|
486
|
+
self.name = agent_name
|
|
487
|
+
self.description = agent_description
|
|
488
|
+
self.agent_output = agent_output
|
|
489
|
+
self.step_pool = step_pool
|
|
490
|
+
self.print_every_step = print_every_step
|
|
491
|
+
self.time_created = time_created
|
|
492
|
+
self.data_memory = data_memory
|
|
493
|
+
self.load_yaml_path = load_yaml_path
|
|
494
|
+
self.tokenizer = tokenizer
|
|
495
|
+
self.auto_generate_prompt = auto_generate_prompt
|
|
496
|
+
self.rag_every_loop = rag_every_loop
|
|
497
|
+
self.plan_enabled = plan_enabled
|
|
498
|
+
self.artifacts_on = artifacts_on
|
|
499
|
+
self.artifacts_output_path = artifacts_output_path
|
|
500
|
+
self.artifacts_file_extension = artifacts_file_extension
|
|
501
|
+
self.device = device
|
|
502
|
+
self.all_cores = all_cores
|
|
503
|
+
self.device_id = device_id
|
|
504
|
+
self.scheduled_run_date = scheduled_run_date
|
|
505
|
+
self.do_not_use_cluster_ops = do_not_use_cluster_ops
|
|
506
|
+
self.all_gpus = all_gpus
|
|
507
|
+
self.model_name = model_name
|
|
508
|
+
self.llm_args = llm_args
|
|
509
|
+
self.load_state_path = load_state_path
|
|
510
|
+
self.role = role
|
|
511
|
+
self.print_on = print_on
|
|
512
|
+
self.tools_list_dictionary = tools_list_dictionary
|
|
513
|
+
self.mcp_url = mcp_url
|
|
514
|
+
self.mcp_urls = mcp_urls
|
|
515
|
+
self.react_on = react_on
|
|
516
|
+
self.safety_prompt_on = safety_prompt_on
|
|
517
|
+
self.random_models_on = random_models_on
|
|
518
|
+
self.mcp_config = mcp_config
|
|
519
|
+
self.top_p = top_p
|
|
520
|
+
self.conversation_schema = conversation_schema
|
|
521
|
+
self.llm_base_url = llm_base_url
|
|
522
|
+
self.llm_api_key = llm_api_key
|
|
523
|
+
self.tool_call_summary = tool_call_summary
|
|
524
|
+
self.output_raw_json_from_tool_call = (
|
|
525
|
+
output_raw_json_from_tool_call
|
|
526
|
+
)
|
|
527
|
+
self.summarize_multiple_images = summarize_multiple_images
|
|
528
|
+
self.tool_retry_attempts = tool_retry_attempts
|
|
529
|
+
self.reasoning_prompt_on = reasoning_prompt_on
|
|
530
|
+
self.dynamic_context_window = dynamic_context_window
|
|
531
|
+
self.show_tool_execution_output = show_tool_execution_output
|
|
532
|
+
self.mcp_configs = mcp_configs
|
|
533
|
+
self.reasoning_effort = reasoning_effort
|
|
534
|
+
self.drop_params = drop_params
|
|
535
|
+
self.thinking_tokens = thinking_tokens
|
|
536
|
+
self.reasoning_enabled = reasoning_enabled
|
|
537
|
+
self.fallback_model_name = fallback_model_name
|
|
538
|
+
self.handoffs = handoffs
|
|
539
|
+
self.capabilities = capabilities
|
|
540
|
+
self.mode = mode
|
|
541
|
+
self.publish_to_marketplace = publish_to_marketplace
|
|
542
|
+
|
|
543
|
+
# Initialize transforms
|
|
544
|
+
if transforms is None:
|
|
545
|
+
self.transforms = None
|
|
546
|
+
elif isinstance(transforms, TransformConfig):
|
|
547
|
+
self.transforms = MessageTransforms(transforms)
|
|
548
|
+
elif isinstance(transforms, dict):
|
|
549
|
+
config = TransformConfig(**transforms)
|
|
550
|
+
self.transforms = MessageTransforms(config)
|
|
551
|
+
else:
|
|
552
|
+
pass
|
|
553
|
+
|
|
554
|
+
self.fallback_models = fallback_models or []
|
|
555
|
+
self.current_model_index = 0
|
|
556
|
+
self.model_attempts = {}
|
|
557
|
+
|
|
558
|
+
# If fallback_models is provided, use the first model as the primary model
|
|
559
|
+
if self.fallback_models and not self.model_name:
|
|
560
|
+
self.model_name = self.fallback_models[0]
|
|
561
|
+
|
|
562
|
+
# self.init_handling()
|
|
563
|
+
self.setup_config()
|
|
564
|
+
|
|
565
|
+
# Initialize the short memory
|
|
566
|
+
self.short_memory = self.short_memory_init()
|
|
567
|
+
|
|
568
|
+
# Initialize the tools
|
|
569
|
+
self.tool_struct = self.setup_tools()
|
|
570
|
+
|
|
571
|
+
if exists(self.docs_folder):
|
|
572
|
+
self.get_docs_from_doc_folders()
|
|
573
|
+
|
|
574
|
+
if exists(self.tool_schema) or exists(self.list_base_models):
|
|
575
|
+
self.handle_tool_schema_ops()
|
|
576
|
+
|
|
577
|
+
if exists(self.sop) or exists(self.sop_list):
|
|
578
|
+
self.handle_sop_ops()
|
|
579
|
+
|
|
580
|
+
if self.interactive is True:
|
|
581
|
+
self.reasoning_prompt_on = False
|
|
582
|
+
|
|
583
|
+
if self.reasoning_prompt_on is True and (
|
|
584
|
+
(isinstance(self.max_loops, int) and self.max_loops >= 2)
|
|
585
|
+
or self.max_loops == "auto"
|
|
586
|
+
):
|
|
587
|
+
self.system_prompt += generate_reasoning_prompt(
|
|
588
|
+
self.max_loops
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
if self.react_on is True:
|
|
592
|
+
self.system_prompt += REACT_SYS_PROMPT
|
|
593
|
+
|
|
594
|
+
if self.autosave is True:
|
|
595
|
+
log_agent_data(self.to_dict())
|
|
596
|
+
|
|
597
|
+
if exists(self.tools):
|
|
598
|
+
self.tool_handling()
|
|
599
|
+
|
|
600
|
+
if self.llm is None:
|
|
601
|
+
self.llm = self.llm_handling()
|
|
602
|
+
|
|
603
|
+
if self.random_models_on is True:
|
|
604
|
+
self.model_name = set_random_models_for_agents()
|
|
605
|
+
|
|
606
|
+
if self.dashboard is True:
|
|
607
|
+
self.print_dashboard()
|
|
608
|
+
|
|
609
|
+
self.reliability_check()
|
|
610
|
+
|
|
611
|
+
if self.mode == "fast":
|
|
612
|
+
self.print_on = False
|
|
613
|
+
self.verbose = False
|
|
614
|
+
|
|
615
|
+
if self.publish_to_marketplace is True:
|
|
616
|
+
# Join tags and capabilities into a single string
|
|
617
|
+
tags_and_capabilities = ", ".join(
|
|
618
|
+
self.tags + self.capabilities
|
|
619
|
+
if self.tags and self.capabilities
|
|
620
|
+
else None
|
|
621
|
+
)
|
|
622
|
+
|
|
623
|
+
if self.use_cases is None:
|
|
624
|
+
raise AgentInitializationError(
|
|
625
|
+
"Use cases are required when publishing to the marketplace. The schema is a list of dictionaries with 'title' and 'description' keys."
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
add_prompt_to_marketplace(
|
|
629
|
+
name=self.agent_name,
|
|
630
|
+
prompt=self.short_memory.get_str(),
|
|
631
|
+
description=self.agent_description,
|
|
632
|
+
tags=tags_and_capabilities,
|
|
633
|
+
category="research",
|
|
634
|
+
use_cases=(
|
|
635
|
+
self.use_cases if self.use_cases else None
|
|
636
|
+
),
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
def handle_handoffs(self, task: Optional[str] = None):
|
|
640
|
+
router = MultiAgentRouter(
|
|
641
|
+
name=self.agent_name,
|
|
642
|
+
description=self.agent_description,
|
|
643
|
+
agents=self.handoffs,
|
|
644
|
+
model=self.model_name,
|
|
645
|
+
temperature=self.temperature,
|
|
646
|
+
system_prompt=self.system_prompt,
|
|
647
|
+
output_type=self.output_type,
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
return router.run(task=task)
|
|
651
|
+
|
|
652
|
+
def setup_tools(self):
|
|
653
|
+
return BaseTool(
|
|
654
|
+
tools=self.tools,
|
|
655
|
+
verbose=self.verbose,
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
def tool_handling(self):
|
|
659
|
+
|
|
660
|
+
# Convert all the tools into a list of dictionaries
|
|
661
|
+
self.tools_list_dictionary = (
|
|
662
|
+
convert_multiple_functions_to_openai_function_schema(
|
|
663
|
+
self.tools
|
|
664
|
+
)
|
|
665
|
+
)
|
|
666
|
+
|
|
667
|
+
self.short_memory.add(
|
|
668
|
+
role=self.agent_name,
|
|
669
|
+
content=self.tools_list_dictionary,
|
|
670
|
+
)
|
|
671
|
+
|
|
672
|
+
def short_memory_init(self):
|
|
673
|
+
# Assemble initial prompt context as a dict, update conditionally, then compose as string
|
|
674
|
+
prompt_dict = {}
|
|
675
|
+
|
|
676
|
+
if self.agent_name is not None:
|
|
677
|
+
prompt_dict["name"] = f"Your Name: {self.agent_name}"
|
|
678
|
+
if self.agent_description is not None:
|
|
679
|
+
prompt_dict["description"] = (
|
|
680
|
+
f"Your Description: {self.agent_description}"
|
|
681
|
+
)
|
|
682
|
+
if self.system_prompt is not None:
|
|
683
|
+
prompt_dict["instructions"] = (
|
|
684
|
+
f"Your Instructions: {self.system_prompt}"
|
|
685
|
+
)
|
|
686
|
+
|
|
687
|
+
# Compose prompt, prioritizing adding everything present in the dict
|
|
688
|
+
# (entries are newline separated, order: name → description → instructions)
|
|
689
|
+
prompt = ""
|
|
690
|
+
for key in ["name", "description", "instructions"]:
|
|
691
|
+
if key in prompt_dict:
|
|
692
|
+
prompt += f"\n {prompt_dict[key]} \n"
|
|
693
|
+
|
|
694
|
+
if self.safety_prompt_on is True:
|
|
695
|
+
prompt += SAFETY_PROMPT
|
|
696
|
+
|
|
697
|
+
# Initialize the short term memory
|
|
698
|
+
memory = Conversation(
|
|
699
|
+
name=f"{self.agent_name}_id_{self.id}_conversation",
|
|
700
|
+
system_prompt=prompt,
|
|
701
|
+
user=self.user_name,
|
|
702
|
+
rules=self.rules,
|
|
703
|
+
token_count=False,
|
|
704
|
+
message_id_on=False,
|
|
705
|
+
time_enabled=True,
|
|
706
|
+
dynamic_context_window=self.dynamic_context_window,
|
|
707
|
+
tokenizer_model_name=self.model_name,
|
|
708
|
+
context_length=self.context_length,
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
return memory
|
|
712
|
+
|
|
713
|
+
def llm_handling(self, *args, **kwargs):
|
|
714
|
+
"""Initialize the LiteLLM instance with combined configuration from all sources.
|
|
715
|
+
|
|
716
|
+
This method combines llm_args, tools_list_dictionary, MCP tools, and any additional
|
|
717
|
+
arguments passed to this method into a single unified configuration.
|
|
718
|
+
|
|
719
|
+
Args:
|
|
720
|
+
*args: Positional arguments that can be used for additional configuration.
|
|
721
|
+
If a single dictionary is passed, it will be merged into the configuration.
|
|
722
|
+
Other types of args will be stored under 'additional_args' key.
|
|
723
|
+
**kwargs: Keyword arguments that will be merged into the LiteLLM configuration.
|
|
724
|
+
These take precedence over existing configuration.
|
|
725
|
+
|
|
726
|
+
Returns:
|
|
727
|
+
LiteLLM: The initialized LiteLLM instance
|
|
728
|
+
"""
|
|
729
|
+
|
|
730
|
+
if self.model_name is None:
|
|
731
|
+
self.model_name = "gpt-4o-mini"
|
|
732
|
+
|
|
733
|
+
# Use current model (which may be a fallback) only if fallbacks are configured
|
|
734
|
+
if self.fallback_models:
|
|
735
|
+
current_model = self.get_current_model()
|
|
736
|
+
else:
|
|
737
|
+
current_model = self.model_name
|
|
738
|
+
|
|
739
|
+
# Determine if parallel tool calls should be enabled
|
|
740
|
+
if exists(self.tools) and len(self.tools) >= 2:
|
|
741
|
+
parallel_tool_calls = True
|
|
742
|
+
elif exists(self.mcp_url) or exists(self.mcp_urls):
|
|
743
|
+
parallel_tool_calls = True
|
|
744
|
+
elif exists(self.mcp_config):
|
|
745
|
+
parallel_tool_calls = True
|
|
746
|
+
else:
|
|
747
|
+
parallel_tool_calls = False
|
|
748
|
+
|
|
749
|
+
try:
|
|
750
|
+
# Get API key from parameter or environment
|
|
751
|
+
api_key = self.llm_api_key or os.getenv('OPENAI_API_KEY')
|
|
752
|
+
|
|
753
|
+
# Base configuration that's always included
|
|
754
|
+
common_args = {
|
|
755
|
+
"model_name": current_model,
|
|
756
|
+
"temperature": self.temperature,
|
|
757
|
+
"max_tokens": self.max_tokens,
|
|
758
|
+
"system_prompt": self.system_prompt,
|
|
759
|
+
"stream": self.streaming_on,
|
|
760
|
+
"top_p": self.top_p,
|
|
761
|
+
"retries": self.retry_attempts,
|
|
762
|
+
"reasoning_effort": self.reasoning_effort,
|
|
763
|
+
"thinking_tokens": self.thinking_tokens,
|
|
764
|
+
"reasoning_enabled": self.reasoning_enabled,
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
# Add API key if available
|
|
768
|
+
if api_key:
|
|
769
|
+
common_args["api_key"] = api_key
|
|
770
|
+
|
|
771
|
+
# Add base URL if provided
|
|
772
|
+
if self.llm_base_url:
|
|
773
|
+
common_args["api_base"] = self.llm_base_url
|
|
774
|
+
|
|
775
|
+
# Initialize tools_list_dictionary, if applicable
|
|
776
|
+
tools_list = []
|
|
777
|
+
|
|
778
|
+
# Append tools from different sources
|
|
779
|
+
if self.tools_list_dictionary is not None:
|
|
780
|
+
tools_list.extend(self.tools_list_dictionary)
|
|
781
|
+
|
|
782
|
+
if exists(self.mcp_url) or exists(self.mcp_urls):
|
|
783
|
+
if self.verbose:
|
|
784
|
+
logger.info(
|
|
785
|
+
f"Adding MCP tools to memory for {self.agent_name}"
|
|
786
|
+
)
|
|
787
|
+
# tools_list.extend(self.add_mcp_tools_to_memory())
|
|
788
|
+
mcp_tools = self.add_mcp_tools_to_memory()
|
|
789
|
+
|
|
790
|
+
if self.verbose:
|
|
791
|
+
logger.info(f"MCP tools: {mcp_tools}")
|
|
792
|
+
|
|
793
|
+
tools_list.extend(mcp_tools)
|
|
794
|
+
|
|
795
|
+
# Additional arguments for LiteLLM initialization
|
|
796
|
+
additional_args = {}
|
|
797
|
+
|
|
798
|
+
if self.llm_args is not None:
|
|
799
|
+
additional_args.update(self.llm_args)
|
|
800
|
+
|
|
801
|
+
if tools_list:
|
|
802
|
+
additional_args.update(
|
|
803
|
+
{
|
|
804
|
+
"tools_list_dictionary": tools_list,
|
|
805
|
+
"tool_choice": "auto",
|
|
806
|
+
"parallel_tool_calls": parallel_tool_calls,
|
|
807
|
+
}
|
|
808
|
+
)
|
|
809
|
+
|
|
810
|
+
if exists(self.mcp_url) or exists(self.mcp_urls):
|
|
811
|
+
additional_args.update({"mcp_call": True})
|
|
812
|
+
|
|
813
|
+
# if args or kwargs are provided, then update the additional_args
|
|
814
|
+
if args or kwargs:
|
|
815
|
+
# Handle keyword arguments first
|
|
816
|
+
if kwargs:
|
|
817
|
+
additional_args.update(kwargs)
|
|
818
|
+
|
|
819
|
+
# Handle positional arguments (args)
|
|
820
|
+
# These could be additional configuration parameters
|
|
821
|
+
# that should be merged into the additional_args
|
|
822
|
+
if args:
|
|
823
|
+
# If args contains a dictionary, merge it directly
|
|
824
|
+
if len(args) == 1 and isinstance(args[0], dict):
|
|
825
|
+
additional_args.update(args[0])
|
|
826
|
+
else:
|
|
827
|
+
# For other types of args, log them for debugging
|
|
828
|
+
# and potentially handle them based on their type
|
|
829
|
+
logger.debug(
|
|
830
|
+
f"Received positional args in llm_handling: {args}"
|
|
831
|
+
)
|
|
832
|
+
# You can add specific handling for different arg types here
|
|
833
|
+
# For now, we'll add them as additional configuration
|
|
834
|
+
additional_args.update(
|
|
835
|
+
{"additional_args": args}
|
|
836
|
+
)
|
|
837
|
+
|
|
838
|
+
# Final LiteLLM initialization with combined arguments
|
|
839
|
+
self.llm = LiteLLM(**{**common_args, **additional_args})
|
|
840
|
+
|
|
841
|
+
return self.llm
|
|
842
|
+
except AgentLLMInitializationError as e:
|
|
843
|
+
logger.error(
|
|
844
|
+
f"AgentLLMInitializationError: Agent Name: {self.agent_name} Error in llm_handling: {e} Your current configuration is not supported. Please check the configuration and parameters. Traceback: {traceback.format_exc()}"
|
|
845
|
+
)
|
|
846
|
+
return None
|
|
847
|
+
|
|
848
|
+
def add_mcp_tools_to_memory(self):
|
|
849
|
+
"""
|
|
850
|
+
Adds MCP tools to the agent's short-term memory.
|
|
851
|
+
|
|
852
|
+
This function checks for either a single MCP URL or multiple MCP URLs and adds the available tools
|
|
853
|
+
to the agent's memory. The tools are listed in JSON format.
|
|
854
|
+
|
|
855
|
+
Raises:
|
|
856
|
+
Exception: If there's an error accessing the MCP tools
|
|
857
|
+
"""
|
|
858
|
+
try:
|
|
859
|
+
# Determine which MCP configuration to use
|
|
860
|
+
if exists(self.mcp_url):
|
|
861
|
+
tools = get_mcp_tools_sync(server_path=self.mcp_url)
|
|
862
|
+
elif exists(self.mcp_config):
|
|
863
|
+
tools = get_mcp_tools_sync(connection=self.mcp_config)
|
|
864
|
+
elif exists(self.mcp_urls):
|
|
865
|
+
logger.info(
|
|
866
|
+
f"Getting MCP tools for multiple MCP servers for {self.agent_name}"
|
|
867
|
+
)
|
|
868
|
+
tools = get_tools_for_multiple_mcp_servers(
|
|
869
|
+
urls=self.mcp_urls,
|
|
870
|
+
)
|
|
871
|
+
|
|
872
|
+
if self.verbose:
|
|
873
|
+
logger.info(f"MCP tools: {tools}")
|
|
874
|
+
else:
|
|
875
|
+
raise AgentMCPConnectionError(
|
|
876
|
+
"mcp_url must be either a string URL or MCPConnection object"
|
|
877
|
+
)
|
|
878
|
+
|
|
879
|
+
# Print success message if any MCP configuration exists
|
|
880
|
+
if self.print_on:
|
|
881
|
+
self.pretty_print(
|
|
882
|
+
f"✨ [SYSTEM] Successfully integrated {len(tools)} MCP tools into agent: {self.agent_name} | Status: ONLINE | Time: {time.strftime('%H:%M:%S')} ✨",
|
|
883
|
+
loop_count=0,
|
|
884
|
+
)
|
|
885
|
+
|
|
886
|
+
return tools
|
|
887
|
+
except AgentMCPConnectionError as e:
|
|
888
|
+
logger.error(
|
|
889
|
+
f"Error Adding MCP Tools to Agent: {self.agent_name} Error: {e} Traceback: {traceback.format_exc()}"
|
|
890
|
+
)
|
|
891
|
+
raise e
|
|
892
|
+
|
|
893
|
+
def setup_config(self):
|
|
894
|
+
# The max_loops will be set dynamically if the dynamic_loop
|
|
895
|
+
if self.dynamic_loops is True:
|
|
896
|
+
logger.info("Dynamic loops enabled")
|
|
897
|
+
self.max_loops = "auto"
|
|
898
|
+
|
|
899
|
+
# If multimodal = yes then set the sop to the multimodal sop
|
|
900
|
+
if self.multi_modal is True:
|
|
901
|
+
self.sop = MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1
|
|
902
|
+
|
|
903
|
+
# If the preset stopping token is enabled then set the stopping token to the preset stopping token
|
|
904
|
+
if self.preset_stopping_token is not None:
|
|
905
|
+
self.stopping_token = "<DONE>"
|
|
906
|
+
|
|
907
|
+
# Initialize the feedback
|
|
908
|
+
self.feedback = []
|
|
909
|
+
|
|
910
|
+
def check_model_supports_utilities(
|
|
911
|
+
self, img: Optional[str] = None
|
|
912
|
+
) -> bool:
|
|
913
|
+
"""
|
|
914
|
+
Check if the current model supports vision capabilities.
|
|
915
|
+
|
|
916
|
+
Args:
|
|
917
|
+
img (str, optional): Image input to check vision support for. Defaults to None.
|
|
918
|
+
|
|
919
|
+
Returns:
|
|
920
|
+
bool: True if model supports vision and image is provided, False otherwise.
|
|
921
|
+
"""
|
|
922
|
+
|
|
923
|
+
# Only check vision support if an image is provided
|
|
924
|
+
if img is not None:
|
|
925
|
+
out = supports_vision(self.model_name)
|
|
926
|
+
if out is False:
|
|
927
|
+
logger.error(
|
|
928
|
+
f"[Agent: {self.agent_name}] Model '{self.model_name}' does not support vision capabilities. "
|
|
929
|
+
f"Image input was provided: {img[:100]}{'...' if len(img) > 100 else ''}. "
|
|
930
|
+
f"Please use a vision-enabled model."
|
|
931
|
+
)
|
|
932
|
+
|
|
933
|
+
if self.tools_list_dictionary is not None:
|
|
934
|
+
out = supports_function_calling(self.model_name)
|
|
935
|
+
if out is False:
|
|
936
|
+
logger.error(
|
|
937
|
+
f"[Agent: {self.agent_name}] Model '{self.model_name}' does not support function calling capabilities. "
|
|
938
|
+
f"tools_list_dictionary is set: {self.tools_list_dictionary}. "
|
|
939
|
+
f"Please use a function calling-enabled model."
|
|
940
|
+
)
|
|
941
|
+
|
|
942
|
+
if self.tools is not None:
|
|
943
|
+
if len(self.tools) > 2:
|
|
944
|
+
out = supports_parallel_function_calling(
|
|
945
|
+
self.model_name
|
|
946
|
+
)
|
|
947
|
+
if out is False:
|
|
948
|
+
logger.error(
|
|
949
|
+
f"[Agent: {self.agent_name}] Model '{self.model_name}' does not support parallel function calling capabilities. "
|
|
950
|
+
f"Please use a parallel function calling-enabled model."
|
|
951
|
+
)
|
|
952
|
+
|
|
953
|
+
return None
|
|
954
|
+
|
|
955
|
+
def check_if_no_prompt_then_autogenerate(self, task: str = None):
|
|
956
|
+
"""
|
|
957
|
+
Checks if auto_generate_prompt is enabled and generates a prompt by combining agent name, description and system prompt if available.
|
|
958
|
+
Falls back to task if all other fields are missing.
|
|
959
|
+
|
|
960
|
+
Args:
|
|
961
|
+
task (str, optional): The task to use as a fallback if name, description and system prompt are missing. Defaults to None.
|
|
962
|
+
"""
|
|
963
|
+
if self.auto_generate_prompt is True:
|
|
964
|
+
# Collect all available prompt components
|
|
965
|
+
components = []
|
|
966
|
+
|
|
967
|
+
if self.agent_name:
|
|
968
|
+
components.append(self.agent_name)
|
|
969
|
+
|
|
970
|
+
if self.agent_description:
|
|
971
|
+
components.append(self.agent_description)
|
|
972
|
+
|
|
973
|
+
if self.system_prompt:
|
|
974
|
+
components.append(self.system_prompt)
|
|
975
|
+
|
|
976
|
+
# If no components available, fall back to task
|
|
977
|
+
if not components and task:
|
|
978
|
+
logger.warning(
|
|
979
|
+
"No agent details found. Using task as fallback for prompt generation."
|
|
980
|
+
)
|
|
981
|
+
self.system_prompt = auto_generate_prompt(
|
|
982
|
+
task=task, model=self.llm
|
|
983
|
+
)
|
|
984
|
+
else:
|
|
985
|
+
# Combine all available components
|
|
986
|
+
combined_prompt = " ".join(components)
|
|
987
|
+
logger.info(
|
|
988
|
+
f"Auto-generating prompt from: {', '.join(components)}"
|
|
989
|
+
)
|
|
990
|
+
self.system_prompt = auto_generate_prompt(
|
|
991
|
+
combined_prompt, self.llm
|
|
992
|
+
)
|
|
993
|
+
self.short_memory.add(
|
|
994
|
+
role="system", content=self.system_prompt
|
|
995
|
+
)
|
|
996
|
+
|
|
997
|
+
logger.info("Auto-generated prompt successfully.")
|
|
998
|
+
|
|
999
|
+
def set_system_prompt(self, system_prompt: str):
|
|
1000
|
+
"""Set the system prompt"""
|
|
1001
|
+
self.system_prompt = system_prompt
|
|
1002
|
+
|
|
1003
|
+
def provide_feedback(self, feedback: str) -> None:
|
|
1004
|
+
"""Allow users to provide feedback on the responses."""
|
|
1005
|
+
self.feedback.append(feedback)
|
|
1006
|
+
logging.info(f"Feedback received: {feedback}")
|
|
1007
|
+
|
|
1008
|
+
def _check_stopping_condition(self, response: str) -> bool:
|
|
1009
|
+
"""Check if the stopping condition is met."""
|
|
1010
|
+
try:
|
|
1011
|
+
if self.stopping_condition:
|
|
1012
|
+
return self.stopping_condition(response)
|
|
1013
|
+
return False
|
|
1014
|
+
except Exception as error:
|
|
1015
|
+
logger.error(
|
|
1016
|
+
f"Error checking stopping condition: {error}"
|
|
1017
|
+
)
|
|
1018
|
+
|
|
1019
|
+
def dynamic_temperature(self):
|
|
1020
|
+
"""
|
|
1021
|
+
1. Check the self.llm object for the temperature
|
|
1022
|
+
2. If the temperature is not present, then use the default temperature
|
|
1023
|
+
3. If the temperature is present, then dynamically change the temperature
|
|
1024
|
+
4. for every loop you can randomly change the temperature on a scale from 0.0 to 1.0
|
|
1025
|
+
"""
|
|
1026
|
+
try:
|
|
1027
|
+
if hasattr(self.llm, "temperature"):
|
|
1028
|
+
# Randomly change the temperature attribute of self.llm object
|
|
1029
|
+
self.llm.temperature = random.uniform(0.0, 1.0)
|
|
1030
|
+
else:
|
|
1031
|
+
# Use a default temperature
|
|
1032
|
+
self.llm.temperature = 0.5
|
|
1033
|
+
except Exception as error:
|
|
1034
|
+
logger.error(
|
|
1035
|
+
f"Error dynamically changing temperature: {error}"
|
|
1036
|
+
)
|
|
1037
|
+
|
|
1038
|
+
def print_dashboard(self):
|
|
1039
|
+
"""
|
|
1040
|
+
Print a dashboard displaying the agent's current status and configuration.
|
|
1041
|
+
Uses square brackets instead of emojis for section headers and bullet points.
|
|
1042
|
+
"""
|
|
1043
|
+
tools_activated = True if self.tools is not None else False
|
|
1044
|
+
mcp_activated = True if self.mcp_url is not None else False
|
|
1045
|
+
formatter.print_panel(
|
|
1046
|
+
f"""
|
|
1047
|
+
|
|
1048
|
+
[Agent {self.agent_name} Dashboard]
|
|
1049
|
+
===========================================================
|
|
1050
|
+
|
|
1051
|
+
[Agent {self.agent_name} Status]: ONLINE & OPERATIONAL
|
|
1052
|
+
-----------------------------------------------------------
|
|
1053
|
+
|
|
1054
|
+
[Agent Identity]
|
|
1055
|
+
- [Name]: {self.agent_name}
|
|
1056
|
+
- [Description]: {self.agent_description}
|
|
1057
|
+
|
|
1058
|
+
[Technical Specifications]
|
|
1059
|
+
- [Model]: {self.model_name}
|
|
1060
|
+
- [Internal Loops]: {self.max_loops}
|
|
1061
|
+
- [Max Tokens]: {self.max_tokens}
|
|
1062
|
+
- [Dynamic Temperature]: {self.dynamic_temperature_enabled}
|
|
1063
|
+
|
|
1064
|
+
[System Modules]
|
|
1065
|
+
- [Tools Activated]: {tools_activated}
|
|
1066
|
+
- [MCP Activated]: {mcp_activated}
|
|
1067
|
+
|
|
1068
|
+
===========================================================
|
|
1069
|
+
[Ready for Tasks]
|
|
1070
|
+
|
|
1071
|
+
""",
|
|
1072
|
+
title=f"Agent {self.agent_name} Dashboard",
|
|
1073
|
+
)
|
|
1074
|
+
|
|
1075
|
+
def handle_rag_query(self, query: str):
|
|
1076
|
+
"""
|
|
1077
|
+
Handle RAG query
|
|
1078
|
+
"""
|
|
1079
|
+
try:
|
|
1080
|
+
logger.info(
|
|
1081
|
+
f"Agent: {self.agent_name} Querying RAG memory for: {query}"
|
|
1082
|
+
)
|
|
1083
|
+
output = self.long_term_memory.query(
|
|
1084
|
+
query,
|
|
1085
|
+
)
|
|
1086
|
+
|
|
1087
|
+
output = dynamic_auto_chunking(
|
|
1088
|
+
content=output,
|
|
1089
|
+
context_length=self.max_tokens,
|
|
1090
|
+
tokenizer_model_name=self.model_name,
|
|
1091
|
+
)
|
|
1092
|
+
|
|
1093
|
+
self.short_memory.add(
|
|
1094
|
+
role="system",
|
|
1095
|
+
content=(
|
|
1096
|
+
"[RAG Query Initiated]\n"
|
|
1097
|
+
"----------------------------------\n"
|
|
1098
|
+
f"Query:\n{query}\n\n"
|
|
1099
|
+
f"Retrieved Knowledge (RAG Output):\n{output}\n"
|
|
1100
|
+
"----------------------------------\n"
|
|
1101
|
+
"The above information was retrieved from the agent's long-term memory using Retrieval-Augmented Generation (RAG). "
|
|
1102
|
+
"Use this context to inform your next response or reasoning step."
|
|
1103
|
+
),
|
|
1104
|
+
)
|
|
1105
|
+
except AgentMemoryError as e:
|
|
1106
|
+
logger.error(
|
|
1107
|
+
f"Agent: {self.agent_name} Error handling RAG query: {e} Traceback: {traceback.format_exc()}"
|
|
1108
|
+
)
|
|
1109
|
+
raise e
|
|
1110
|
+
|
|
1111
|
+
# Main function
|
|
1112
|
+
def _run(
|
|
1113
|
+
self,
|
|
1114
|
+
task: Optional[Union[str, Any]] = None,
|
|
1115
|
+
img: Optional[str] = None,
|
|
1116
|
+
streaming_callback: Optional[Callable[[str], None]] = None,
|
|
1117
|
+
*args,
|
|
1118
|
+
**kwargs,
|
|
1119
|
+
) -> Any:
|
|
1120
|
+
"""
|
|
1121
|
+
Execute the agent's main loop for a given task.
|
|
1122
|
+
|
|
1123
|
+
This function manages the agent's reasoning and action loop, including:
|
|
1124
|
+
- Initializing the task and context
|
|
1125
|
+
- Handling Retrieval-Augmented Generation (RAG) queries if enabled
|
|
1126
|
+
- Planning (if enabled)
|
|
1127
|
+
- Managing internal reasoning loops and memory
|
|
1128
|
+
- Optionally processing images and streaming output
|
|
1129
|
+
- Autosaving agent state if configured
|
|
1130
|
+
|
|
1131
|
+
Args:
|
|
1132
|
+
task (Optional[Union[str, Any]]): The task or prompt for the agent to process.
|
|
1133
|
+
img (Optional[str]): Optional image path or data to be processed by the agent.
|
|
1134
|
+
streaming_callback (Optional[Callable[[str], None]]): Optional callback for streaming output.
|
|
1135
|
+
*args: Additional positional arguments for extensibility.
|
|
1136
|
+
**kwargs: Additional keyword arguments for extensibility.
|
|
1137
|
+
|
|
1138
|
+
Returns:
|
|
1139
|
+
Any: The agent's output, which may be a string, list, JSON, dict, YAML, XML, or other type depending on the agent's configuration and the task.
|
|
1140
|
+
|
|
1141
|
+
Examples:
|
|
1142
|
+
agent(task="What is the capital of France?")
|
|
1143
|
+
agent(task="Summarize this document.", img="path/to/image.jpg")
|
|
1144
|
+
agent(task="Analyze this image.", img="path/to/image.jpg", is_last=True)
|
|
1145
|
+
"""
|
|
1146
|
+
try:
|
|
1147
|
+
|
|
1148
|
+
self.check_if_no_prompt_then_autogenerate(task)
|
|
1149
|
+
|
|
1150
|
+
self.check_model_supports_utilities(img=img)
|
|
1151
|
+
|
|
1152
|
+
self.short_memory.add(role=self.user_name, content=task)
|
|
1153
|
+
|
|
1154
|
+
# Handle RAG query only once
|
|
1155
|
+
if (
|
|
1156
|
+
self.long_term_memory is not None
|
|
1157
|
+
and self.rag_every_loop is False
|
|
1158
|
+
):
|
|
1159
|
+
self.handle_rag_query(task)
|
|
1160
|
+
|
|
1161
|
+
if self.plan_enabled is True:
|
|
1162
|
+
self.plan(task)
|
|
1163
|
+
|
|
1164
|
+
# Set the loop count
|
|
1165
|
+
loop_count = 0
|
|
1166
|
+
|
|
1167
|
+
# Clear the short memory
|
|
1168
|
+
response = None
|
|
1169
|
+
|
|
1170
|
+
# Autosave
|
|
1171
|
+
if self.autosave:
|
|
1172
|
+
log_agent_data(self.to_dict())
|
|
1173
|
+
self.save()
|
|
1174
|
+
|
|
1175
|
+
while (
|
|
1176
|
+
self.max_loops == "auto"
|
|
1177
|
+
or loop_count < self.max_loops
|
|
1178
|
+
):
|
|
1179
|
+
loop_count += 1
|
|
1180
|
+
|
|
1181
|
+
# Handle RAG query every loop
|
|
1182
|
+
if (
|
|
1183
|
+
self.long_term_memory is not None
|
|
1184
|
+
and self.rag_every_loop is True
|
|
1185
|
+
):
|
|
1186
|
+
self.handle_rag_query(task)
|
|
1187
|
+
|
|
1188
|
+
if (
|
|
1189
|
+
isinstance(self.max_loops, int)
|
|
1190
|
+
and self.max_loops >= 2
|
|
1191
|
+
):
|
|
1192
|
+
if self.reasoning_prompt_on is True:
|
|
1193
|
+
self.short_memory.add(
|
|
1194
|
+
role=self.agent_name,
|
|
1195
|
+
content=f"Current Internal Reasoning Loop: {loop_count}/{self.max_loops}",
|
|
1196
|
+
)
|
|
1197
|
+
|
|
1198
|
+
# If it is the final loop, then add the final loop message
|
|
1199
|
+
if (
|
|
1200
|
+
loop_count >= 2
|
|
1201
|
+
and isinstance(self.max_loops, int)
|
|
1202
|
+
and loop_count == self.max_loops
|
|
1203
|
+
):
|
|
1204
|
+
if self.reasoning_prompt_on is True:
|
|
1205
|
+
self.short_memory.add(
|
|
1206
|
+
role=self.agent_name,
|
|
1207
|
+
content=f"🎉 Final Internal Reasoning Loop: {loop_count}/{self.max_loops} Prepare your comprehensive response.",
|
|
1208
|
+
)
|
|
1209
|
+
|
|
1210
|
+
# Dynamic temperature
|
|
1211
|
+
if self.dynamic_temperature_enabled is True:
|
|
1212
|
+
self.dynamic_temperature()
|
|
1213
|
+
|
|
1214
|
+
# Task prompt with optional transforms
|
|
1215
|
+
if self.transforms is not None:
|
|
1216
|
+
task_prompt = handle_transforms(
|
|
1217
|
+
transforms=self.transforms,
|
|
1218
|
+
short_memory=self.short_memory,
|
|
1219
|
+
model_name=self.model_name,
|
|
1220
|
+
)
|
|
1221
|
+
|
|
1222
|
+
else:
|
|
1223
|
+
# Use original method if no transforms
|
|
1224
|
+
task_prompt = (
|
|
1225
|
+
self.short_memory.return_history_as_string()
|
|
1226
|
+
)
|
|
1227
|
+
|
|
1228
|
+
# Parameters
|
|
1229
|
+
attempt = 0
|
|
1230
|
+
success = False
|
|
1231
|
+
while attempt < self.retry_attempts and not success:
|
|
1232
|
+
try:
|
|
1233
|
+
|
|
1234
|
+
if img is not None:
|
|
1235
|
+
response = self.call_llm(
|
|
1236
|
+
task=task_prompt,
|
|
1237
|
+
img=img,
|
|
1238
|
+
current_loop=loop_count,
|
|
1239
|
+
streaming_callback=streaming_callback,
|
|
1240
|
+
*args,
|
|
1241
|
+
**kwargs,
|
|
1242
|
+
)
|
|
1243
|
+
else:
|
|
1244
|
+
response = self.call_llm(
|
|
1245
|
+
task=task_prompt,
|
|
1246
|
+
current_loop=loop_count,
|
|
1247
|
+
streaming_callback=streaming_callback,
|
|
1248
|
+
*args,
|
|
1249
|
+
**kwargs,
|
|
1250
|
+
)
|
|
1251
|
+
|
|
1252
|
+
# If streaming is enabled, then don't print the response
|
|
1253
|
+
|
|
1254
|
+
# Parse the response from the agent with the output type
|
|
1255
|
+
if exists(self.tools_list_dictionary):
|
|
1256
|
+
if isinstance(response, BaseModel):
|
|
1257
|
+
response = response.model_dump()
|
|
1258
|
+
|
|
1259
|
+
# Parse the response from the agent with the output type
|
|
1260
|
+
response = self.parse_llm_output(response)
|
|
1261
|
+
|
|
1262
|
+
self.short_memory.add(
|
|
1263
|
+
role=self.agent_name,
|
|
1264
|
+
content=response,
|
|
1265
|
+
)
|
|
1266
|
+
|
|
1267
|
+
# Print
|
|
1268
|
+
if self.print_on is True:
|
|
1269
|
+
if isinstance(response, list):
|
|
1270
|
+
self.pretty_print(
|
|
1271
|
+
# f"Structured Output - Attempting Function Call Execution [{time.strftime('%H:%M:%S')}] \n\n Output: {format_data_structure(response)} ",
|
|
1272
|
+
f"[Structured Output] [Time: {time.strftime('%H:%M:%S')}] \n\n {json.dumps(response, indent=4)}",
|
|
1273
|
+
loop_count,
|
|
1274
|
+
)
|
|
1275
|
+
elif self.streaming_on:
|
|
1276
|
+
pass
|
|
1277
|
+
elif self.stream:
|
|
1278
|
+
pass
|
|
1279
|
+
else:
|
|
1280
|
+
self.pretty_print(
|
|
1281
|
+
response, loop_count
|
|
1282
|
+
)
|
|
1283
|
+
|
|
1284
|
+
# Check and execute callable tools
|
|
1285
|
+
if exists(self.tools):
|
|
1286
|
+
self.tool_execution_retry(
|
|
1287
|
+
response, loop_count
|
|
1288
|
+
)
|
|
1289
|
+
|
|
1290
|
+
# Handle MCP tools
|
|
1291
|
+
if (
|
|
1292
|
+
exists(self.mcp_url)
|
|
1293
|
+
or exists(self.mcp_config)
|
|
1294
|
+
or exists(self.mcp_urls)
|
|
1295
|
+
):
|
|
1296
|
+
# Only handle MCP tools if response is not None
|
|
1297
|
+
if response is not None:
|
|
1298
|
+
self.mcp_tool_handling(
|
|
1299
|
+
response=response,
|
|
1300
|
+
current_loop=loop_count,
|
|
1301
|
+
)
|
|
1302
|
+
else:
|
|
1303
|
+
logger.warning(
|
|
1304
|
+
f"LLM returned None response in loop {loop_count}, skipping MCP tool handling"
|
|
1305
|
+
)
|
|
1306
|
+
|
|
1307
|
+
# self.sentiment_and_evaluator(response)
|
|
1308
|
+
|
|
1309
|
+
success = True # Mark as successful to exit the retry loop
|
|
1310
|
+
|
|
1311
|
+
except (
|
|
1312
|
+
BadRequestError,
|
|
1313
|
+
InternalServerError,
|
|
1314
|
+
AuthenticationError,
|
|
1315
|
+
Exception,
|
|
1316
|
+
) as e:
|
|
1317
|
+
|
|
1318
|
+
if self.autosave is True:
|
|
1319
|
+
log_agent_data(self.to_dict())
|
|
1320
|
+
self.save()
|
|
1321
|
+
|
|
1322
|
+
logger.error(
|
|
1323
|
+
f"Attempt {attempt+1}/{self.retry_attempts}: Error generating response in loop {loop_count} for agent '{self.agent_name}': {str(e)} | Traceback: {traceback.format_exc()}"
|
|
1324
|
+
)
|
|
1325
|
+
attempt += 1
|
|
1326
|
+
|
|
1327
|
+
if not success:
|
|
1328
|
+
|
|
1329
|
+
if self.autosave is True:
|
|
1330
|
+
log_agent_data(self.to_dict())
|
|
1331
|
+
self.save()
|
|
1332
|
+
|
|
1333
|
+
logger.error(
|
|
1334
|
+
"Failed to generate a valid response after"
|
|
1335
|
+
" retry attempts."
|
|
1336
|
+
)
|
|
1337
|
+
break # Exit the loop if all retry attempts fail
|
|
1338
|
+
|
|
1339
|
+
# Check stopping conditions
|
|
1340
|
+
if (
|
|
1341
|
+
self.stopping_condition is not None
|
|
1342
|
+
and self._check_stopping_condition(response)
|
|
1343
|
+
):
|
|
1344
|
+
logger.info(
|
|
1345
|
+
f"Agent '{self.agent_name}' stopping condition met. "
|
|
1346
|
+
f"Loop: {loop_count}, Response length: {len(str(response)) if response else 0}"
|
|
1347
|
+
)
|
|
1348
|
+
break
|
|
1349
|
+
elif (
|
|
1350
|
+
self.stopping_func is not None
|
|
1351
|
+
and self.stopping_func(response)
|
|
1352
|
+
):
|
|
1353
|
+
logger.info(
|
|
1354
|
+
f"Agent '{self.agent_name}' stopping function condition met. "
|
|
1355
|
+
f"Loop: {loop_count}, Response length: {len(str(response)) if response else 0}"
|
|
1356
|
+
)
|
|
1357
|
+
break
|
|
1358
|
+
|
|
1359
|
+
if self.interactive:
|
|
1360
|
+
|
|
1361
|
+
# logger.info("Interactive mode enabled.")
|
|
1362
|
+
user_input = input("You: ")
|
|
1363
|
+
|
|
1364
|
+
# User-defined exit command
|
|
1365
|
+
if (
|
|
1366
|
+
user_input.lower()
|
|
1367
|
+
== self.custom_exit_command.lower()
|
|
1368
|
+
):
|
|
1369
|
+
self.pretty_print(
|
|
1370
|
+
"Exiting as per user request.",
|
|
1371
|
+
loop_count=loop_count,
|
|
1372
|
+
)
|
|
1373
|
+
break
|
|
1374
|
+
|
|
1375
|
+
self.short_memory.add(
|
|
1376
|
+
role=self.user_name, content=user_input
|
|
1377
|
+
)
|
|
1378
|
+
|
|
1379
|
+
if self.loop_interval:
|
|
1380
|
+
logger.info(
|
|
1381
|
+
f"Sleeping for {self.loop_interval} seconds"
|
|
1382
|
+
)
|
|
1383
|
+
time.sleep(self.loop_interval)
|
|
1384
|
+
|
|
1385
|
+
if self.autosave is True:
|
|
1386
|
+
log_agent_data(self.to_dict())
|
|
1387
|
+
|
|
1388
|
+
self.save()
|
|
1389
|
+
|
|
1390
|
+
# Output formatting based on output_type
|
|
1391
|
+
return history_output_formatter(
|
|
1392
|
+
self.short_memory, type=self.output_type
|
|
1393
|
+
)
|
|
1394
|
+
|
|
1395
|
+
except Exception as error:
|
|
1396
|
+
self._handle_run_error(error)
|
|
1397
|
+
|
|
1398
|
+
except KeyboardInterrupt as error:
|
|
1399
|
+
self._handle_run_error(error)
|
|
1400
|
+
|
|
1401
|
+
def _handle_run_error(self, error: any):
|
|
1402
|
+
if self.autosave is True:
|
|
1403
|
+
self.save()
|
|
1404
|
+
log_agent_data(self.to_dict())
|
|
1405
|
+
|
|
1406
|
+
# Get detailed error information
|
|
1407
|
+
error_type = type(error).__name__
|
|
1408
|
+
error_message = str(error)
|
|
1409
|
+
traceback_info = traceback.format_exc()
|
|
1410
|
+
|
|
1411
|
+
logger.error(
|
|
1412
|
+
f"Agent: {self.agent_name} An error occurred while running your agent.\n"
|
|
1413
|
+
f"Error Type: {error_type}\n"
|
|
1414
|
+
f"Error Message: {error_message}\n"
|
|
1415
|
+
f"Traceback:\n{traceback_info}\n"
|
|
1416
|
+
f"Agent State: {self.to_dict()}\n"
|
|
1417
|
+
f"Please optimize your input parameters, or create an issue on the Swarms GitHub and contact our team on Discord for support. "
|
|
1418
|
+
f"For technical support, refer to this document: https://docs.swarms.world/en/latest/swarms/support/"
|
|
1419
|
+
)
|
|
1420
|
+
|
|
1421
|
+
raise error
|
|
1422
|
+
|
|
1423
|
+
async def arun(
|
|
1424
|
+
self,
|
|
1425
|
+
task: Optional[str] = None,
|
|
1426
|
+
img: Optional[str] = None,
|
|
1427
|
+
*args,
|
|
1428
|
+
**kwargs,
|
|
1429
|
+
) -> Any:
|
|
1430
|
+
"""
|
|
1431
|
+
Asynchronously runs the agent with the specified parameters.
|
|
1432
|
+
|
|
1433
|
+
Args:
|
|
1434
|
+
task (Optional[str]): The task to be performed. Defaults to None.
|
|
1435
|
+
img (Optional[str]): The image to be processed. Defaults to None.
|
|
1436
|
+
is_last (bool): Indicates if this is the last task. Defaults to False.
|
|
1437
|
+
device (str): The device to use for execution. Defaults to "cpu".
|
|
1438
|
+
device_id (int): The ID of the GPU to use if device is set to "gpu". Defaults to 1.
|
|
1439
|
+
all_cores (bool): If True, uses all available CPU cores. Defaults to True.
|
|
1440
|
+
do_not_use_cluster_ops (bool): If True, does not use cluster operations. Defaults to True.
|
|
1441
|
+
all_gpus (bool): If True, uses all available GPUs. Defaults to False.
|
|
1442
|
+
*args: Additional positional arguments.
|
|
1443
|
+
**kwargs: Additional keyword arguments.
|
|
1444
|
+
|
|
1445
|
+
Returns:
|
|
1446
|
+
Any: The result of the asynchronous operation.
|
|
1447
|
+
|
|
1448
|
+
Raises:
|
|
1449
|
+
Exception: If an error occurs during the asynchronous operation.
|
|
1450
|
+
"""
|
|
1451
|
+
try:
|
|
1452
|
+
return await asyncio.to_thread(
|
|
1453
|
+
self.run,
|
|
1454
|
+
task=task,
|
|
1455
|
+
img=img,
|
|
1456
|
+
*args,
|
|
1457
|
+
**kwargs,
|
|
1458
|
+
)
|
|
1459
|
+
except Exception as error:
|
|
1460
|
+
await self._handle_run_error(
|
|
1461
|
+
error
|
|
1462
|
+
) # Ensure this is also async if needed
|
|
1463
|
+
|
|
1464
|
+
def __call__(
|
|
1465
|
+
self,
|
|
1466
|
+
task: Optional[str] = None,
|
|
1467
|
+
img: Optional[str] = None,
|
|
1468
|
+
*args,
|
|
1469
|
+
**kwargs,
|
|
1470
|
+
) -> Any:
|
|
1471
|
+
"""Call the agent
|
|
1472
|
+
|
|
1473
|
+
Args:
|
|
1474
|
+
task (Optional[str]): The task to be performed. Defaults to None.
|
|
1475
|
+
img (Optional[str]): The image to be processed. Defaults to None.
|
|
1476
|
+
"""
|
|
1477
|
+
try:
|
|
1478
|
+
return self.run(
|
|
1479
|
+
task=task,
|
|
1480
|
+
img=img,
|
|
1481
|
+
*args,
|
|
1482
|
+
**kwargs,
|
|
1483
|
+
)
|
|
1484
|
+
except Exception as error:
|
|
1485
|
+
self._handle_run_error(error)
|
|
1486
|
+
|
|
1487
|
+
def receive_message(
|
|
1488
|
+
self, agent_name: str, task: str, *args, **kwargs
|
|
1489
|
+
):
|
|
1490
|
+
improved_prompt = (
|
|
1491
|
+
f"You have received a message from agent '{agent_name}':\n\n"
|
|
1492
|
+
f'"{task}"\n\n'
|
|
1493
|
+
"Please process this message and respond appropriately."
|
|
1494
|
+
)
|
|
1495
|
+
return self.run(task=improved_prompt, *args, **kwargs)
|
|
1496
|
+
|
|
1497
|
+
def add_memory(self, message: str):
|
|
1498
|
+
"""Add a memory to the agent
|
|
1499
|
+
|
|
1500
|
+
Args:
|
|
1501
|
+
message (str): _description_
|
|
1502
|
+
|
|
1503
|
+
Returns:
|
|
1504
|
+
_type_: _description_
|
|
1505
|
+
"""
|
|
1506
|
+
logger.info(f"Adding memory: {message}")
|
|
1507
|
+
|
|
1508
|
+
return self.short_memory.add(
|
|
1509
|
+
role=self.agent_name, content=message
|
|
1510
|
+
)
|
|
1511
|
+
|
|
1512
|
+
def plan(self, task: str, *args, **kwargs) -> None:
|
|
1513
|
+
"""
|
|
1514
|
+
Create a strategic plan for executing the given task.
|
|
1515
|
+
|
|
1516
|
+
This method generates a step-by-step plan by combining the conversation
|
|
1517
|
+
history, planning prompt, and current task. The plan is then added to
|
|
1518
|
+
the agent's short-term memory for reference during execution.
|
|
1519
|
+
|
|
1520
|
+
Args:
|
|
1521
|
+
task (str): The task to create a plan for
|
|
1522
|
+
*args: Additional positional arguments passed to the LLM
|
|
1523
|
+
**kwargs: Additional keyword arguments passed to the LLM
|
|
1524
|
+
|
|
1525
|
+
Returns:
|
|
1526
|
+
None: The plan is stored in memory rather than returned
|
|
1527
|
+
|
|
1528
|
+
Raises:
|
|
1529
|
+
Exception: If planning fails, the original exception is re-raised
|
|
1530
|
+
"""
|
|
1531
|
+
try:
|
|
1532
|
+
# Get the current conversation history
|
|
1533
|
+
history = self.short_memory.get_str()
|
|
1534
|
+
|
|
1535
|
+
plan_prompt = f"Create a comprehensive step-by-step plan to complete the following task: \n\n {task}"
|
|
1536
|
+
|
|
1537
|
+
# Construct the planning prompt by combining history, planning prompt, and task
|
|
1538
|
+
if exists(self.planning_prompt):
|
|
1539
|
+
planning_prompt = f"{history}\n\n{self.planning_prompt}\n\nTask: {task}"
|
|
1540
|
+
else:
|
|
1541
|
+
planning_prompt = (
|
|
1542
|
+
f"{history}\n\n{plan_prompt}\n\nTask: {task}"
|
|
1543
|
+
)
|
|
1544
|
+
|
|
1545
|
+
# Generate the plan using the LLM
|
|
1546
|
+
plan = self.llm.run(task=planning_prompt, *args, **kwargs)
|
|
1547
|
+
|
|
1548
|
+
# Store the generated plan in short-term memory
|
|
1549
|
+
self.short_memory.add(role=self.agent_name, content=plan)
|
|
1550
|
+
|
|
1551
|
+
return None
|
|
1552
|
+
|
|
1553
|
+
except Exception as error:
|
|
1554
|
+
logger.error(
|
|
1555
|
+
f"Failed to create plan for task '{task}': {error}"
|
|
1556
|
+
)
|
|
1557
|
+
raise error
|
|
1558
|
+
|
|
1559
|
+
async def run_concurrent(self, task: str, *args, **kwargs):
|
|
1560
|
+
"""
|
|
1561
|
+
Run a task concurrently.
|
|
1562
|
+
|
|
1563
|
+
Args:
|
|
1564
|
+
task (str): The task to run.
|
|
1565
|
+
"""
|
|
1566
|
+
try:
|
|
1567
|
+
logger.info(f"Running concurrent task: {task}")
|
|
1568
|
+
future = self.executor.submit(
|
|
1569
|
+
self.run, task, *args, **kwargs
|
|
1570
|
+
)
|
|
1571
|
+
result = await asyncio.wrap_future(future)
|
|
1572
|
+
logger.info(f"Completed task: {result}")
|
|
1573
|
+
return result
|
|
1574
|
+
except Exception as error:
|
|
1575
|
+
logger.error(
|
|
1576
|
+
f"Error running agent: {error} while running concurrently"
|
|
1577
|
+
)
|
|
1578
|
+
|
|
1579
|
+
def run_concurrent_tasks(self, tasks: List[str], *args, **kwargs):
|
|
1580
|
+
"""
|
|
1581
|
+
Run multiple tasks concurrently.
|
|
1582
|
+
|
|
1583
|
+
Args:
|
|
1584
|
+
tasks (List[str]): A list of tasks to run.
|
|
1585
|
+
"""
|
|
1586
|
+
try:
|
|
1587
|
+
logger.info(f"Running concurrent tasks: {tasks}")
|
|
1588
|
+
futures = [
|
|
1589
|
+
self.executor.submit(
|
|
1590
|
+
self.run, task=task, *args, **kwargs
|
|
1591
|
+
)
|
|
1592
|
+
for task in tasks
|
|
1593
|
+
]
|
|
1594
|
+
results = [future.result() for future in futures]
|
|
1595
|
+
logger.info(f"Completed tasks: {results}")
|
|
1596
|
+
return results
|
|
1597
|
+
except Exception as error:
|
|
1598
|
+
logger.error(f"Error running concurrent tasks: {error}")
|
|
1599
|
+
|
|
1600
|
+
def bulk_run(self, inputs: List[Dict[str, Any]]) -> List[str]:
|
|
1601
|
+
"""
|
|
1602
|
+
Generate responses for multiple input sets.
|
|
1603
|
+
|
|
1604
|
+
Args:
|
|
1605
|
+
inputs (List[Dict[str, Any]]): A list of input dictionaries containing the necessary data for each run.
|
|
1606
|
+
|
|
1607
|
+
Returns:
|
|
1608
|
+
List[str]: A list of response strings generated for each input set.
|
|
1609
|
+
|
|
1610
|
+
Raises:
|
|
1611
|
+
Exception: If an error occurs while running the bulk tasks.
|
|
1612
|
+
"""
|
|
1613
|
+
try:
|
|
1614
|
+
logger.info(f"Running bulk tasks: {inputs}")
|
|
1615
|
+
return [self.run(**input_data) for input_data in inputs]
|
|
1616
|
+
except Exception as error:
|
|
1617
|
+
logger.info(f"Error running bulk run: {error}", "red")
|
|
1618
|
+
|
|
1619
|
+
def reliability_check(self):
|
|
1620
|
+
|
|
1621
|
+
if self.system_prompt is None:
|
|
1622
|
+
logger.warning(
|
|
1623
|
+
"The system prompt is not set. Please set a system prompt for the agent to improve reliability."
|
|
1624
|
+
)
|
|
1625
|
+
|
|
1626
|
+
if self.agent_name is None:
|
|
1627
|
+
logger.warning(
|
|
1628
|
+
"The agent name is not set. Please set an agent name to improve reliability."
|
|
1629
|
+
)
|
|
1630
|
+
|
|
1631
|
+
if self.max_loops is None or self.max_loops == 0:
|
|
1632
|
+
raise AgentInitializationError(
|
|
1633
|
+
"Max loops is not provided or is set to 0. Please set max loops to 1 or more."
|
|
1634
|
+
)
|
|
1635
|
+
|
|
1636
|
+
# Ensure max_tokens is set to a valid value based on the model, with a robust fallback.
|
|
1637
|
+
if self.max_tokens is None or self.max_tokens <= 0:
|
|
1638
|
+
suggested_tokens = get_max_tokens(self.model_name)
|
|
1639
|
+
if suggested_tokens is not None and suggested_tokens > 0:
|
|
1640
|
+
self.max_tokens = suggested_tokens
|
|
1641
|
+
else:
|
|
1642
|
+
logger.warning(
|
|
1643
|
+
f"Could not determine max_tokens for model '{self.model_name}'. Falling back to default value of 8192."
|
|
1644
|
+
)
|
|
1645
|
+
self.max_tokens = 8192
|
|
1646
|
+
|
|
1647
|
+
if self.context_length is None or self.context_length == 0:
|
|
1648
|
+
raise AgentInitializationError(
|
|
1649
|
+
"Context length is not provided. Please set a valid context length."
|
|
1650
|
+
)
|
|
1651
|
+
|
|
1652
|
+
if self.tools_list_dictionary is not None:
|
|
1653
|
+
if not supports_function_calling(self.model_name):
|
|
1654
|
+
logger.warning(
|
|
1655
|
+
f"The model '{self.model_name}' does not support function calling. Please use a model that supports function calling."
|
|
1656
|
+
)
|
|
1657
|
+
|
|
1658
|
+
try:
|
|
1659
|
+
if self.max_tokens > get_max_tokens(self.model_name):
|
|
1660
|
+
logger.warning(
|
|
1661
|
+
f"Max tokens is set to {self.max_tokens}, but the model '{self.model_name}' may or may not support {get_max_tokens(self.model_name)} tokens. Please set max tokens to {get_max_tokens(self.model_name)} or less."
|
|
1662
|
+
)
|
|
1663
|
+
|
|
1664
|
+
except Exception:
|
|
1665
|
+
pass
|
|
1666
|
+
|
|
1667
|
+
if self.model_name not in model_list:
|
|
1668
|
+
logger.warning(
|
|
1669
|
+
f"The model '{self.model_name}' may not be supported. Please use a supported model, or override the model name with the 'llm' parameter, which should be a class with a 'run(task: str)' method or a '__call__' method."
|
|
1670
|
+
)
|
|
1671
|
+
|
|
1672
|
+
def save(self, file_path: str = None) -> None:
|
|
1673
|
+
"""
|
|
1674
|
+
Save the agent state to a file using SafeStateManager with atomic writing
|
|
1675
|
+
and backup functionality. Automatically handles complex objects and class instances.
|
|
1676
|
+
|
|
1677
|
+
Args:
|
|
1678
|
+
file_path (str, optional): Custom path to save the state.
|
|
1679
|
+
If None, uses configured paths.
|
|
1680
|
+
|
|
1681
|
+
Raises:
|
|
1682
|
+
OSError: If there are filesystem-related errors
|
|
1683
|
+
Exception: For other unexpected errors
|
|
1684
|
+
"""
|
|
1685
|
+
try:
|
|
1686
|
+
# Determine the save path
|
|
1687
|
+
resolved_path = (
|
|
1688
|
+
file_path
|
|
1689
|
+
or self.saved_state_path
|
|
1690
|
+
or f"{self.agent_name}_state.json"
|
|
1691
|
+
)
|
|
1692
|
+
|
|
1693
|
+
# Ensure path has .json extension
|
|
1694
|
+
if not resolved_path.endswith(".json"):
|
|
1695
|
+
resolved_path += ".json"
|
|
1696
|
+
|
|
1697
|
+
# Create full path including workspace directory
|
|
1698
|
+
full_path = os.path.join(
|
|
1699
|
+
self.workspace_dir, resolved_path
|
|
1700
|
+
)
|
|
1701
|
+
backup_path = full_path + ".backup"
|
|
1702
|
+
temp_path = full_path + ".temp"
|
|
1703
|
+
|
|
1704
|
+
# Ensure workspace directory exists
|
|
1705
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
1706
|
+
|
|
1707
|
+
# First save to temporary file using SafeStateManager
|
|
1708
|
+
SafeStateManager.save_state(self, temp_path)
|
|
1709
|
+
|
|
1710
|
+
# If current file exists, create backup
|
|
1711
|
+
if os.path.exists(full_path):
|
|
1712
|
+
try:
|
|
1713
|
+
os.replace(full_path, backup_path)
|
|
1714
|
+
except Exception as e:
|
|
1715
|
+
logger.warning(f"Could not create backup: {e}")
|
|
1716
|
+
|
|
1717
|
+
# Move temporary file to final location
|
|
1718
|
+
os.replace(temp_path, full_path)
|
|
1719
|
+
|
|
1720
|
+
# Clean up old backup if everything succeeded
|
|
1721
|
+
if os.path.exists(backup_path):
|
|
1722
|
+
try:
|
|
1723
|
+
os.remove(backup_path)
|
|
1724
|
+
except Exception as e:
|
|
1725
|
+
logger.warning(
|
|
1726
|
+
f"Could not remove backup file: {e}"
|
|
1727
|
+
)
|
|
1728
|
+
|
|
1729
|
+
# Log saved state information if verbose
|
|
1730
|
+
if self.verbose:
|
|
1731
|
+
self._log_saved_state_info(full_path)
|
|
1732
|
+
|
|
1733
|
+
logger.info(
|
|
1734
|
+
f"Successfully saved agent state to: {full_path}"
|
|
1735
|
+
)
|
|
1736
|
+
|
|
1737
|
+
# Handle additional component saves
|
|
1738
|
+
self._save_additional_components(full_path)
|
|
1739
|
+
|
|
1740
|
+
except OSError as e:
|
|
1741
|
+
logger.error(
|
|
1742
|
+
f"Filesystem error while saving agent state: {e}"
|
|
1743
|
+
)
|
|
1744
|
+
raise
|
|
1745
|
+
except Exception as e:
|
|
1746
|
+
logger.error(f"Unexpected error saving agent state: {e}")
|
|
1747
|
+
raise
|
|
1748
|
+
|
|
1749
|
+
def _save_additional_components(self, base_path: str) -> None:
|
|
1750
|
+
"""Save additional agent components like memory."""
|
|
1751
|
+
try:
|
|
1752
|
+
# Save long term memory if it exists
|
|
1753
|
+
if (
|
|
1754
|
+
hasattr(self, "long_term_memory")
|
|
1755
|
+
and self.long_term_memory is not None
|
|
1756
|
+
):
|
|
1757
|
+
memory_path = (
|
|
1758
|
+
f"{os.path.splitext(base_path)[0]}_memory.json"
|
|
1759
|
+
)
|
|
1760
|
+
try:
|
|
1761
|
+
self.long_term_memory.save(memory_path)
|
|
1762
|
+
logger.info(
|
|
1763
|
+
f"Saved long-term memory to: {memory_path}"
|
|
1764
|
+
)
|
|
1765
|
+
except Exception as e:
|
|
1766
|
+
logger.warning(
|
|
1767
|
+
f"Could not save long-term memory: {e}"
|
|
1768
|
+
)
|
|
1769
|
+
|
|
1770
|
+
# Save memory manager if it exists
|
|
1771
|
+
if (
|
|
1772
|
+
hasattr(self, "memory_manager")
|
|
1773
|
+
and self.memory_manager is not None
|
|
1774
|
+
):
|
|
1775
|
+
manager_path = f"{os.path.splitext(base_path)[0]}_memory_manager.json"
|
|
1776
|
+
try:
|
|
1777
|
+
self.memory_manager.save_memory_snapshot(
|
|
1778
|
+
manager_path
|
|
1779
|
+
)
|
|
1780
|
+
logger.info(
|
|
1781
|
+
f"Saved memory manager state to: {manager_path}"
|
|
1782
|
+
)
|
|
1783
|
+
except Exception as e:
|
|
1784
|
+
logger.warning(
|
|
1785
|
+
f"Could not save memory manager: {e}"
|
|
1786
|
+
)
|
|
1787
|
+
|
|
1788
|
+
except Exception as e:
|
|
1789
|
+
logger.warning(f"Error saving additional components: {e}")
|
|
1790
|
+
|
|
1791
|
+
def enable_autosave(self, interval: int = 300) -> None:
|
|
1792
|
+
"""
|
|
1793
|
+
Enable automatic saving of agent state using SafeStateManager at specified intervals.
|
|
1794
|
+
|
|
1795
|
+
Args:
|
|
1796
|
+
interval (int): Time between saves in seconds. Defaults to 300 (5 minutes).
|
|
1797
|
+
"""
|
|
1798
|
+
|
|
1799
|
+
def autosave_loop():
|
|
1800
|
+
while self.autosave:
|
|
1801
|
+
try:
|
|
1802
|
+
self.save()
|
|
1803
|
+
if self.verbose:
|
|
1804
|
+
logger.debug(
|
|
1805
|
+
f"Autosaved agent state (interval: {interval}s)"
|
|
1806
|
+
)
|
|
1807
|
+
except Exception as e:
|
|
1808
|
+
logger.error(f"Autosave failed: {e}")
|
|
1809
|
+
time.sleep(interval)
|
|
1810
|
+
|
|
1811
|
+
self.autosave = True
|
|
1812
|
+
self.autosave_thread = threading.Thread(
|
|
1813
|
+
target=autosave_loop,
|
|
1814
|
+
daemon=True,
|
|
1815
|
+
name=f"{self.agent_name}_autosave",
|
|
1816
|
+
)
|
|
1817
|
+
self.autosave_thread.start()
|
|
1818
|
+
logger.info(f"Enabled autosave with {interval}s interval")
|
|
1819
|
+
|
|
1820
|
+
def disable_autosave(self) -> None:
|
|
1821
|
+
"""Disable automatic saving of agent state."""
|
|
1822
|
+
if hasattr(self, "autosave"):
|
|
1823
|
+
self.autosave = False
|
|
1824
|
+
if hasattr(self, "autosave_thread"):
|
|
1825
|
+
self.autosave_thread.join(timeout=1)
|
|
1826
|
+
delattr(self, "autosave_thread")
|
|
1827
|
+
logger.info("Disabled autosave")
|
|
1828
|
+
|
|
1829
|
+
def cleanup(self) -> None:
|
|
1830
|
+
"""Cleanup method to be called on exit. Ensures final state is saved."""
|
|
1831
|
+
try:
|
|
1832
|
+
if getattr(self, "autosave", False):
|
|
1833
|
+
logger.info(
|
|
1834
|
+
"Performing final autosave before exit..."
|
|
1835
|
+
)
|
|
1836
|
+
self.disable_autosave()
|
|
1837
|
+
self.save()
|
|
1838
|
+
except Exception as e:
|
|
1839
|
+
logger.error(f"Error during cleanup: {e}")
|
|
1840
|
+
|
|
1841
|
+
def load(self, file_path: str = None) -> None:
|
|
1842
|
+
"""
|
|
1843
|
+
Load agent state from a file using SafeStateManager.
|
|
1844
|
+
Automatically preserves class instances and complex objects.
|
|
1845
|
+
|
|
1846
|
+
Args:
|
|
1847
|
+
file_path (str, optional): Path to load state from.
|
|
1848
|
+
If None, uses default path from agent config.
|
|
1849
|
+
|
|
1850
|
+
Raises:
|
|
1851
|
+
FileNotFoundError: If state file doesn't exist
|
|
1852
|
+
Exception: If there's an error during loading
|
|
1853
|
+
"""
|
|
1854
|
+
try:
|
|
1855
|
+
# Resolve load path conditionally with a check for self.load_state_path
|
|
1856
|
+
resolved_path = (
|
|
1857
|
+
file_path
|
|
1858
|
+
or self.load_state_path
|
|
1859
|
+
or (
|
|
1860
|
+
f"{self.saved_state_path}.json"
|
|
1861
|
+
if self.saved_state_path
|
|
1862
|
+
else (
|
|
1863
|
+
f"{self.agent_name}.json"
|
|
1864
|
+
if self.agent_name
|
|
1865
|
+
else (
|
|
1866
|
+
f"{self.workspace_dir}/{self.agent_name}_state.json"
|
|
1867
|
+
if self.workspace_dir and self.agent_name
|
|
1868
|
+
else None
|
|
1869
|
+
)
|
|
1870
|
+
)
|
|
1871
|
+
)
|
|
1872
|
+
)
|
|
1873
|
+
|
|
1874
|
+
# Load state using SafeStateManager
|
|
1875
|
+
SafeStateManager.load_state(self, resolved_path)
|
|
1876
|
+
|
|
1877
|
+
# Reinitialize any necessary runtime components
|
|
1878
|
+
self._reinitialize_after_load()
|
|
1879
|
+
|
|
1880
|
+
if self.verbose:
|
|
1881
|
+
self._log_loaded_state_info(resolved_path)
|
|
1882
|
+
|
|
1883
|
+
except FileNotFoundError:
|
|
1884
|
+
logger.error(f"State file not found: {resolved_path}")
|
|
1885
|
+
raise
|
|
1886
|
+
except Exception as e:
|
|
1887
|
+
logger.error(f"Error loading agent state: {e}")
|
|
1888
|
+
raise
|
|
1889
|
+
|
|
1890
|
+
def _reinitialize_after_load(self) -> None:
|
|
1891
|
+
"""
|
|
1892
|
+
Reinitialize necessary components after loading state.
|
|
1893
|
+
Called automatically after load() to ensure all components are properly set up.
|
|
1894
|
+
"""
|
|
1895
|
+
try:
|
|
1896
|
+
# Reinitialize conversation if needed
|
|
1897
|
+
if (
|
|
1898
|
+
not hasattr(self, "short_memory")
|
|
1899
|
+
or self.short_memory is None
|
|
1900
|
+
):
|
|
1901
|
+
self.short_memory = Conversation(
|
|
1902
|
+
system_prompt=self.system_prompt,
|
|
1903
|
+
time_enabled=False,
|
|
1904
|
+
user=self.user_name,
|
|
1905
|
+
rules=self.rules,
|
|
1906
|
+
)
|
|
1907
|
+
|
|
1908
|
+
# Reinitialize executor if needed
|
|
1909
|
+
# if not hasattr(self, "executor") or self.executor is None:
|
|
1910
|
+
with ThreadPoolExecutor(
|
|
1911
|
+
max_workers=os.cpu_count()
|
|
1912
|
+
) as executor:
|
|
1913
|
+
self.executor = executor
|
|
1914
|
+
|
|
1915
|
+
except Exception as e:
|
|
1916
|
+
logger.error(f"Error reinitializing components: {e}")
|
|
1917
|
+
raise
|
|
1918
|
+
|
|
1919
|
+
def _log_saved_state_info(self, file_path: str) -> None:
|
|
1920
|
+
"""Log information about saved state for debugging"""
|
|
1921
|
+
try:
|
|
1922
|
+
state_dict = SafeLoaderUtils.create_state_dict(self)
|
|
1923
|
+
preserved = SafeLoaderUtils.preserve_instances(self)
|
|
1924
|
+
|
|
1925
|
+
logger.info(f"Saved agent state to: {file_path}")
|
|
1926
|
+
logger.debug(
|
|
1927
|
+
f"Saved {len(state_dict)} configuration values"
|
|
1928
|
+
)
|
|
1929
|
+
logger.debug(
|
|
1930
|
+
f"Preserved {len(preserved)} class instances"
|
|
1931
|
+
)
|
|
1932
|
+
|
|
1933
|
+
if self.verbose:
|
|
1934
|
+
logger.debug("Preserved instances:")
|
|
1935
|
+
for name, instance in preserved.items():
|
|
1936
|
+
logger.debug(
|
|
1937
|
+
f" - {name}: {type(instance).__name__}"
|
|
1938
|
+
)
|
|
1939
|
+
except Exception as e:
|
|
1940
|
+
logger.error(f"Error logging state info: {e}")
|
|
1941
|
+
|
|
1942
|
+
def _log_loaded_state_info(self, file_path: str) -> None:
|
|
1943
|
+
"""Log information about loaded state for debugging"""
|
|
1944
|
+
try:
|
|
1945
|
+
state_dict = SafeLoaderUtils.create_state_dict(self)
|
|
1946
|
+
preserved = SafeLoaderUtils.preserve_instances(self)
|
|
1947
|
+
|
|
1948
|
+
logger.info(f"Loaded agent state from: {file_path}")
|
|
1949
|
+
logger.debug(
|
|
1950
|
+
f"Loaded {len(state_dict)} configuration values"
|
|
1951
|
+
)
|
|
1952
|
+
logger.debug(
|
|
1953
|
+
f"Preserved {len(preserved)} class instances"
|
|
1954
|
+
)
|
|
1955
|
+
|
|
1956
|
+
if self.verbose:
|
|
1957
|
+
logger.debug("Current class instances:")
|
|
1958
|
+
for name, instance in preserved.items():
|
|
1959
|
+
logger.debug(
|
|
1960
|
+
f" - {name}: {type(instance).__name__}"
|
|
1961
|
+
)
|
|
1962
|
+
except Exception as e:
|
|
1963
|
+
logger.error(f"Error logging state info: {e}")
|
|
1964
|
+
|
|
1965
|
+
def get_saveable_state(self) -> Dict[str, Any]:
|
|
1966
|
+
"""
|
|
1967
|
+
Get a dictionary of all saveable state values.
|
|
1968
|
+
Useful for debugging or manual state inspection.
|
|
1969
|
+
|
|
1970
|
+
Returns:
|
|
1971
|
+
Dict[str, Any]: Dictionary of saveable values
|
|
1972
|
+
"""
|
|
1973
|
+
return SafeLoaderUtils.create_state_dict(self)
|
|
1974
|
+
|
|
1975
|
+
def get_preserved_instances(self) -> Dict[str, Any]:
|
|
1976
|
+
"""
|
|
1977
|
+
Get a dictionary of all preserved class instances.
|
|
1978
|
+
Useful for debugging or manual state inspection.
|
|
1979
|
+
|
|
1980
|
+
Returns:
|
|
1981
|
+
Dict[str, Any]: Dictionary of preserved instances
|
|
1982
|
+
"""
|
|
1983
|
+
return SafeLoaderUtils.preserve_instances(self)
|
|
1984
|
+
|
|
1985
|
+
def graceful_shutdown(self):
|
|
1986
|
+
"""Gracefully shutdown the system saving the state"""
|
|
1987
|
+
logger.info("Shutting down the system...")
|
|
1988
|
+
return self.save()
|
|
1989
|
+
|
|
1990
|
+
def analyze_feedback(self):
|
|
1991
|
+
"""Analyze the feedback for issues"""
|
|
1992
|
+
feedback_counts = {}
|
|
1993
|
+
for feedback in self.feedback:
|
|
1994
|
+
if feedback in feedback_counts:
|
|
1995
|
+
feedback_counts[feedback] += 1
|
|
1996
|
+
else:
|
|
1997
|
+
feedback_counts[feedback] = 1
|
|
1998
|
+
|
|
1999
|
+
def undo_last(self) -> Tuple[str, str]:
|
|
2000
|
+
"""
|
|
2001
|
+
Response the last response and return the previous state
|
|
2002
|
+
|
|
2003
|
+
Example:
|
|
2004
|
+
# Feature 2: Undo functionality
|
|
2005
|
+
response = agent.run("Another task")
|
|
2006
|
+
print(f"Response: {response}")
|
|
2007
|
+
previous_state, message = agent.undo_last()
|
|
2008
|
+
print(message)
|
|
2009
|
+
|
|
2010
|
+
"""
|
|
2011
|
+
if len(self.short_memory) < 2:
|
|
2012
|
+
return None, None
|
|
2013
|
+
|
|
2014
|
+
# Remove the last response but keep the last state, short_memory is a dict
|
|
2015
|
+
self.short_memory.delete(-1)
|
|
2016
|
+
|
|
2017
|
+
# Get the previous state
|
|
2018
|
+
previous_state = self.short_memory[-1]
|
|
2019
|
+
return previous_state, f"Restored to {previous_state}"
|
|
2020
|
+
|
|
2021
|
+
# Response Filtering
|
|
2022
|
+
def add_response_filter(self, filter_word: str) -> None:
|
|
2023
|
+
"""
|
|
2024
|
+
Add a response filter to filter out certain words from the response
|
|
2025
|
+
|
|
2026
|
+
Example:
|
|
2027
|
+
agent.add_response_filter("Trump")
|
|
2028
|
+
agent.run("Generate a report on Trump")
|
|
2029
|
+
|
|
2030
|
+
|
|
2031
|
+
"""
|
|
2032
|
+
logger.info(f"Adding response filter: {filter_word}")
|
|
2033
|
+
self.response_filters.append(filter_word)
|
|
2034
|
+
|
|
2035
|
+
def apply_response_filters(self, response: str) -> str:
|
|
2036
|
+
"""
|
|
2037
|
+
Apply the response filters to the response
|
|
2038
|
+
|
|
2039
|
+
"""
|
|
2040
|
+
logger.info(
|
|
2041
|
+
f"Applying response filters to response: {response}"
|
|
2042
|
+
)
|
|
2043
|
+
for word in self.response_filters:
|
|
2044
|
+
response = response.replace(word, "[FILTERED]")
|
|
2045
|
+
return response
|
|
2046
|
+
|
|
2047
|
+
def filtered_run(self, task: str) -> str:
|
|
2048
|
+
"""
|
|
2049
|
+
# Feature 3: Response filtering
|
|
2050
|
+
agent.add_response_filter("report")
|
|
2051
|
+
response = agent.filtered_run("Generate a report on finance")
|
|
2052
|
+
print(response)
|
|
2053
|
+
"""
|
|
2054
|
+
logger.info(f"Running filtered task: {task}")
|
|
2055
|
+
raw_response = self.run(task)
|
|
2056
|
+
return self.apply_response_filters(raw_response)
|
|
2057
|
+
|
|
2058
|
+
def save_to_yaml(self, file_path: str) -> None:
|
|
2059
|
+
"""
|
|
2060
|
+
Save the agent to a YAML file
|
|
2061
|
+
|
|
2062
|
+
Args:
|
|
2063
|
+
file_path (str): The path to the YAML file
|
|
2064
|
+
"""
|
|
2065
|
+
try:
|
|
2066
|
+
logger.info(f"Saving agent to YAML file: {file_path}")
|
|
2067
|
+
with open(file_path, "w") as f:
|
|
2068
|
+
yaml.dump(self.to_dict(), f)
|
|
2069
|
+
except Exception as error:
|
|
2070
|
+
logger.error(f"Error saving agent to YAML: {error}")
|
|
2071
|
+
raise error
|
|
2072
|
+
|
|
2073
|
+
def get_llm_parameters(self):
|
|
2074
|
+
return str(vars(self.llm))
|
|
2075
|
+
|
|
2076
|
+
def update_system_prompt(self, system_prompt: str):
|
|
2077
|
+
"""Upddate the system message"""
|
|
2078
|
+
self.system_prompt = system_prompt
|
|
2079
|
+
|
|
2080
|
+
def update_max_loops(self, max_loops: Union[int, str]):
|
|
2081
|
+
"""Update the max loops"""
|
|
2082
|
+
self.max_loops = max_loops
|
|
2083
|
+
|
|
2084
|
+
def update_loop_interval(self, loop_interval: int):
|
|
2085
|
+
"""Update the loop interval"""
|
|
2086
|
+
self.loop_interval = loop_interval
|
|
2087
|
+
|
|
2088
|
+
def update_retry_attempts(self, retry_attempts: int):
|
|
2089
|
+
"""Update the retry attempts"""
|
|
2090
|
+
self.retry_attempts = retry_attempts
|
|
2091
|
+
|
|
2092
|
+
def update_retry_interval(self, retry_interval: int):
|
|
2093
|
+
"""Update the retry interval"""
|
|
2094
|
+
self.retry_interval = retry_interval
|
|
2095
|
+
|
|
2096
|
+
def reset(self):
|
|
2097
|
+
"""Reset the agent"""
|
|
2098
|
+
self.short_memory = None
|
|
2099
|
+
|
|
2100
|
+
def ingest_docs(self, docs: List[str], *args, **kwargs):
|
|
2101
|
+
"""Ingest the docs into the memory
|
|
2102
|
+
|
|
2103
|
+
Args:
|
|
2104
|
+
docs (List[str]): Documents of pdfs, text, csvs
|
|
2105
|
+
|
|
2106
|
+
Returns:
|
|
2107
|
+
None
|
|
2108
|
+
"""
|
|
2109
|
+
try:
|
|
2110
|
+
# Process all documents and combine their content
|
|
2111
|
+
all_data = []
|
|
2112
|
+
for doc in docs:
|
|
2113
|
+
data = data_to_text(doc)
|
|
2114
|
+
all_data.append(f"Document: {doc}\n{data}")
|
|
2115
|
+
|
|
2116
|
+
# Combine all document content
|
|
2117
|
+
combined_data = "\n\n".join(all_data)
|
|
2118
|
+
|
|
2119
|
+
return self.short_memory.add(
|
|
2120
|
+
role=self.user_name, content=combined_data
|
|
2121
|
+
)
|
|
2122
|
+
except Exception as error:
|
|
2123
|
+
logger.info(f"Error ingesting docs: {error}", "red")
|
|
2124
|
+
|
|
2125
|
+
def ingest_pdf(self, pdf: str):
|
|
2126
|
+
"""Ingest the pdf into the memory
|
|
2127
|
+
|
|
2128
|
+
Args:
|
|
2129
|
+
pdf (str): file path of pdf
|
|
2130
|
+
"""
|
|
2131
|
+
try:
|
|
2132
|
+
logger.info(f"Ingesting pdf: {pdf}")
|
|
2133
|
+
text = pdf_to_text(pdf)
|
|
2134
|
+
return self.short_memory.add(
|
|
2135
|
+
role=self.user_name, content=text
|
|
2136
|
+
)
|
|
2137
|
+
except Exception as error:
|
|
2138
|
+
logger.info(f"Error ingesting pdf: {error}", "red")
|
|
2139
|
+
|
|
2140
|
+
def receieve_message(self, name: str, message: str):
|
|
2141
|
+
"""Receieve a message"""
|
|
2142
|
+
try:
|
|
2143
|
+
message = f"{name}: {message}"
|
|
2144
|
+
return self.short_memory.add(role=name, content=message)
|
|
2145
|
+
except Exception as error:
|
|
2146
|
+
logger.info(f"Error receiving message: {error}")
|
|
2147
|
+
raise error
|
|
2148
|
+
|
|
2149
|
+
def send_agent_message(
|
|
2150
|
+
self, agent_name: str, message: str, *args, **kwargs
|
|
2151
|
+
):
|
|
2152
|
+
"""Send a message to the agent"""
|
|
2153
|
+
try:
|
|
2154
|
+
logger.info(f"Sending agent message: {message}")
|
|
2155
|
+
message = f"To: {agent_name}: {message}"
|
|
2156
|
+
return self.run(message, *args, **kwargs)
|
|
2157
|
+
except Exception as error:
|
|
2158
|
+
logger.info(f"Error sending agent message: {error}")
|
|
2159
|
+
raise error
|
|
2160
|
+
|
|
2161
|
+
def add_tool(self, tool: Callable):
|
|
2162
|
+
"""Add a single tool to the agent's tools list.
|
|
2163
|
+
|
|
2164
|
+
Args:
|
|
2165
|
+
tool (Callable): The tool function to add
|
|
2166
|
+
|
|
2167
|
+
Returns:
|
|
2168
|
+
The result of appending the tool to the tools list
|
|
2169
|
+
"""
|
|
2170
|
+
logger.info(f"Adding tool: {tool.__name__}")
|
|
2171
|
+
return self.tools.append(tool)
|
|
2172
|
+
|
|
2173
|
+
def add_tools(self, tools: List[Callable]):
|
|
2174
|
+
"""Add multiple tools to the agent's tools list.
|
|
2175
|
+
|
|
2176
|
+
Args:
|
|
2177
|
+
tools (List[Callable]): List of tool functions to add
|
|
2178
|
+
|
|
2179
|
+
Returns:
|
|
2180
|
+
The result of extending the tools list
|
|
2181
|
+
"""
|
|
2182
|
+
logger.info(f"Adding tools: {[t.__name__ for t in tools]}")
|
|
2183
|
+
return self.tools.extend(tools)
|
|
2184
|
+
|
|
2185
|
+
def remove_tool(self, tool: Callable):
|
|
2186
|
+
"""Remove a single tool from the agent's tools list.
|
|
2187
|
+
|
|
2188
|
+
Args:
|
|
2189
|
+
tool (Callable): The tool function to remove
|
|
2190
|
+
|
|
2191
|
+
Returns:
|
|
2192
|
+
The result of removing the tool from the tools list
|
|
2193
|
+
"""
|
|
2194
|
+
logger.info(f"Removing tool: {tool.__name__}")
|
|
2195
|
+
return self.tools.remove(tool)
|
|
2196
|
+
|
|
2197
|
+
def remove_tools(self, tools: List[Callable]):
|
|
2198
|
+
"""Remove multiple tools from the agent's tools list.
|
|
2199
|
+
|
|
2200
|
+
Args:
|
|
2201
|
+
tools (List[Callable]): List of tool functions to remove
|
|
2202
|
+
"""
|
|
2203
|
+
logger.info(f"Removing tools: {[t.__name__ for t in tools]}")
|
|
2204
|
+
for tool in tools:
|
|
2205
|
+
self.tools.remove(tool)
|
|
2206
|
+
|
|
2207
|
+
def get_docs_from_doc_folders(self):
|
|
2208
|
+
"""Get the docs from the files"""
|
|
2209
|
+
try:
|
|
2210
|
+
logger.info("Getting docs from doc folders")
|
|
2211
|
+
# Get the list of files then extract them and add them to the memory
|
|
2212
|
+
files = os.listdir(self.docs_folder)
|
|
2213
|
+
|
|
2214
|
+
# Extract the text from the files
|
|
2215
|
+
# Process each file and combine their contents
|
|
2216
|
+
all_text = ""
|
|
2217
|
+
for file in files:
|
|
2218
|
+
file_path = os.path.join(self.docs_folder, file)
|
|
2219
|
+
text = data_to_text(file_path)
|
|
2220
|
+
all_text += f"\nContent from {file}:\n{text}\n"
|
|
2221
|
+
|
|
2222
|
+
# Add the combined content to memory
|
|
2223
|
+
return self.short_memory.add(
|
|
2224
|
+
role=self.user_name, content=all_text
|
|
2225
|
+
)
|
|
2226
|
+
except Exception as error:
|
|
2227
|
+
logger.error(
|
|
2228
|
+
f"Error getting docs from doc folders: {error}"
|
|
2229
|
+
)
|
|
2230
|
+
raise error
|
|
2231
|
+
|
|
2232
|
+
def sentiment_analysis_handler(self, response: str = None):
|
|
2233
|
+
"""
|
|
2234
|
+
Performs sentiment analysis on the given response and stores the result in the short-term memory.
|
|
2235
|
+
|
|
2236
|
+
Args:
|
|
2237
|
+
response (str): The response to analyze sentiment for.
|
|
2238
|
+
|
|
2239
|
+
Returns:
|
|
2240
|
+
None
|
|
2241
|
+
"""
|
|
2242
|
+
try:
|
|
2243
|
+
# Sentiment analysis
|
|
2244
|
+
if self.sentiment_analyzer:
|
|
2245
|
+
sentiment = self.sentiment_analyzer(response)
|
|
2246
|
+
|
|
2247
|
+
if sentiment > self.sentiment_threshold:
|
|
2248
|
+
pass
|
|
2249
|
+
elif sentiment < self.sentiment_threshold:
|
|
2250
|
+
pass
|
|
2251
|
+
|
|
2252
|
+
self.short_memory.add(
|
|
2253
|
+
role=self.agent_name,
|
|
2254
|
+
content=sentiment,
|
|
2255
|
+
)
|
|
2256
|
+
except Exception:
|
|
2257
|
+
pass
|
|
2258
|
+
|
|
2259
|
+
def stream_response(
|
|
2260
|
+
self, response: str, delay: float = 0.001
|
|
2261
|
+
) -> None:
|
|
2262
|
+
"""
|
|
2263
|
+
Streams the response token by token.
|
|
2264
|
+
|
|
2265
|
+
Args:
|
|
2266
|
+
response (str): The response text to be streamed.
|
|
2267
|
+
delay (float, optional): Delay in seconds between printing each token. Default is 0.1 seconds.
|
|
2268
|
+
|
|
2269
|
+
Raises:
|
|
2270
|
+
ValueError: If the response is not provided.
|
|
2271
|
+
Exception: For any errors encountered during the streaming process.
|
|
2272
|
+
|
|
2273
|
+
Example:
|
|
2274
|
+
response = "This is a sample response from the API."
|
|
2275
|
+
stream_response(response)
|
|
2276
|
+
"""
|
|
2277
|
+
# Check for required inputs
|
|
2278
|
+
if not response:
|
|
2279
|
+
raise ValueError("Response is required.")
|
|
2280
|
+
|
|
2281
|
+
try:
|
|
2282
|
+
# Stream and print the response token by token
|
|
2283
|
+
for token in response.split():
|
|
2284
|
+
time.sleep(delay)
|
|
2285
|
+
except Exception:
|
|
2286
|
+
pass
|
|
2287
|
+
|
|
2288
|
+
def check_available_tokens(self):
|
|
2289
|
+
# Log the amount of tokens left in the memory and in the task
|
|
2290
|
+
if self.tokenizer is not None:
|
|
2291
|
+
tokens_used = count_tokens(
|
|
2292
|
+
self.short_memory.return_history_as_string()
|
|
2293
|
+
)
|
|
2294
|
+
logger.info(
|
|
2295
|
+
f"Tokens available: {self.context_length - tokens_used}"
|
|
2296
|
+
)
|
|
2297
|
+
|
|
2298
|
+
return tokens_used
|
|
2299
|
+
|
|
2300
|
+
def tokens_checks(self):
|
|
2301
|
+
# Check the tokens available
|
|
2302
|
+
tokens_used = count_tokens(
|
|
2303
|
+
self.short_memory.return_history_as_string()
|
|
2304
|
+
)
|
|
2305
|
+
out = self.check_available_tokens()
|
|
2306
|
+
|
|
2307
|
+
logger.info(
|
|
2308
|
+
f"Tokens available: {out} Context Length: {self.context_length} Tokens in memory: {tokens_used}"
|
|
2309
|
+
)
|
|
2310
|
+
|
|
2311
|
+
return out
|
|
2312
|
+
|
|
2313
|
+
def update_tool_usage(
|
|
2314
|
+
self,
|
|
2315
|
+
step_id: str,
|
|
2316
|
+
tool_name: str,
|
|
2317
|
+
tool_args: dict,
|
|
2318
|
+
tool_response: Any,
|
|
2319
|
+
):
|
|
2320
|
+
"""Update tool usage information for a specific step."""
|
|
2321
|
+
for step in self.agent_output.steps:
|
|
2322
|
+
if step.step_id == step_id:
|
|
2323
|
+
step.response.tool_calls.append(
|
|
2324
|
+
{
|
|
2325
|
+
"tool": tool_name,
|
|
2326
|
+
"arguments": tool_args,
|
|
2327
|
+
"response": str(tool_response),
|
|
2328
|
+
}
|
|
2329
|
+
)
|
|
2330
|
+
break
|
|
2331
|
+
|
|
2332
|
+
def _serialize_callable(
|
|
2333
|
+
self, attr_value: Callable
|
|
2334
|
+
) -> Dict[str, Any]:
|
|
2335
|
+
"""
|
|
2336
|
+
Serializes callable attributes by extracting their name and docstring.
|
|
2337
|
+
|
|
2338
|
+
Args:
|
|
2339
|
+
attr_value (Callable): The callable to serialize.
|
|
2340
|
+
|
|
2341
|
+
Returns:
|
|
2342
|
+
Dict[str, Any]: Dictionary with name and docstring of the callable.
|
|
2343
|
+
"""
|
|
2344
|
+
return {
|
|
2345
|
+
"name": getattr(
|
|
2346
|
+
attr_value, "__name__", type(attr_value).__name__
|
|
2347
|
+
),
|
|
2348
|
+
"doc": getattr(attr_value, "__doc__", None),
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
def _serialize_attr(self, attr_name: str, attr_value: Any) -> Any:
|
|
2352
|
+
"""
|
|
2353
|
+
Serializes an individual attribute, handling non-serializable objects.
|
|
2354
|
+
|
|
2355
|
+
Args:
|
|
2356
|
+
attr_name (str): The name of the attribute.
|
|
2357
|
+
attr_value (Any): The value of the attribute.
|
|
2358
|
+
|
|
2359
|
+
Returns:
|
|
2360
|
+
Any: The serialized value of the attribute.
|
|
2361
|
+
"""
|
|
2362
|
+
try:
|
|
2363
|
+
if callable(attr_value):
|
|
2364
|
+
return self._serialize_callable(attr_value)
|
|
2365
|
+
elif hasattr(attr_value, "to_dict"):
|
|
2366
|
+
return (
|
|
2367
|
+
attr_value.to_dict()
|
|
2368
|
+
) # Recursive serialization for nested objects
|
|
2369
|
+
else:
|
|
2370
|
+
json.dumps(
|
|
2371
|
+
attr_value
|
|
2372
|
+
) # Attempt to serialize to catch non-serializable objects
|
|
2373
|
+
return attr_value
|
|
2374
|
+
except (TypeError, ValueError):
|
|
2375
|
+
return f"<Non-serializable: {type(attr_value).__name__}>"
|
|
2376
|
+
|
|
2377
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
2378
|
+
"""
|
|
2379
|
+
Converts all attributes of the class, including callables, into a dictionary.
|
|
2380
|
+
Handles non-serializable attributes by converting them or skipping them.
|
|
2381
|
+
|
|
2382
|
+
Returns:
|
|
2383
|
+
Dict[str, Any]: A dictionary representation of the class attributes.
|
|
2384
|
+
"""
|
|
2385
|
+
|
|
2386
|
+
# Create a copy of the dict to avoid mutating the original object
|
|
2387
|
+
# Remove the llm object from the copy since it's not serializable
|
|
2388
|
+
dict_copy = self.__dict__.copy()
|
|
2389
|
+
dict_copy.pop("llm", None)
|
|
2390
|
+
|
|
2391
|
+
return {
|
|
2392
|
+
attr_name: self._serialize_attr(attr_name, attr_value)
|
|
2393
|
+
for attr_name, attr_value in dict_copy.items()
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
def to_json(self, indent: int = 4, *args, **kwargs):
|
|
2397
|
+
return json.dumps(
|
|
2398
|
+
self.to_dict(), indent=indent, *args, **kwargs
|
|
2399
|
+
)
|
|
2400
|
+
|
|
2401
|
+
def to_yaml(self, indent: int = 4, *args, **kwargs):
|
|
2402
|
+
return yaml.dump(
|
|
2403
|
+
self.to_dict(), indent=indent, *args, **kwargs
|
|
2404
|
+
)
|
|
2405
|
+
|
|
2406
|
+
def to_toml(self, *args, **kwargs):
|
|
2407
|
+
return toml.dumps(self.to_dict(), *args, **kwargs)
|
|
2408
|
+
|
|
2409
|
+
def model_dump_json(self):
|
|
2410
|
+
logger.info(
|
|
2411
|
+
f"Saving {self.agent_name} model to JSON in the {self.workspace_dir} directory"
|
|
2412
|
+
)
|
|
2413
|
+
|
|
2414
|
+
create_file_in_folder(
|
|
2415
|
+
self.workspace_dir,
|
|
2416
|
+
f"{self.agent_name}.json",
|
|
2417
|
+
str(self.to_json()),
|
|
2418
|
+
)
|
|
2419
|
+
|
|
2420
|
+
return f"Model saved to {self.workspace_dir}/{self.agent_name}.json"
|
|
2421
|
+
|
|
2422
|
+
def model_dump_yaml(self):
|
|
2423
|
+
logger.info(
|
|
2424
|
+
f"Saving {self.agent_name} model to YAML in the {self.workspace_dir} directory"
|
|
2425
|
+
)
|
|
2426
|
+
|
|
2427
|
+
create_file_in_folder(
|
|
2428
|
+
self.workspace_dir,
|
|
2429
|
+
f"{self.agent_name}.yaml",
|
|
2430
|
+
str(self.to_yaml()),
|
|
2431
|
+
)
|
|
2432
|
+
|
|
2433
|
+
return f"Model saved to {self.workspace_dir}/{self.agent_name}.yaml"
|
|
2434
|
+
|
|
2435
|
+
def handle_tool_schema_ops(self):
|
|
2436
|
+
if exists(self.tool_schema):
|
|
2437
|
+
logger.info(f"Tool schema provided: {self.tool_schema}")
|
|
2438
|
+
|
|
2439
|
+
output = self.tool_struct.base_model_to_dict(
|
|
2440
|
+
self.tool_schema, output_str=True
|
|
2441
|
+
)
|
|
2442
|
+
|
|
2443
|
+
# Add the tool schema to the short memory
|
|
2444
|
+
self.short_memory.add(
|
|
2445
|
+
role=self.agent_name, content=output
|
|
2446
|
+
)
|
|
2447
|
+
|
|
2448
|
+
# If multiple base models, then conver them.
|
|
2449
|
+
if exists(self.list_base_models):
|
|
2450
|
+
logger.info(
|
|
2451
|
+
"Multiple base models provided, Automatically converting to OpenAI function"
|
|
2452
|
+
)
|
|
2453
|
+
|
|
2454
|
+
schemas = self.tool_struct.multi_base_models_to_dict(
|
|
2455
|
+
output_str=True
|
|
2456
|
+
)
|
|
2457
|
+
|
|
2458
|
+
# If the output is a string then add it to the memory
|
|
2459
|
+
self.short_memory.add(
|
|
2460
|
+
role=self.agent_name, content=schemas
|
|
2461
|
+
)
|
|
2462
|
+
|
|
2463
|
+
return None
|
|
2464
|
+
|
|
2465
|
+
def call_llm(
|
|
2466
|
+
self,
|
|
2467
|
+
task: str,
|
|
2468
|
+
img: Optional[str] = None,
|
|
2469
|
+
current_loop: int = 0,
|
|
2470
|
+
streaming_callback: Optional[Callable[[str], None]] = None,
|
|
2471
|
+
*args,
|
|
2472
|
+
**kwargs,
|
|
2473
|
+
) -> str:
|
|
2474
|
+
"""
|
|
2475
|
+
Calls the appropriate method on the `llm` object based on the given task.
|
|
2476
|
+
|
|
2477
|
+
Args:
|
|
2478
|
+
task (str): The task to be performed by the `llm` object.
|
|
2479
|
+
img (str, optional): Path or URL to an image file.
|
|
2480
|
+
audio (str, optional): Path or URL to an audio file.
|
|
2481
|
+
streaming_callback (Optional[Callable[[str], None]]): Callback function to receive streaming tokens in real-time.
|
|
2482
|
+
*args: Variable length argument list.
|
|
2483
|
+
**kwargs: Arbitrary keyword arguments.
|
|
2484
|
+
|
|
2485
|
+
Returns:
|
|
2486
|
+
str: The result of the method call on the `llm` object.
|
|
2487
|
+
|
|
2488
|
+
Raises:
|
|
2489
|
+
AttributeError: If no suitable method is found in the llm object.
|
|
2490
|
+
TypeError: If task is not a string or llm object is None.
|
|
2491
|
+
ValueError: If task is empty.
|
|
2492
|
+
"""
|
|
2493
|
+
|
|
2494
|
+
# Filter out is_last from kwargs if present
|
|
2495
|
+
if "is_last" in kwargs:
|
|
2496
|
+
del kwargs["is_last"]
|
|
2497
|
+
|
|
2498
|
+
try:
|
|
2499
|
+
if self.stream and hasattr(self.llm, "stream"):
|
|
2500
|
+
original_stream = self.llm.stream
|
|
2501
|
+
self.llm.stream = True
|
|
2502
|
+
|
|
2503
|
+
if img is not None:
|
|
2504
|
+
streaming_response = self.llm.run(
|
|
2505
|
+
task=task, img=img, *args, **kwargs
|
|
2506
|
+
)
|
|
2507
|
+
else:
|
|
2508
|
+
streaming_response = self.llm.run(
|
|
2509
|
+
task=task, *args, **kwargs
|
|
2510
|
+
)
|
|
2511
|
+
|
|
2512
|
+
if hasattr(
|
|
2513
|
+
streaming_response, "__iter__"
|
|
2514
|
+
) and not isinstance(streaming_response, str):
|
|
2515
|
+
complete_response = ""
|
|
2516
|
+
token_count = 0
|
|
2517
|
+
final_chunk = None
|
|
2518
|
+
first_chunk = None
|
|
2519
|
+
|
|
2520
|
+
for chunk in streaming_response:
|
|
2521
|
+
if first_chunk is None:
|
|
2522
|
+
first_chunk = chunk
|
|
2523
|
+
|
|
2524
|
+
if (
|
|
2525
|
+
hasattr(chunk, "choices")
|
|
2526
|
+
and chunk.choices[0].delta.content
|
|
2527
|
+
):
|
|
2528
|
+
content = chunk.choices[0].delta.content
|
|
2529
|
+
complete_response += content
|
|
2530
|
+
token_count += 1
|
|
2531
|
+
|
|
2532
|
+
# Schema per token outputted
|
|
2533
|
+
token_info = {
|
|
2534
|
+
"token_index": token_count,
|
|
2535
|
+
"model": getattr(
|
|
2536
|
+
chunk,
|
|
2537
|
+
"model",
|
|
2538
|
+
self.get_current_model(),
|
|
2539
|
+
),
|
|
2540
|
+
"id": getattr(chunk, "id", ""),
|
|
2541
|
+
"created": getattr(
|
|
2542
|
+
chunk, "created", int(time.time())
|
|
2543
|
+
),
|
|
2544
|
+
"object": getattr(
|
|
2545
|
+
chunk,
|
|
2546
|
+
"object",
|
|
2547
|
+
"chat.completion.chunk",
|
|
2548
|
+
),
|
|
2549
|
+
"token": content,
|
|
2550
|
+
"system_fingerprint": getattr(
|
|
2551
|
+
chunk, "system_fingerprint", ""
|
|
2552
|
+
),
|
|
2553
|
+
"finish_reason": chunk.choices[
|
|
2554
|
+
0
|
|
2555
|
+
].finish_reason,
|
|
2556
|
+
"citations": getattr(
|
|
2557
|
+
chunk, "citations", None
|
|
2558
|
+
),
|
|
2559
|
+
"provider_specific_fields": getattr(
|
|
2560
|
+
chunk,
|
|
2561
|
+
"provider_specific_fields",
|
|
2562
|
+
None,
|
|
2563
|
+
),
|
|
2564
|
+
"service_tier": getattr(
|
|
2565
|
+
chunk, "service_tier", "default"
|
|
2566
|
+
),
|
|
2567
|
+
"obfuscation": getattr(
|
|
2568
|
+
chunk, "obfuscation", None
|
|
2569
|
+
),
|
|
2570
|
+
"usage": getattr(
|
|
2571
|
+
chunk, "usage", None
|
|
2572
|
+
),
|
|
2573
|
+
"logprobs": chunk.choices[0].logprobs,
|
|
2574
|
+
"timestamp": time.time(),
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
logger.debug(f"ResponseStream {token_info}")
|
|
2578
|
+
|
|
2579
|
+
if streaming_callback is not None:
|
|
2580
|
+
streaming_callback(token_info)
|
|
2581
|
+
|
|
2582
|
+
final_chunk = chunk
|
|
2583
|
+
|
|
2584
|
+
# Final ModelResponse to stream
|
|
2585
|
+
if (
|
|
2586
|
+
final_chunk
|
|
2587
|
+
and hasattr(final_chunk, "usage")
|
|
2588
|
+
and final_chunk.usage
|
|
2589
|
+
):
|
|
2590
|
+
usage = final_chunk.usage
|
|
2591
|
+
logger.debug(
|
|
2592
|
+
f"ModelResponseStream(id='{getattr(final_chunk, 'id', 'N/A')}', "
|
|
2593
|
+
f"created={getattr(final_chunk, 'created', 'N/A')}, "
|
|
2594
|
+
f"model='{getattr(final_chunk, 'model', self.get_current_model())}', "
|
|
2595
|
+
f"object='{getattr(final_chunk, 'object', 'chat.completion.chunk')}', "
|
|
2596
|
+
f"system_fingerprint='{getattr(final_chunk, 'system_fingerprint', 'N/A')}', "
|
|
2597
|
+
f"choices=[StreamingChoices(finish_reason='{final_chunk.choices[0].finish_reason}', "
|
|
2598
|
+
f"index=0, delta=Delta(provider_specific_fields=None, content=None, role=None, "
|
|
2599
|
+
f"function_call=None, tool_calls=None, audio=None), logprobs=None)], "
|
|
2600
|
+
f"provider_specific_fields=None, "
|
|
2601
|
+
f"usage=Usage(completion_tokens={usage.completion_tokens}, "
|
|
2602
|
+
f"prompt_tokens={usage.prompt_tokens}, "
|
|
2603
|
+
f"total_tokens={usage.total_tokens}, "
|
|
2604
|
+
f"completion_tokens_details=CompletionTokensDetailsWrapper("
|
|
2605
|
+
f"accepted_prediction_tokens={usage.completion_tokens_details.accepted_prediction_tokens}, "
|
|
2606
|
+
f"audio_tokens={usage.completion_tokens_details.audio_tokens}, "
|
|
2607
|
+
f"reasoning_tokens={usage.completion_tokens_details.reasoning_tokens}, "
|
|
2608
|
+
f"rejected_prediction_tokens={usage.completion_tokens_details.rejected_prediction_tokens}, "
|
|
2609
|
+
f"text_tokens={usage.completion_tokens_details.text_tokens}), "
|
|
2610
|
+
f"prompt_tokens_details=PromptTokensDetailsWrapper("
|
|
2611
|
+
f"audio_tokens={usage.prompt_tokens_details.audio_tokens}, "
|
|
2612
|
+
f"cached_tokens={usage.prompt_tokens_details.cached_tokens}, "
|
|
2613
|
+
f"text_tokens={usage.prompt_tokens_details.text_tokens}, "
|
|
2614
|
+
f"image_tokens={usage.prompt_tokens_details.image_tokens})))"
|
|
2615
|
+
)
|
|
2616
|
+
else:
|
|
2617
|
+
logger.debug(
|
|
2618
|
+
f"ModelResponseStream(id='{getattr(final_chunk, 'id', 'N/A')}', "
|
|
2619
|
+
f"created={getattr(final_chunk, 'created', 'N/A')}, "
|
|
2620
|
+
f"model='{getattr(final_chunk, 'model', self.get_current_model())}', "
|
|
2621
|
+
f"object='{getattr(final_chunk, 'object', 'chat.completion.chunk')}', "
|
|
2622
|
+
f"system_fingerprint='{getattr(final_chunk, 'system_fingerprint', 'N/A')}', "
|
|
2623
|
+
f"choices=[StreamingChoices(finish_reason='{final_chunk.choices[0].finish_reason}', "
|
|
2624
|
+
f"index=0, delta=Delta(provider_specific_fields=None, content=None, role=None, "
|
|
2625
|
+
f"function_call=None, tool_calls=None, audio=None), logprobs=None)], "
|
|
2626
|
+
f"provider_specific_fields=None)"
|
|
2627
|
+
)
|
|
2628
|
+
|
|
2629
|
+
self.llm.stream = original_stream
|
|
2630
|
+
return complete_response
|
|
2631
|
+
else:
|
|
2632
|
+
self.llm.stream = original_stream
|
|
2633
|
+
return streaming_response
|
|
2634
|
+
|
|
2635
|
+
elif self.streaming_on and hasattr(self.llm, "stream"):
|
|
2636
|
+
original_stream = self.llm.stream
|
|
2637
|
+
self.llm.stream = True
|
|
2638
|
+
|
|
2639
|
+
if img is not None:
|
|
2640
|
+
streaming_response = self.llm.run(
|
|
2641
|
+
task=task, img=img, *args, **kwargs
|
|
2642
|
+
)
|
|
2643
|
+
else:
|
|
2644
|
+
streaming_response = self.llm.run(
|
|
2645
|
+
task=task, *args, **kwargs
|
|
2646
|
+
)
|
|
2647
|
+
|
|
2648
|
+
# If we get a streaming response, handle it with the new streaming panel
|
|
2649
|
+
if hasattr(
|
|
2650
|
+
streaming_response, "__iter__"
|
|
2651
|
+
) and not isinstance(streaming_response, str):
|
|
2652
|
+
# Check if streaming_callback is provided (for ConcurrentWorkflow dashboard integration)
|
|
2653
|
+
if streaming_callback is not None:
|
|
2654
|
+
# Real-time callback streaming for dashboard integration
|
|
2655
|
+
chunks = []
|
|
2656
|
+
for chunk in streaming_response:
|
|
2657
|
+
if (
|
|
2658
|
+
hasattr(chunk, "choices")
|
|
2659
|
+
and chunk.choices[0].delta.content
|
|
2660
|
+
):
|
|
2661
|
+
content = chunk.choices[
|
|
2662
|
+
0
|
|
2663
|
+
].delta.content
|
|
2664
|
+
chunks.append(content)
|
|
2665
|
+
# Call the streaming callback with the new chunk
|
|
2666
|
+
streaming_callback(content)
|
|
2667
|
+
complete_response = "".join(chunks)
|
|
2668
|
+
# Check print_on parameter for different streaming behaviors
|
|
2669
|
+
elif self.print_on is False:
|
|
2670
|
+
# Silent streaming - no printing, just collect chunks
|
|
2671
|
+
chunks = []
|
|
2672
|
+
for chunk in streaming_response:
|
|
2673
|
+
if (
|
|
2674
|
+
hasattr(chunk, "choices")
|
|
2675
|
+
and chunk.choices[0].delta.content
|
|
2676
|
+
):
|
|
2677
|
+
content = chunk.choices[
|
|
2678
|
+
0
|
|
2679
|
+
].delta.content
|
|
2680
|
+
chunks.append(content)
|
|
2681
|
+
complete_response = "".join(chunks)
|
|
2682
|
+
else:
|
|
2683
|
+
# Collect chunks for conversation saving
|
|
2684
|
+
collected_chunks = []
|
|
2685
|
+
|
|
2686
|
+
def on_chunk_received(chunk: str):
|
|
2687
|
+
"""Callback to collect chunks as they arrive"""
|
|
2688
|
+
collected_chunks.append(chunk)
|
|
2689
|
+
# Optional: Save each chunk to conversation in real-time
|
|
2690
|
+
# This creates a more detailed conversation history
|
|
2691
|
+
if self.verbose:
|
|
2692
|
+
logger.debug(
|
|
2693
|
+
f"Streaming chunk received: {chunk[:50]}..."
|
|
2694
|
+
)
|
|
2695
|
+
|
|
2696
|
+
# Use the streaming panel to display and collect the response
|
|
2697
|
+
complete_response = formatter.print_streaming_panel(
|
|
2698
|
+
streaming_response,
|
|
2699
|
+
title=f"🤖 Agent: {self.agent_name} Loops: {current_loop}",
|
|
2700
|
+
style=None, # Use random color like non-streaming approach
|
|
2701
|
+
collect_chunks=True,
|
|
2702
|
+
on_chunk_callback=on_chunk_received,
|
|
2703
|
+
)
|
|
2704
|
+
|
|
2705
|
+
# Restore original stream setting
|
|
2706
|
+
self.llm.stream = original_stream
|
|
2707
|
+
|
|
2708
|
+
# Return the complete response for further processing
|
|
2709
|
+
return complete_response
|
|
2710
|
+
else:
|
|
2711
|
+
# Restore original stream setting
|
|
2712
|
+
self.llm.stream = original_stream
|
|
2713
|
+
return streaming_response
|
|
2714
|
+
else:
|
|
2715
|
+
args = {
|
|
2716
|
+
"task": task,
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2719
|
+
if img is not None:
|
|
2720
|
+
args["img"] = img
|
|
2721
|
+
|
|
2722
|
+
out = self.llm.run(**args, **kwargs)
|
|
2723
|
+
|
|
2724
|
+
return out
|
|
2725
|
+
|
|
2726
|
+
except (
|
|
2727
|
+
AgentLLMError,
|
|
2728
|
+
BadRequestError,
|
|
2729
|
+
InternalServerError,
|
|
2730
|
+
AuthenticationError,
|
|
2731
|
+
Exception,
|
|
2732
|
+
) as e:
|
|
2733
|
+
logger.error(
|
|
2734
|
+
f"Error calling LLM with model '{self.get_current_model()}': {e}. "
|
|
2735
|
+
f"Task: {task}, Args: {args}, Kwargs: {kwargs} Traceback: {traceback.format_exc()}"
|
|
2736
|
+
)
|
|
2737
|
+
raise e
|
|
2738
|
+
|
|
2739
|
+
def handle_sop_ops(self):
|
|
2740
|
+
# If the user inputs a list of strings for the sop then join them and set the sop
|
|
2741
|
+
if exists(self.sop_list):
|
|
2742
|
+
self.sop = "\n".join(self.sop_list)
|
|
2743
|
+
self.short_memory.add(
|
|
2744
|
+
role=self.user_name, content=self.sop
|
|
2745
|
+
)
|
|
2746
|
+
|
|
2747
|
+
if exists(self.sop):
|
|
2748
|
+
self.short_memory.add(
|
|
2749
|
+
role=self.user_name, content=self.sop
|
|
2750
|
+
)
|
|
2751
|
+
|
|
2752
|
+
logger.info("SOP Uploaded into the memory")
|
|
2753
|
+
|
|
2754
|
+
def run(
|
|
2755
|
+
self,
|
|
2756
|
+
task: Optional[Union[str, Any]] = None,
|
|
2757
|
+
img: Optional[str] = None,
|
|
2758
|
+
imgs: Optional[List[str]] = None,
|
|
2759
|
+
correct_answer: Optional[str] = None,
|
|
2760
|
+
streaming_callback: Optional[Callable[[str], None]] = None,
|
|
2761
|
+
n: int = 1,
|
|
2762
|
+
*args,
|
|
2763
|
+
**kwargs,
|
|
2764
|
+
) -> Any:
|
|
2765
|
+
"""
|
|
2766
|
+
Executes the agent's run method on a specified device, with optional scheduling.
|
|
2767
|
+
|
|
2768
|
+
This method attempts to execute the agent's run method on a specified device, either CPU or GPU. It logs the device selection and the number of cores or GPU ID used. If the device is set to CPU, it can use all available cores or a specific core specified by `device_id`. If the device is set to GPU, it uses the GPU specified by `device_id`.
|
|
2769
|
+
|
|
2770
|
+
If a `scheduled_date` is provided, the method will wait until that date and time before executing the task.
|
|
2771
|
+
|
|
2772
|
+
Args:
|
|
2773
|
+
task (Optional[str], optional): The task to be executed. Defaults to None.
|
|
2774
|
+
img (Optional[str], optional): The image to be processed. Defaults to None.
|
|
2775
|
+
imgs (Optional[List[str]], optional): The list of images to be processed. Defaults to None.
|
|
2776
|
+
streaming_callback (Optional[Callable[[str], None]], optional): Callback function to receive streaming tokens in real-time. Defaults to None.
|
|
2777
|
+
*args: Additional positional arguments to be passed to the execution method.
|
|
2778
|
+
**kwargs: Additional keyword arguments to be passed to the execution method.
|
|
2779
|
+
|
|
2780
|
+
Returns:
|
|
2781
|
+
Any: The result of the execution.
|
|
2782
|
+
|
|
2783
|
+
Raises:
|
|
2784
|
+
ValueError: If an invalid device is specified.
|
|
2785
|
+
Exception: If any other error occurs during execution.
|
|
2786
|
+
"""
|
|
2787
|
+
|
|
2788
|
+
if not isinstance(task, str):
|
|
2789
|
+
task = format_data_structure(task)
|
|
2790
|
+
|
|
2791
|
+
try:
|
|
2792
|
+
if exists(imgs):
|
|
2793
|
+
output = self.run_multiple_images(
|
|
2794
|
+
task=task, imgs=imgs, *args, **kwargs
|
|
2795
|
+
)
|
|
2796
|
+
elif exists(correct_answer):
|
|
2797
|
+
output = self.continuous_run_with_answer(
|
|
2798
|
+
task=task,
|
|
2799
|
+
img=img,
|
|
2800
|
+
correct_answer=correct_answer,
|
|
2801
|
+
*args,
|
|
2802
|
+
**kwargs,
|
|
2803
|
+
)
|
|
2804
|
+
elif exists(self.handoffs):
|
|
2805
|
+
output = self.handle_handoffs(task=task)
|
|
2806
|
+
elif n > 1:
|
|
2807
|
+
output = [self.run(task=task) for _ in range(n)]
|
|
2808
|
+
else:
|
|
2809
|
+
output = self._run(
|
|
2810
|
+
task=task,
|
|
2811
|
+
img=img,
|
|
2812
|
+
streaming_callback=streaming_callback,
|
|
2813
|
+
*args,
|
|
2814
|
+
**kwargs,
|
|
2815
|
+
)
|
|
2816
|
+
|
|
2817
|
+
return output
|
|
2818
|
+
|
|
2819
|
+
except (
|
|
2820
|
+
AgentRunError,
|
|
2821
|
+
AgentLLMError,
|
|
2822
|
+
BadRequestError,
|
|
2823
|
+
InternalServerError,
|
|
2824
|
+
AuthenticationError,
|
|
2825
|
+
Exception,
|
|
2826
|
+
) as e:
|
|
2827
|
+
# Try fallback models if available
|
|
2828
|
+
if self.is_fallback_available():
|
|
2829
|
+
return self._handle_fallback_execution(
|
|
2830
|
+
task=task,
|
|
2831
|
+
img=img,
|
|
2832
|
+
imgs=imgs,
|
|
2833
|
+
correct_answer=correct_answer,
|
|
2834
|
+
streaming_callback=streaming_callback,
|
|
2835
|
+
original_error=e,
|
|
2836
|
+
*args,
|
|
2837
|
+
**kwargs,
|
|
2838
|
+
)
|
|
2839
|
+
else:
|
|
2840
|
+
if self.verbose:
|
|
2841
|
+
# No fallback available
|
|
2842
|
+
logger.error(
|
|
2843
|
+
f"Agent Name: {self.agent_name} [NO FALLBACK] failed with model '{self.get_current_model()}' "
|
|
2844
|
+
f"and no fallback models are configured. Error: {str(e)[:100]}{'...' if len(str(e)) > 100 else ''}"
|
|
2845
|
+
)
|
|
2846
|
+
|
|
2847
|
+
self._handle_run_error(e)
|
|
2848
|
+
|
|
2849
|
+
except KeyboardInterrupt:
|
|
2850
|
+
logger.warning(
|
|
2851
|
+
f"Agent Name: {self.agent_name} Keyboard interrupt detected. "
|
|
2852
|
+
"If autosave is enabled, the agent's state will be saved to the workspace directory. "
|
|
2853
|
+
"To enable autosave, please initialize the agent with Agent(autosave=True)."
|
|
2854
|
+
"For technical support, refer to this document: https://docs.swarms.world/en/latest/swarms/support/"
|
|
2855
|
+
)
|
|
2856
|
+
raise KeyboardInterrupt
|
|
2857
|
+
|
|
2858
|
+
def _handle_fallback_execution(
|
|
2859
|
+
self,
|
|
2860
|
+
task: Optional[Union[str, Any]] = None,
|
|
2861
|
+
img: Optional[str] = None,
|
|
2862
|
+
imgs: Optional[List[str]] = None,
|
|
2863
|
+
correct_answer: Optional[str] = None,
|
|
2864
|
+
streaming_callback: Optional[Callable[[str], None]] = None,
|
|
2865
|
+
original_error: Exception = None,
|
|
2866
|
+
*args,
|
|
2867
|
+
**kwargs,
|
|
2868
|
+
) -> Any:
|
|
2869
|
+
"""
|
|
2870
|
+
Handles fallback execution when the primary model fails.
|
|
2871
|
+
|
|
2872
|
+
This method attempts to execute the task using fallback models when the primary
|
|
2873
|
+
model encounters an error. It will try each available fallback model in sequence
|
|
2874
|
+
until either the task succeeds or all fallback models are exhausted.
|
|
2875
|
+
|
|
2876
|
+
Args:
|
|
2877
|
+
task (Optional[Union[str, Any]], optional): The task to be executed. Defaults to None.
|
|
2878
|
+
img (Optional[str], optional): The image to be processed. Defaults to None.
|
|
2879
|
+
imgs (Optional[List[str]], optional): The list of images to be processed. Defaults to None.
|
|
2880
|
+
correct_answer (Optional[str], optional): The correct answer for continuous run mode. Defaults to None.
|
|
2881
|
+
streaming_callback (Optional[Callable[[str], None]], optional): Callback function to receive streaming tokens in real-time. Defaults to None.
|
|
2882
|
+
original_error (Exception): The original error that triggered the fallback. Defaults to None.
|
|
2883
|
+
*args: Additional positional arguments to be passed to the execution method.
|
|
2884
|
+
**kwargs: Additional keyword arguments to be passed to the execution method.
|
|
2885
|
+
|
|
2886
|
+
Returns:
|
|
2887
|
+
Any: The result of the execution if successful.
|
|
2888
|
+
|
|
2889
|
+
Raises:
|
|
2890
|
+
Exception: If all fallback models fail or no fallback models are available.
|
|
2891
|
+
"""
|
|
2892
|
+
# Check if fallback models are available
|
|
2893
|
+
if not self.is_fallback_available():
|
|
2894
|
+
if self.verbose:
|
|
2895
|
+
logger.error(
|
|
2896
|
+
f"Agent Name: {self.agent_name} [NO FALLBACK] failed with model '{self.get_current_model()}' "
|
|
2897
|
+
f"and no fallback models are configured. Error: {str(original_error)[:100]}{'...' if len(str(original_error)) > 100 else ''}"
|
|
2898
|
+
)
|
|
2899
|
+
self._handle_run_error(original_error)
|
|
2900
|
+
return None
|
|
2901
|
+
|
|
2902
|
+
# Try to switch to the next fallback model
|
|
2903
|
+
if not self.switch_to_next_model():
|
|
2904
|
+
if self.verbose:
|
|
2905
|
+
logger.error(
|
|
2906
|
+
f"Agent Name: {self.agent_name} [FALLBACK EXHAUSTED] has exhausted all available models. "
|
|
2907
|
+
f"Tried {len(self.get_available_models())} models: {self.get_available_models()}"
|
|
2908
|
+
)
|
|
2909
|
+
self._handle_run_error(original_error)
|
|
2910
|
+
return None
|
|
2911
|
+
|
|
2912
|
+
# Log fallback attempt
|
|
2913
|
+
if self.verbose:
|
|
2914
|
+
logger.warning(
|
|
2915
|
+
f"Agent Name: {self.agent_name} [FALLBACK] failed with model '{self.get_current_model()}'. "
|
|
2916
|
+
f"Switching to fallback model '{self.get_current_model()}' (attempt {self.current_model_index + 1}/{len(self.get_available_models())})"
|
|
2917
|
+
)
|
|
2918
|
+
|
|
2919
|
+
try:
|
|
2920
|
+
# Recursive call to run() with the new model
|
|
2921
|
+
result = self.run(
|
|
2922
|
+
task=task,
|
|
2923
|
+
img=img,
|
|
2924
|
+
imgs=imgs,
|
|
2925
|
+
correct_answer=correct_answer,
|
|
2926
|
+
streaming_callback=streaming_callback,
|
|
2927
|
+
*args,
|
|
2928
|
+
**kwargs,
|
|
2929
|
+
)
|
|
2930
|
+
|
|
2931
|
+
if self.verbose:
|
|
2932
|
+
# Log successful completion with fallback model
|
|
2933
|
+
logger.info(
|
|
2934
|
+
f"Agent Name: {self.agent_name} [FALLBACK SUCCESS] successfully completed task "
|
|
2935
|
+
f"using fallback model '{self.get_current_model()}'"
|
|
2936
|
+
)
|
|
2937
|
+
return result
|
|
2938
|
+
|
|
2939
|
+
except Exception as fallback_error:
|
|
2940
|
+
logger.error(
|
|
2941
|
+
f"Agent Name: {self.agent_name} Fallback model '{self.get_current_model()}' also failed: {fallback_error}"
|
|
2942
|
+
)
|
|
2943
|
+
|
|
2944
|
+
# Try the next fallback model recursively
|
|
2945
|
+
return self._handle_fallback_execution(
|
|
2946
|
+
task=task,
|
|
2947
|
+
img=img,
|
|
2948
|
+
imgs=imgs,
|
|
2949
|
+
correct_answer=correct_answer,
|
|
2950
|
+
streaming_callback=streaming_callback,
|
|
2951
|
+
original_error=original_error,
|
|
2952
|
+
*args,
|
|
2953
|
+
**kwargs,
|
|
2954
|
+
)
|
|
2955
|
+
|
|
2956
|
+
def run_batched(
|
|
2957
|
+
self,
|
|
2958
|
+
tasks: List[str],
|
|
2959
|
+
imgs: List[str] = None,
|
|
2960
|
+
*args,
|
|
2961
|
+
**kwargs,
|
|
2962
|
+
):
|
|
2963
|
+
"""
|
|
2964
|
+
Run a batch of tasks concurrently.
|
|
2965
|
+
|
|
2966
|
+
Args:
|
|
2967
|
+
tasks (List[str]): List of tasks to run.
|
|
2968
|
+
imgs (List[str], optional): List of images to run. Defaults to None.
|
|
2969
|
+
*args: Additional positional arguments to be passed to the execution method.
|
|
2970
|
+
**kwargs: Additional keyword arguments to be passed to the execution method.
|
|
2971
|
+
|
|
2972
|
+
Returns:
|
|
2973
|
+
List[Any]: List of results from each task execution.
|
|
2974
|
+
"""
|
|
2975
|
+
return [
|
|
2976
|
+
self.run(task=task, imgs=imgs, *args, **kwargs)
|
|
2977
|
+
for task, imgs in zip(tasks, imgs)
|
|
2978
|
+
]
|
|
2979
|
+
|
|
2980
|
+
def handle_artifacts(
|
|
2981
|
+
self, text: str, file_output_path: str, file_extension: str
|
|
2982
|
+
) -> None:
|
|
2983
|
+
"""Handle creating and saving artifacts with error handling."""
|
|
2984
|
+
try:
|
|
2985
|
+
# Ensure file_extension starts with a dot
|
|
2986
|
+
if not file_extension.startswith("."):
|
|
2987
|
+
file_extension = "." + file_extension
|
|
2988
|
+
|
|
2989
|
+
# If file_output_path doesn't have an extension, treat it as a directory
|
|
2990
|
+
# and create a default filename based on timestamp
|
|
2991
|
+
if not os.path.splitext(file_output_path)[1]:
|
|
2992
|
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
|
2993
|
+
filename = f"artifact_{timestamp}{file_extension}"
|
|
2994
|
+
full_path = os.path.join(file_output_path, filename)
|
|
2995
|
+
else:
|
|
2996
|
+
full_path = file_output_path
|
|
2997
|
+
|
|
2998
|
+
# Create the directory if it doesn't exist
|
|
2999
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
3000
|
+
|
|
3001
|
+
logger.info(f"Creating artifact for file: {full_path}")
|
|
3002
|
+
artifact = Artifact(
|
|
3003
|
+
file_path=full_path,
|
|
3004
|
+
file_type=file_extension,
|
|
3005
|
+
contents=text,
|
|
3006
|
+
edit_count=0,
|
|
3007
|
+
)
|
|
3008
|
+
|
|
3009
|
+
logger.info(
|
|
3010
|
+
f"Saving artifact with extension: {file_extension}"
|
|
3011
|
+
)
|
|
3012
|
+
artifact.save_as(file_extension)
|
|
3013
|
+
logger.success(
|
|
3014
|
+
f"Successfully saved artifact to {full_path}"
|
|
3015
|
+
)
|
|
3016
|
+
|
|
3017
|
+
except ValueError as e:
|
|
3018
|
+
logger.error(
|
|
3019
|
+
f"Invalid input values for artifact: {str(e)}"
|
|
3020
|
+
)
|
|
3021
|
+
raise
|
|
3022
|
+
except IOError as e:
|
|
3023
|
+
logger.error(f"Error saving artifact to file: {str(e)}")
|
|
3024
|
+
raise
|
|
3025
|
+
except Exception as e:
|
|
3026
|
+
logger.error(
|
|
3027
|
+
f"Unexpected error handling artifact: {str(e)}"
|
|
3028
|
+
)
|
|
3029
|
+
raise
|
|
3030
|
+
|
|
3031
|
+
def showcase_config(self):
|
|
3032
|
+
|
|
3033
|
+
# Convert all values in config_dict to concise string representations
|
|
3034
|
+
config_dict = self.to_dict()
|
|
3035
|
+
for key, value in config_dict.items():
|
|
3036
|
+
if isinstance(value, list):
|
|
3037
|
+
# Format list as a comma-separated string
|
|
3038
|
+
config_dict[key] = ", ".join(
|
|
3039
|
+
str(item) for item in value
|
|
3040
|
+
)
|
|
3041
|
+
elif isinstance(value, dict):
|
|
3042
|
+
# Format dict as key-value pairs in a single string
|
|
3043
|
+
config_dict[key] = ", ".join(
|
|
3044
|
+
f"{k}: {v}" for k, v in value.items()
|
|
3045
|
+
)
|
|
3046
|
+
else:
|
|
3047
|
+
# Ensure any non-iterable value is a string
|
|
3048
|
+
config_dict[key] = str(value)
|
|
3049
|
+
|
|
3050
|
+
return formatter.print_table(
|
|
3051
|
+
f"Agent: {self.agent_name} Configuration", config_dict
|
|
3052
|
+
)
|
|
3053
|
+
|
|
3054
|
+
def talk_to(
|
|
3055
|
+
self, agent: Any, task: str, img: str = None, *args, **kwargs
|
|
3056
|
+
) -> Any:
|
|
3057
|
+
"""
|
|
3058
|
+
Talk to another agent.
|
|
3059
|
+
"""
|
|
3060
|
+
# return agent.run(f"{agent.agent_name}: {task}", img, *args, **kwargs)
|
|
3061
|
+
output = self.run(
|
|
3062
|
+
f"{self.agent_name}: {task}", img, *args, **kwargs
|
|
3063
|
+
)
|
|
3064
|
+
|
|
3065
|
+
return agent.run(
|
|
3066
|
+
task=f"From {self.agent_name}: Message: {output}",
|
|
3067
|
+
img=img,
|
|
3068
|
+
*args,
|
|
3069
|
+
**kwargs,
|
|
3070
|
+
)
|
|
3071
|
+
|
|
3072
|
+
def talk_to_multiple_agents(
|
|
3073
|
+
self,
|
|
3074
|
+
agents: List[Union[Any, Callable]],
|
|
3075
|
+
task: str,
|
|
3076
|
+
*args,
|
|
3077
|
+
**kwargs,
|
|
3078
|
+
) -> Any:
|
|
3079
|
+
"""
|
|
3080
|
+
Talk to multiple agents.
|
|
3081
|
+
"""
|
|
3082
|
+
# o# Use the existing executor from self.executor or create a new one if needed
|
|
3083
|
+
with ThreadPoolExecutor() as executor:
|
|
3084
|
+
# Create futures for each agent conversation
|
|
3085
|
+
futures = [
|
|
3086
|
+
executor.submit(
|
|
3087
|
+
self.talk_to, agent, task, *args, **kwargs
|
|
3088
|
+
)
|
|
3089
|
+
for agent in agents
|
|
3090
|
+
]
|
|
3091
|
+
|
|
3092
|
+
# Wait for all futures to complete and collect results
|
|
3093
|
+
outputs = []
|
|
3094
|
+
for future in futures:
|
|
3095
|
+
try:
|
|
3096
|
+
result = future.result()
|
|
3097
|
+
outputs.append(result)
|
|
3098
|
+
except Exception as e:
|
|
3099
|
+
logger.error(f"Error in agent communication: {e}")
|
|
3100
|
+
outputs.append(
|
|
3101
|
+
None
|
|
3102
|
+
) # or handle error case as needed
|
|
3103
|
+
|
|
3104
|
+
return outputs
|
|
3105
|
+
|
|
3106
|
+
def get_agent_role(self) -> str:
|
|
3107
|
+
"""
|
|
3108
|
+
Get the role of the agent.
|
|
3109
|
+
"""
|
|
3110
|
+
return self.role
|
|
3111
|
+
|
|
3112
|
+
def pretty_print(self, response: str, loop_count: int):
|
|
3113
|
+
"""Print the response in a formatted panel"""
|
|
3114
|
+
# Handle None response
|
|
3115
|
+
if response is None:
|
|
3116
|
+
response = "No response generated"
|
|
3117
|
+
|
|
3118
|
+
if self.streaming_on:
|
|
3119
|
+
pass
|
|
3120
|
+
elif self.stream:
|
|
3121
|
+
pass
|
|
3122
|
+
|
|
3123
|
+
if self.print_on:
|
|
3124
|
+
formatter.print_panel(
|
|
3125
|
+
response,
|
|
3126
|
+
f"Agent Name {self.agent_name} [Max Loops: {loop_count} ]",
|
|
3127
|
+
)
|
|
3128
|
+
|
|
3129
|
+
def parse_llm_output(self, response: Any):
|
|
3130
|
+
"""Parse and standardize the output from the LLM.
|
|
3131
|
+
|
|
3132
|
+
Args:
|
|
3133
|
+
response (Any): The response from the LLM in any format
|
|
3134
|
+
|
|
3135
|
+
Returns:
|
|
3136
|
+
str: Standardized string output
|
|
3137
|
+
|
|
3138
|
+
Raises:
|
|
3139
|
+
ValueError: If the response format is unexpected and can't be handled
|
|
3140
|
+
"""
|
|
3141
|
+
try:
|
|
3142
|
+
|
|
3143
|
+
if isinstance(response, dict):
|
|
3144
|
+
if "choices" in response:
|
|
3145
|
+
return response["choices"][0]["message"][
|
|
3146
|
+
"content"
|
|
3147
|
+
]
|
|
3148
|
+
return json.dumps(
|
|
3149
|
+
response
|
|
3150
|
+
) # Convert other dicts to string
|
|
3151
|
+
|
|
3152
|
+
elif isinstance(response, BaseModel):
|
|
3153
|
+
response = response.model_dump()
|
|
3154
|
+
|
|
3155
|
+
# Handle List[BaseModel] responses
|
|
3156
|
+
elif (
|
|
3157
|
+
isinstance(response, list)
|
|
3158
|
+
and response
|
|
3159
|
+
and isinstance(response[0], BaseModel)
|
|
3160
|
+
):
|
|
3161
|
+
return [item.model_dump() for item in response]
|
|
3162
|
+
|
|
3163
|
+
return response
|
|
3164
|
+
|
|
3165
|
+
except AgentChatCompletionResponse as e:
|
|
3166
|
+
logger.error(f"Error parsing LLM output: {e}")
|
|
3167
|
+
raise ValueError(
|
|
3168
|
+
f"Failed to parse LLM output: {type(response)}"
|
|
3169
|
+
)
|
|
3170
|
+
|
|
3171
|
+
def sentiment_and_evaluator(self, response: str):
|
|
3172
|
+
if self.evaluator:
|
|
3173
|
+
logger.info("Evaluating response...")
|
|
3174
|
+
|
|
3175
|
+
evaluated_response = self.evaluator(response)
|
|
3176
|
+
self.short_memory.add(
|
|
3177
|
+
role="Evaluator",
|
|
3178
|
+
content=evaluated_response,
|
|
3179
|
+
)
|
|
3180
|
+
|
|
3181
|
+
# Sentiment analysis
|
|
3182
|
+
if self.sentiment_analyzer:
|
|
3183
|
+
logger.info("Analyzing sentiment...")
|
|
3184
|
+
self.sentiment_analysis_handler(response)
|
|
3185
|
+
|
|
3186
|
+
def output_cleaner_op(self, response: str):
|
|
3187
|
+
# Apply the cleaner function to the response
|
|
3188
|
+
if self.output_cleaner is not None:
|
|
3189
|
+
logger.info("Applying output cleaner to response.")
|
|
3190
|
+
|
|
3191
|
+
response = self.output_cleaner(response)
|
|
3192
|
+
|
|
3193
|
+
logger.info(f"Response after output cleaner: {response}")
|
|
3194
|
+
|
|
3195
|
+
self.short_memory.add(
|
|
3196
|
+
role="Output Cleaner",
|
|
3197
|
+
content=response,
|
|
3198
|
+
)
|
|
3199
|
+
|
|
3200
|
+
def mcp_tool_handling(
|
|
3201
|
+
self, response: any, current_loop: Optional[int] = 0
|
|
3202
|
+
):
|
|
3203
|
+
try:
|
|
3204
|
+
|
|
3205
|
+
if exists(self.mcp_url):
|
|
3206
|
+
# Execute the tool call
|
|
3207
|
+
tool_response = asyncio.run(
|
|
3208
|
+
execute_tool_call_simple(
|
|
3209
|
+
response=response,
|
|
3210
|
+
server_path=self.mcp_url,
|
|
3211
|
+
)
|
|
3212
|
+
)
|
|
3213
|
+
elif exists(self.mcp_config):
|
|
3214
|
+
# Execute the tool call
|
|
3215
|
+
tool_response = asyncio.run(
|
|
3216
|
+
execute_tool_call_simple(
|
|
3217
|
+
response=response,
|
|
3218
|
+
connection=self.mcp_config,
|
|
3219
|
+
)
|
|
3220
|
+
)
|
|
3221
|
+
elif exists(self.mcp_urls):
|
|
3222
|
+
tool_response = execute_multiple_tools_on_multiple_mcp_servers_sync(
|
|
3223
|
+
responses=response,
|
|
3224
|
+
urls=self.mcp_urls,
|
|
3225
|
+
output_type="json",
|
|
3226
|
+
)
|
|
3227
|
+
# tool_response = format_data_structure(tool_response)
|
|
3228
|
+
|
|
3229
|
+
# print(f"Multiple MCP Tool Response: {tool_response}")
|
|
3230
|
+
else:
|
|
3231
|
+
raise AgentMCPConnectionError(
|
|
3232
|
+
"mcp_url must be either a string URL or MCPConnection object"
|
|
3233
|
+
)
|
|
3234
|
+
|
|
3235
|
+
# Get the text content from the tool response
|
|
3236
|
+
# execute_tool_call_simple returns a string directly, not an object with content attribute
|
|
3237
|
+
text_content = f"MCP Tool Response: \n\n {json.dumps(tool_response, indent=2, sort_keys=True)}"
|
|
3238
|
+
|
|
3239
|
+
if self.print_on is True:
|
|
3240
|
+
formatter.print_panel(
|
|
3241
|
+
content=text_content,
|
|
3242
|
+
title="MCP Tool Response: 🛠️",
|
|
3243
|
+
style="green",
|
|
3244
|
+
)
|
|
3245
|
+
|
|
3246
|
+
# Add to the memory
|
|
3247
|
+
self.short_memory.add(
|
|
3248
|
+
role="Tool Executor",
|
|
3249
|
+
content=text_content,
|
|
3250
|
+
)
|
|
3251
|
+
|
|
3252
|
+
# Create a temporary LLM instance without tools for the follow-up call
|
|
3253
|
+
try:
|
|
3254
|
+
temp_llm = self.temp_llm_instance_for_tool_summary()
|
|
3255
|
+
|
|
3256
|
+
summary = temp_llm.run(
|
|
3257
|
+
task=self.short_memory.get_str()
|
|
3258
|
+
)
|
|
3259
|
+
except Exception as e:
|
|
3260
|
+
logger.error(
|
|
3261
|
+
f"Error calling LLM after MCP tool execution: {e}"
|
|
3262
|
+
)
|
|
3263
|
+
# Fallback: provide a default summary
|
|
3264
|
+
summary = "I successfully executed the MCP tool and retrieved the information above."
|
|
3265
|
+
|
|
3266
|
+
if self.print_on is True:
|
|
3267
|
+
self.pretty_print(summary, loop_count=current_loop)
|
|
3268
|
+
|
|
3269
|
+
# Add to the memory
|
|
3270
|
+
self.short_memory.add(
|
|
3271
|
+
role=self.agent_name, content=summary
|
|
3272
|
+
)
|
|
3273
|
+
except AgentMCPToolError as e:
|
|
3274
|
+
logger.error(f"Error in MCP tool: {e}")
|
|
3275
|
+
raise e
|
|
3276
|
+
|
|
3277
|
+
def temp_llm_instance_for_tool_summary(self):
|
|
3278
|
+
return LiteLLM(
|
|
3279
|
+
model_name=self.model_name,
|
|
3280
|
+
temperature=self.temperature,
|
|
3281
|
+
max_tokens=self.max_tokens,
|
|
3282
|
+
system_prompt=self.system_prompt,
|
|
3283
|
+
stream=False, # Always disable streaming for tool summaries
|
|
3284
|
+
tools_list_dictionary=None,
|
|
3285
|
+
parallel_tool_calls=False,
|
|
3286
|
+
base_url=self.llm_base_url,
|
|
3287
|
+
api_key=self.llm_api_key,
|
|
3288
|
+
)
|
|
3289
|
+
|
|
3290
|
+
def get_available_models(self) -> List[str]:
|
|
3291
|
+
"""
|
|
3292
|
+
Get the list of available models including primary and fallback models.
|
|
3293
|
+
|
|
3294
|
+
Returns:
|
|
3295
|
+
List[str]: List of model names in order of preference
|
|
3296
|
+
"""
|
|
3297
|
+
models = []
|
|
3298
|
+
|
|
3299
|
+
# If fallback_models is specified, use it as the primary list
|
|
3300
|
+
if self.fallback_models:
|
|
3301
|
+
models = self.fallback_models.copy()
|
|
3302
|
+
else:
|
|
3303
|
+
# Otherwise, build the list from individual parameters
|
|
3304
|
+
if self.model_name:
|
|
3305
|
+
models.append(self.model_name)
|
|
3306
|
+
if (
|
|
3307
|
+
self.fallback_model_name
|
|
3308
|
+
and self.fallback_model_name not in models
|
|
3309
|
+
):
|
|
3310
|
+
models.append(self.fallback_model_name)
|
|
3311
|
+
|
|
3312
|
+
return models
|
|
3313
|
+
|
|
3314
|
+
def get_current_model(self) -> str:
|
|
3315
|
+
"""
|
|
3316
|
+
Get the current model being used.
|
|
3317
|
+
|
|
3318
|
+
Returns:
|
|
3319
|
+
str: Current model name
|
|
3320
|
+
"""
|
|
3321
|
+
available_models = self.get_available_models()
|
|
3322
|
+
if self.current_model_index < len(available_models):
|
|
3323
|
+
return available_models[self.current_model_index]
|
|
3324
|
+
return (
|
|
3325
|
+
available_models[0] if available_models else "gpt-4o-mini"
|
|
3326
|
+
)
|
|
3327
|
+
|
|
3328
|
+
def switch_to_next_model(self) -> bool:
|
|
3329
|
+
"""
|
|
3330
|
+
Switch to the next available model in the fallback list.
|
|
3331
|
+
|
|
3332
|
+
Returns:
|
|
3333
|
+
bool: True if successfully switched to next model, False if no more models available
|
|
3334
|
+
"""
|
|
3335
|
+
available_models = self.get_available_models()
|
|
3336
|
+
|
|
3337
|
+
if self.current_model_index + 1 < len(available_models):
|
|
3338
|
+
previous_model = (
|
|
3339
|
+
available_models[self.current_model_index]
|
|
3340
|
+
if self.current_model_index < len(available_models)
|
|
3341
|
+
else "Unknown"
|
|
3342
|
+
)
|
|
3343
|
+
self.current_model_index += 1
|
|
3344
|
+
new_model = available_models[self.current_model_index]
|
|
3345
|
+
|
|
3346
|
+
# Always log model switches
|
|
3347
|
+
logger.warning(
|
|
3348
|
+
f"🔄 [MODEL SWITCH] Agent '{self.agent_name}' switching from '{previous_model}' to fallback model: '{new_model}' "
|
|
3349
|
+
f"(attempt {self.current_model_index + 1}/{len(available_models)})"
|
|
3350
|
+
)
|
|
3351
|
+
|
|
3352
|
+
# Update the model name and reinitialize LLM
|
|
3353
|
+
self.model_name = new_model
|
|
3354
|
+
self.llm = self.llm_handling()
|
|
3355
|
+
|
|
3356
|
+
return True
|
|
3357
|
+
else:
|
|
3358
|
+
logger.error(
|
|
3359
|
+
f"❌ [NO MORE MODELS] Agent '{self.agent_name}' has exhausted all available models. "
|
|
3360
|
+
f"Tried {len(available_models)} models: {available_models}"
|
|
3361
|
+
)
|
|
3362
|
+
return False
|
|
3363
|
+
|
|
3364
|
+
def reset_model_index(self) -> None:
|
|
3365
|
+
"""Reset the model index to use the primary model."""
|
|
3366
|
+
self.current_model_index = 0
|
|
3367
|
+
available_models = self.get_available_models()
|
|
3368
|
+
if available_models:
|
|
3369
|
+
self.model_name = available_models[0]
|
|
3370
|
+
self.llm = self.llm_handling()
|
|
3371
|
+
|
|
3372
|
+
def is_fallback_available(self) -> bool:
|
|
3373
|
+
"""
|
|
3374
|
+
Check if fallback models are available.
|
|
3375
|
+
|
|
3376
|
+
Returns:
|
|
3377
|
+
bool: True if fallback models are configured
|
|
3378
|
+
"""
|
|
3379
|
+
available_models = self.get_available_models()
|
|
3380
|
+
return len(available_models) > 1
|
|
3381
|
+
|
|
3382
|
+
def execute_tools(self, response: any, loop_count: int):
|
|
3383
|
+
# Handle None response gracefully
|
|
3384
|
+
if response is None:
|
|
3385
|
+
logger.warning(
|
|
3386
|
+
f"Cannot execute tools with None response in loop {loop_count}. "
|
|
3387
|
+
"This may indicate the LLM did not return a valid response."
|
|
3388
|
+
)
|
|
3389
|
+
return
|
|
3390
|
+
|
|
3391
|
+
try:
|
|
3392
|
+
output = self.tool_struct.execute_function_calls_from_api_response(
|
|
3393
|
+
response
|
|
3394
|
+
)
|
|
3395
|
+
except Exception as e:
|
|
3396
|
+
# Retry the tool call
|
|
3397
|
+
output = self.tool_struct.execute_function_calls_from_api_response(
|
|
3398
|
+
response
|
|
3399
|
+
)
|
|
3400
|
+
|
|
3401
|
+
if output is None:
|
|
3402
|
+
logger.error(f"Error executing tools: {e}")
|
|
3403
|
+
raise e
|
|
3404
|
+
|
|
3405
|
+
self.short_memory.add(
|
|
3406
|
+
role="Tool Executor",
|
|
3407
|
+
content=format_data_structure(output),
|
|
3408
|
+
)
|
|
3409
|
+
|
|
3410
|
+
if self.print_on is True:
|
|
3411
|
+
if self.show_tool_execution_output is True:
|
|
3412
|
+
|
|
3413
|
+
self.pretty_print(
|
|
3414
|
+
f"Tool Executed Successfully [{time.strftime('%H:%M:%S')}] \n\nTool Output: {format_data_structure(output)}",
|
|
3415
|
+
loop_count,
|
|
3416
|
+
)
|
|
3417
|
+
else:
|
|
3418
|
+
self.pretty_print(
|
|
3419
|
+
f"Tool Executed Successfully [{time.strftime('%H:%M:%S')}]",
|
|
3420
|
+
loop_count,
|
|
3421
|
+
)
|
|
3422
|
+
|
|
3423
|
+
# Now run the LLM again without tools - create a temporary LLM instance
|
|
3424
|
+
# instead of modifying the cached one
|
|
3425
|
+
# Create a temporary LLM instance without tools for the follow-up call
|
|
3426
|
+
if self.tool_call_summary is True:
|
|
3427
|
+
temp_llm = self.temp_llm_instance_for_tool_summary()
|
|
3428
|
+
|
|
3429
|
+
tool_response = temp_llm.run(
|
|
3430
|
+
f"""
|
|
3431
|
+
Please analyze and summarize the following tool execution output in a clear and concise way.
|
|
3432
|
+
Focus on the key information and insights that would be most relevant to the user's original request.
|
|
3433
|
+
If there are any errors or issues, highlight them prominently.
|
|
3434
|
+
|
|
3435
|
+
Tool Output:
|
|
3436
|
+
{output}
|
|
3437
|
+
"""
|
|
3438
|
+
)
|
|
3439
|
+
|
|
3440
|
+
self.short_memory.add(
|
|
3441
|
+
role=self.agent_name,
|
|
3442
|
+
content=tool_response,
|
|
3443
|
+
)
|
|
3444
|
+
|
|
3445
|
+
if self.print_on is True:
|
|
3446
|
+
self.pretty_print(
|
|
3447
|
+
tool_response,
|
|
3448
|
+
loop_count,
|
|
3449
|
+
)
|
|
3450
|
+
|
|
3451
|
+
def list_output_types(self):
|
|
3452
|
+
return OutputType
|
|
3453
|
+
|
|
3454
|
+
def run_multiple_images(
|
|
3455
|
+
self, task: str, imgs: List[str], *args, **kwargs
|
|
3456
|
+
):
|
|
3457
|
+
"""
|
|
3458
|
+
Run the agent with multiple images using concurrent processing.
|
|
3459
|
+
|
|
3460
|
+
Args:
|
|
3461
|
+
task (str): The task to be performed on each image.
|
|
3462
|
+
imgs (List[str]): List of image paths or URLs to process.
|
|
3463
|
+
*args: Additional positional arguments to pass to the agent's run method.
|
|
3464
|
+
**kwargs: Additional keyword arguments to pass to the agent's run method.
|
|
3465
|
+
|
|
3466
|
+
Returns:
|
|
3467
|
+
List[Any]: A list of outputs generated for each image in the same order as the input images.
|
|
3468
|
+
|
|
3469
|
+
Examples:
|
|
3470
|
+
>>> agent = Agent()
|
|
3471
|
+
>>> outputs = agent.run_multiple_images(
|
|
3472
|
+
... task="Describe what you see in this image",
|
|
3473
|
+
... imgs=["image1.jpg", "image2.png", "image3.jpeg"]
|
|
3474
|
+
... )
|
|
3475
|
+
>>> print(f"Processed {len(outputs)} images")
|
|
3476
|
+
Processed 3 images
|
|
3477
|
+
|
|
3478
|
+
Raises:
|
|
3479
|
+
Exception: If an error occurs while processing any of the images.
|
|
3480
|
+
"""
|
|
3481
|
+
# Calculate number of workers as 95% of available CPU cores
|
|
3482
|
+
cpu_count = os.cpu_count()
|
|
3483
|
+
max_workers = max(1, int(cpu_count * 0.95))
|
|
3484
|
+
|
|
3485
|
+
# Use ThreadPoolExecutor for concurrent processing
|
|
3486
|
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
3487
|
+
# Submit all image processing tasks
|
|
3488
|
+
future_to_img = {
|
|
3489
|
+
executor.submit(
|
|
3490
|
+
self.run, task=task, img=img, *args, **kwargs
|
|
3491
|
+
): img
|
|
3492
|
+
for img in imgs
|
|
3493
|
+
}
|
|
3494
|
+
|
|
3495
|
+
# Collect results in order
|
|
3496
|
+
outputs = []
|
|
3497
|
+
for future in future_to_img:
|
|
3498
|
+
try:
|
|
3499
|
+
output = future.result()
|
|
3500
|
+
outputs.append(output)
|
|
3501
|
+
except Exception as e:
|
|
3502
|
+
logger.error(f"Error processing image: {e}")
|
|
3503
|
+
outputs.append(
|
|
3504
|
+
None
|
|
3505
|
+
) # or raise the exception based on your preference
|
|
3506
|
+
|
|
3507
|
+
# Combine the outputs into a single string if summarization is enabled
|
|
3508
|
+
if self.summarize_multiple_images is True:
|
|
3509
|
+
output = "\n".join(outputs)
|
|
3510
|
+
|
|
3511
|
+
prompt = f"""
|
|
3512
|
+
You have already analyzed {len(outputs)} images and provided detailed descriptions for each one.
|
|
3513
|
+
Now, based on your previous analysis of these images, create a comprehensive report that:
|
|
3514
|
+
|
|
3515
|
+
1. Synthesizes the key findings across all images
|
|
3516
|
+
2. Identifies common themes, patterns, or relationships between the images
|
|
3517
|
+
3. Provides an overall summary that captures the most important insights
|
|
3518
|
+
4. Highlights any notable differences or contrasts between the images
|
|
3519
|
+
|
|
3520
|
+
Here are your previous analyses of the images:
|
|
3521
|
+
{output}
|
|
3522
|
+
|
|
3523
|
+
Please create a well-structured report that brings together your insights from all {len(outputs)} images.
|
|
3524
|
+
"""
|
|
3525
|
+
|
|
3526
|
+
outputs = self.run(task=prompt, *args, **kwargs)
|
|
3527
|
+
|
|
3528
|
+
return outputs
|
|
3529
|
+
|
|
3530
|
+
def continuous_run_with_answer(
|
|
3531
|
+
self,
|
|
3532
|
+
task: str,
|
|
3533
|
+
img: Optional[str] = None,
|
|
3534
|
+
correct_answer: str = None,
|
|
3535
|
+
max_attempts: int = 10,
|
|
3536
|
+
):
|
|
3537
|
+
"""
|
|
3538
|
+
Run the agent with the task until the correct answer is provided.
|
|
3539
|
+
|
|
3540
|
+
Args:
|
|
3541
|
+
task (str): The task to be performed
|
|
3542
|
+
correct_answer (str): The correct answer that must be found in the response
|
|
3543
|
+
max_attempts (int): Maximum number of attempts before giving up (default: 10)
|
|
3544
|
+
|
|
3545
|
+
Returns:
|
|
3546
|
+
str: The response containing the correct answer
|
|
3547
|
+
|
|
3548
|
+
Raises:
|
|
3549
|
+
Exception: If max_attempts is reached without finding the correct answer
|
|
3550
|
+
"""
|
|
3551
|
+
attempts = 0
|
|
3552
|
+
|
|
3553
|
+
while attempts < max_attempts:
|
|
3554
|
+
attempts += 1
|
|
3555
|
+
|
|
3556
|
+
if self.verbose:
|
|
3557
|
+
logger.info(
|
|
3558
|
+
f"Attempt {attempts}/{max_attempts} to find correct answer"
|
|
3559
|
+
)
|
|
3560
|
+
|
|
3561
|
+
response = self._run(task=task, img=img)
|
|
3562
|
+
|
|
3563
|
+
# Check if the correct answer is in the response (case-insensitive)
|
|
3564
|
+
if correct_answer.lower() in response.lower():
|
|
3565
|
+
if self.verbose:
|
|
3566
|
+
logger.info(
|
|
3567
|
+
f"Correct answer found on attempt {attempts}"
|
|
3568
|
+
)
|
|
3569
|
+
return response
|
|
3570
|
+
else:
|
|
3571
|
+
# Add feedback to help guide the agent
|
|
3572
|
+
feedback = "Your previous response was incorrect. Think carefully about the question and ensure your response directly addresses what was asked."
|
|
3573
|
+
self.short_memory.add(role="User", content=feedback)
|
|
3574
|
+
|
|
3575
|
+
if self.verbose:
|
|
3576
|
+
logger.info(
|
|
3577
|
+
f"Correct answer not found. Expected: '{correct_answer}'"
|
|
3578
|
+
)
|
|
3579
|
+
|
|
3580
|
+
# If we reach here, we've exceeded max_attempts
|
|
3581
|
+
raise Exception(
|
|
3582
|
+
f"Failed to find correct answer '{correct_answer}' after {max_attempts} attempts"
|
|
3583
|
+
)
|
|
3584
|
+
|
|
3585
|
+
def tool_execution_retry(self, response: any, loop_count: int):
|
|
3586
|
+
"""
|
|
3587
|
+
Execute tools with retry logic for handling failures.
|
|
3588
|
+
|
|
3589
|
+
This method attempts to execute tools based on the LLM response. If the response
|
|
3590
|
+
is None, it logs a warning and skips execution. If an exception occurs during
|
|
3591
|
+
tool execution, it logs the error with full traceback and retries the operation
|
|
3592
|
+
using the configured retry attempts.
|
|
3593
|
+
|
|
3594
|
+
Args:
|
|
3595
|
+
response (any): The response from the LLM that may contain tool calls to execute.
|
|
3596
|
+
Can be None if the LLM failed to provide a valid response.
|
|
3597
|
+
loop_count (int): The current iteration loop number for logging and debugging purposes.
|
|
3598
|
+
|
|
3599
|
+
Returns:
|
|
3600
|
+
None
|
|
3601
|
+
|
|
3602
|
+
Raises:
|
|
3603
|
+
Exception: Re-raises any exception that occurs during tool execution after
|
|
3604
|
+
all retry attempts have been exhausted.
|
|
3605
|
+
|
|
3606
|
+
Note:
|
|
3607
|
+
- Uses self.tool_retry_attempts for the maximum number of retry attempts
|
|
3608
|
+
- Logs detailed error information including agent name and loop count
|
|
3609
|
+
- Skips execution gracefully if response is None
|
|
3610
|
+
"""
|
|
3611
|
+
try:
|
|
3612
|
+
if response is not None:
|
|
3613
|
+
self.execute_tools(
|
|
3614
|
+
response=response,
|
|
3615
|
+
loop_count=loop_count,
|
|
3616
|
+
)
|
|
3617
|
+
else:
|
|
3618
|
+
logger.warning(
|
|
3619
|
+
f"Agent '{self.agent_name}' received None response from LLM in loop {loop_count}. "
|
|
3620
|
+
f"This may indicate an issue with the model or prompt. Skipping tool execution."
|
|
3621
|
+
)
|
|
3622
|
+
except AgentToolExecutionError as e:
|
|
3623
|
+
logger.error(
|
|
3624
|
+
f"Agent '{self.agent_name}' encountered error during tool execution in loop {loop_count}: {str(e)}. "
|
|
3625
|
+
f"Full traceback: {traceback.format_exc()}. "
|
|
3626
|
+
f"Attempting to retry tool execution with 3 attempts"
|
|
3627
|
+
)
|