@framers/agentos 0.1.0
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.
- package/LICENSE +98 -0
- package/README.md +576 -0
- package/dist/api/AgentOS.d.ts +451 -0
- package/dist/api/AgentOS.d.ts.map +1 -0
- package/dist/api/AgentOS.js +1157 -0
- package/dist/api/AgentOS.js.map +1 -0
- package/dist/api/AgentOSOrchestrator.d.ts +157 -0
- package/dist/api/AgentOSOrchestrator.d.ts.map +1 -0
- package/dist/api/AgentOSOrchestrator.js +679 -0
- package/dist/api/AgentOSOrchestrator.js.map +1 -0
- package/dist/api/interfaces/IAgentOS.d.ts +138 -0
- package/dist/api/interfaces/IAgentOS.d.ts.map +1 -0
- package/dist/api/interfaces/IAgentOS.js +11 -0
- package/dist/api/interfaces/IAgentOS.js.map +1 -0
- package/dist/api/interfaces/IUnifiedAgent.d.ts +126 -0
- package/dist/api/interfaces/IUnifiedAgent.d.ts.map +1 -0
- package/dist/api/interfaces/IUnifiedAgent.js +3 -0
- package/dist/api/interfaces/IUnifiedAgent.js.map +1 -0
- package/dist/api/types/AgentOSInput.d.ts +114 -0
- package/dist/api/types/AgentOSInput.d.ts.map +1 -0
- package/dist/api/types/AgentOSInput.js +13 -0
- package/dist/api/types/AgentOSInput.js.map +1 -0
- package/dist/api/types/AgentOSResponse.d.ts +170 -0
- package/dist/api/types/AgentOSResponse.d.ts.map +1 -0
- package/dist/api/types/AgentOSResponse.js +25 -0
- package/dist/api/types/AgentOSResponse.js.map +1 -0
- package/dist/cognitive_substrate/GMI.d.ts +148 -0
- package/dist/cognitive_substrate/GMI.d.ts.map +1 -0
- package/dist/cognitive_substrate/GMI.js +1003 -0
- package/dist/cognitive_substrate/GMI.js.map +1 -0
- package/dist/cognitive_substrate/GMIManager.d.ts +98 -0
- package/dist/cognitive_substrate/GMIManager.d.ts.map +1 -0
- package/dist/cognitive_substrate/GMIManager.js +517 -0
- package/dist/cognitive_substrate/GMIManager.js.map +1 -0
- package/dist/cognitive_substrate/IGMI.d.ts +469 -0
- package/dist/cognitive_substrate/IGMI.d.ts.map +1 -0
- package/dist/cognitive_substrate/IGMI.js +111 -0
- package/dist/cognitive_substrate/IGMI.js.map +1 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.d.ts +139 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.d.ts.map +1 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.js +14 -0
- package/dist/cognitive_substrate/memory/IWorkingMemory.js.map +1 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.d.ts +143 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.d.ts.map +1 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.js +186 -0
- package/dist/cognitive_substrate/memory/InMemoryWorkingMemory.js.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.d.ts +33 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.d.ts.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.js +138 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayManager.js.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.d.ts +32 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.d.ts.map +1 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.js +2 -0
- package/dist/cognitive_substrate/persona_overlays/PersonaOverlayTypes.js.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.d.ts +336 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.js +8 -0
- package/dist/cognitive_substrate/personas/IPersonaDefinition.js.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.d.ts +78 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.js +9 -0
- package/dist/cognitive_substrate/personas/IPersonaLoader.js.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.d.ts +60 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.js +138 -0
- package/dist/cognitive_substrate/personas/PersonaLoader.js.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.d.ts +139 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.js +277 -0
- package/dist/cognitive_substrate/personas/PersonaValidation.js.map +1 -0
- package/dist/cognitive_substrate/personas/definitions/atlas_systems_architect.json +29 -0
- package/dist/cognitive_substrate/personas/definitions/default_assistant_persona.json +346 -0
- package/dist/cognitive_substrate/personas/definitions/default_free_assistant.json +13 -0
- package/dist/cognitive_substrate/personas/definitions/index.d.ts +14 -0
- package/dist/cognitive_substrate/personas/definitions/index.d.ts.map +1 -0
- package/dist/cognitive_substrate/personas/definitions/index.js +35 -0
- package/dist/cognitive_substrate/personas/definitions/index.js.map +1 -0
- package/dist/cognitive_substrate/personas/definitions/nerf_generalist.json +11 -0
- package/dist/cognitive_substrate/personas/definitions/v_researcher.json +11 -0
- package/dist/config/AgentOSConfig.d.ts +74 -0
- package/dist/config/AgentOSConfig.d.ts.map +1 -0
- package/dist/config/AgentOSConfig.js +399 -0
- package/dist/config/AgentOSConfig.js.map +1 -0
- package/dist/config/EmbeddingManagerConfiguration.d.ts +190 -0
- package/dist/config/EmbeddingManagerConfiguration.d.ts.map +1 -0
- package/dist/config/EmbeddingManagerConfiguration.js +16 -0
- package/dist/config/EmbeddingManagerConfiguration.js.map +1 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.d.ts +165 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.d.ts.map +1 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.js +69 -0
- package/dist/config/MemoryLifecycleManagerConfiguration.js.map +1 -0
- package/dist/config/RetrievalAugmentorConfiguration.d.ts +98 -0
- package/dist/config/RetrievalAugmentorConfiguration.d.ts.map +1 -0
- package/dist/config/RetrievalAugmentorConfiguration.js +47 -0
- package/dist/config/RetrievalAugmentorConfiguration.js.map +1 -0
- package/dist/config/ToolOrchestratorConfig.d.ts +69 -0
- package/dist/config/ToolOrchestratorConfig.d.ts.map +1 -0
- package/dist/config/ToolOrchestratorConfig.js +11 -0
- package/dist/config/ToolOrchestratorConfig.js.map +1 -0
- package/dist/config/VectorStoreConfiguration.d.ts +223 -0
- package/dist/config/VectorStoreConfiguration.d.ts.map +1 -0
- package/dist/config/VectorStoreConfiguration.js +59 -0
- package/dist/config/VectorStoreConfiguration.js.map +1 -0
- package/dist/config/extension-secrets.json +38 -0
- package/dist/config/extensionSecrets.d.ts +13 -0
- package/dist/config/extensionSecrets.d.ts.map +1 -0
- package/dist/config/extensionSecrets.js +24 -0
- package/dist/config/extensionSecrets.js.map +1 -0
- package/dist/core/agency/AgencyMemoryManager.d.ts +300 -0
- package/dist/core/agency/AgencyMemoryManager.d.ts.map +1 -0
- package/dist/core/agency/AgencyMemoryManager.js +657 -0
- package/dist/core/agency/AgencyMemoryManager.js.map +1 -0
- package/dist/core/agency/AgencyRegistry.d.ts +100 -0
- package/dist/core/agency/AgencyRegistry.d.ts.map +1 -0
- package/dist/core/agency/AgencyRegistry.js +209 -0
- package/dist/core/agency/AgencyRegistry.js.map +1 -0
- package/dist/core/agency/AgencyTypes.d.ts +200 -0
- package/dist/core/agency/AgencyTypes.d.ts.map +1 -0
- package/dist/core/agency/AgencyTypes.js +7 -0
- package/dist/core/agency/AgencyTypes.js.map +1 -0
- package/dist/core/agency/AgentCommunicationBus.d.ts +150 -0
- package/dist/core/agency/AgentCommunicationBus.d.ts.map +1 -0
- package/dist/core/agency/AgentCommunicationBus.js +568 -0
- package/dist/core/agency/AgentCommunicationBus.js.map +1 -0
- package/dist/core/agency/IAgentCommunicationBus.d.ts +469 -0
- package/dist/core/agency/IAgentCommunicationBus.d.ts.map +1 -0
- package/dist/core/agency/IAgentCommunicationBus.js +40 -0
- package/dist/core/agency/IAgentCommunicationBus.js.map +1 -0
- package/dist/core/agency/index.d.ts +18 -0
- package/dist/core/agency/index.d.ts.map +1 -0
- package/dist/core/agency/index.js +18 -0
- package/dist/core/agency/index.js.map +1 -0
- package/dist/core/agents/AgentCore.d.ts +385 -0
- package/dist/core/agents/AgentCore.d.ts.map +1 -0
- package/dist/core/agents/AgentCore.js +527 -0
- package/dist/core/agents/AgentCore.js.map +1 -0
- package/dist/core/agents/AgentFactory.d.ts +123 -0
- package/dist/core/agents/AgentFactory.d.ts.map +1 -0
- package/dist/core/agents/AgentFactory.js +232 -0
- package/dist/core/agents/AgentFactory.js.map +1 -0
- package/dist/core/agents/AgentPoolAgent.d.ts +244 -0
- package/dist/core/agents/AgentPoolAgent.d.ts.map +1 -0
- package/dist/core/agents/AgentPoolAgent.js +697 -0
- package/dist/core/agents/AgentPoolAgent.js.map +1 -0
- package/dist/core/agents/AgentPoolConfig.d.ts +191 -0
- package/dist/core/agents/AgentPoolConfig.d.ts.map +1 -0
- package/dist/core/agents/AgentPoolConfig.js +58 -0
- package/dist/core/agents/AgentPoolConfig.js.map +1 -0
- package/dist/core/agents/IAgent.d.ts +226 -0
- package/dist/core/agents/IAgent.d.ts.map +1 -0
- package/dist/core/agents/IAgent.js +14 -0
- package/dist/core/agents/IAgent.js.map +1 -0
- package/dist/core/agents/IAgentFactory.d.ts +137 -0
- package/dist/core/agents/IAgentFactory.d.ts.map +1 -0
- package/dist/core/agents/IAgentFactory.js +13 -0
- package/dist/core/agents/IAgentFactory.js.map +1 -0
- package/dist/core/agents/tools/Tool.d.ts +17 -0
- package/dist/core/agents/tools/Tool.d.ts.map +1 -0
- package/dist/core/agents/tools/Tool.js +8 -0
- package/dist/core/agents/tools/Tool.js.map +1 -0
- package/dist/core/ai_utilities/HybridUtilityAI.d.ts +1 -0
- package/dist/core/ai_utilities/HybridUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/HybridUtilityAI.js +2 -0
- package/dist/core/ai_utilities/HybridUtilityAI.js.map +1 -0
- package/dist/core/ai_utilities/IUtilityAI.d.ts +212 -0
- package/dist/core/ai_utilities/IUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/IUtilityAI.js +11 -0
- package/dist/core/ai_utilities/IUtilityAI.js.map +1 -0
- package/dist/core/ai_utilities/LLMUtilityAI.d.ts +94 -0
- package/dist/core/ai_utilities/LLMUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/LLMUtilityAI.js +434 -0
- package/dist/core/ai_utilities/LLMUtilityAI.js.map +1 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.d.ts +102 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.d.ts.map +1 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.js +617 -0
- package/dist/core/ai_utilities/StatisticalUtilityAI.js.map +1 -0
- package/dist/core/conversation/ConversationContext.d.ts +259 -0
- package/dist/core/conversation/ConversationContext.d.ts.map +1 -0
- package/dist/core/conversation/ConversationContext.js +450 -0
- package/dist/core/conversation/ConversationContext.js.map +1 -0
- package/dist/core/conversation/ConversationManager.d.ts +223 -0
- package/dist/core/conversation/ConversationManager.d.ts.map +1 -0
- package/dist/core/conversation/ConversationManager.js +558 -0
- package/dist/core/conversation/ConversationManager.js.map +1 -0
- package/dist/core/conversation/ConversationMessage.d.ts +184 -0
- package/dist/core/conversation/ConversationMessage.d.ts.map +1 -0
- package/dist/core/conversation/ConversationMessage.js +66 -0
- package/dist/core/conversation/ConversationMessage.js.map +1 -0
- package/dist/core/evaluation/Evaluator.d.ts +28 -0
- package/dist/core/evaluation/Evaluator.d.ts.map +1 -0
- package/dist/core/evaluation/Evaluator.js +490 -0
- package/dist/core/evaluation/Evaluator.js.map +1 -0
- package/dist/core/evaluation/IEvaluator.d.ts +309 -0
- package/dist/core/evaluation/IEvaluator.d.ts.map +1 -0
- package/dist/core/evaluation/IEvaluator.js +12 -0
- package/dist/core/evaluation/IEvaluator.js.map +1 -0
- package/dist/core/evaluation/LLMJudge.d.ts +105 -0
- package/dist/core/evaluation/LLMJudge.d.ts.map +1 -0
- package/dist/core/evaluation/LLMJudge.js +229 -0
- package/dist/core/evaluation/LLMJudge.js.map +1 -0
- package/dist/core/evaluation/index.d.ts +9 -0
- package/dist/core/evaluation/index.d.ts.map +1 -0
- package/dist/core/evaluation/index.js +9 -0
- package/dist/core/evaluation/index.js.map +1 -0
- package/dist/core/guardrails/IGuardrailService.d.ts +142 -0
- package/dist/core/guardrails/IGuardrailService.d.ts.map +1 -0
- package/dist/core/guardrails/IGuardrailService.js +24 -0
- package/dist/core/guardrails/IGuardrailService.js.map +1 -0
- package/dist/core/guardrails/guardrailDispatcher.d.ts +36 -0
- package/dist/core/guardrails/guardrailDispatcher.d.ts.map +1 -0
- package/dist/core/guardrails/guardrailDispatcher.js +240 -0
- package/dist/core/guardrails/guardrailDispatcher.js.map +1 -0
- package/dist/core/hitl/HumanInteractionManager.d.ts +146 -0
- package/dist/core/hitl/HumanInteractionManager.d.ts.map +1 -0
- package/dist/core/hitl/HumanInteractionManager.js +491 -0
- package/dist/core/hitl/HumanInteractionManager.js.map +1 -0
- package/dist/core/hitl/IHumanInteractionManager.d.ts +521 -0
- package/dist/core/hitl/IHumanInteractionManager.d.ts.map +1 -0
- package/dist/core/hitl/IHumanInteractionManager.js +33 -0
- package/dist/core/hitl/IHumanInteractionManager.js.map +1 -0
- package/dist/core/hitl/index.d.ts +17 -0
- package/dist/core/hitl/index.d.ts.map +1 -0
- package/dist/core/hitl/index.js +17 -0
- package/dist/core/hitl/index.js.map +1 -0
- package/dist/core/knowledge/IKnowledgeGraph.d.ts +351 -0
- package/dist/core/knowledge/IKnowledgeGraph.d.ts.map +1 -0
- package/dist/core/knowledge/IKnowledgeGraph.js +10 -0
- package/dist/core/knowledge/IKnowledgeGraph.js.map +1 -0
- package/dist/core/knowledge/KnowledgeGraph.d.ts +93 -0
- package/dist/core/knowledge/KnowledgeGraph.d.ts.map +1 -0
- package/dist/core/knowledge/KnowledgeGraph.js +601 -0
- package/dist/core/knowledge/KnowledgeGraph.js.map +1 -0
- package/dist/core/knowledge/index.d.ts +8 -0
- package/dist/core/knowledge/index.d.ts.map +1 -0
- package/dist/core/knowledge/index.js +8 -0
- package/dist/core/knowledge/index.js.map +1 -0
- package/dist/core/language/LanguageService.d.ts +77 -0
- package/dist/core/language/LanguageService.d.ts.map +1 -0
- package/dist/core/language/LanguageService.js +305 -0
- package/dist/core/language/LanguageService.js.map +1 -0
- package/dist/core/language/index.d.ts +6 -0
- package/dist/core/language/index.d.ts.map +1 -0
- package/dist/core/language/index.js +6 -0
- package/dist/core/language/index.js.map +1 -0
- package/dist/core/language/interfaces.d.ts +168 -0
- package/dist/core/language/interfaces.d.ts.map +1 -0
- package/dist/core/language/interfaces.js +37 -0
- package/dist/core/language/interfaces.js.map +1 -0
- package/dist/core/language/providers/DeepLTranslationProvider.d.ts +16 -0
- package/dist/core/language/providers/DeepLTranslationProvider.d.ts.map +1 -0
- package/dist/core/language/providers/DeepLTranslationProvider.js +28 -0
- package/dist/core/language/providers/DeepLTranslationProvider.js.map +1 -0
- package/dist/core/language/providers/OpenAITranslationProvider.d.ts +17 -0
- package/dist/core/language/providers/OpenAITranslationProvider.d.ts.map +1 -0
- package/dist/core/language/providers/OpenAITranslationProvider.js +34 -0
- package/dist/core/language/providers/OpenAITranslationProvider.js.map +1 -0
- package/dist/core/language/providers/WhisperDetectionProvider.d.ts +16 -0
- package/dist/core/language/providers/WhisperDetectionProvider.d.ts.map +1 -0
- package/dist/core/language/providers/WhisperDetectionProvider.js +15 -0
- package/dist/core/language/providers/WhisperDetectionProvider.js.map +1 -0
- package/dist/core/llm/IPromptEngine.d.ts +627 -0
- package/dist/core/llm/IPromptEngine.d.ts.map +1 -0
- package/dist/core/llm/IPromptEngine.js +81 -0
- package/dist/core/llm/IPromptEngine.js.map +1 -0
- package/dist/core/llm/PromptEngine.d.ts +108 -0
- package/dist/core/llm/PromptEngine.d.ts.map +1 -0
- package/dist/core/llm/PromptEngine.js +872 -0
- package/dist/core/llm/PromptEngine.js.map +1 -0
- package/dist/core/llm/providers/AIModelProviderManager.d.ts +74 -0
- package/dist/core/llm/providers/AIModelProviderManager.d.ts.map +1 -0
- package/dist/core/llm/providers/AIModelProviderManager.js +263 -0
- package/dist/core/llm/providers/AIModelProviderManager.js.map +1 -0
- package/dist/core/llm/providers/IProvider.d.ts +327 -0
- package/dist/core/llm/providers/IProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/IProvider.js +39 -0
- package/dist/core/llm/providers/IProvider.js.map +1 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.d.ts +36 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.js +40 -0
- package/dist/core/llm/providers/errors/OllamaProviderError.js.map +1 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.d.ts +42 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.js +44 -0
- package/dist/core/llm/providers/errors/OpenAIProviderError.js.map +1 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.d.ts +39 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.js +42 -0
- package/dist/core/llm/providers/errors/OpenRouterProviderError.js.map +1 -0
- package/dist/core/llm/providers/errors/ProviderError.d.ts +37 -0
- package/dist/core/llm/providers/errors/ProviderError.d.ts.map +1 -0
- package/dist/core/llm/providers/errors/ProviderError.js +36 -0
- package/dist/core/llm/providers/errors/ProviderError.js.map +1 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.d.ts +80 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.js +473 -0
- package/dist/core/llm/providers/implementations/OllamaProvider.js.map +1 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.d.ts +160 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.js +672 -0
- package/dist/core/llm/providers/implementations/OpenAIProvider.js.map +1 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.d.ts +51 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.d.ts.map +1 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.js +499 -0
- package/dist/core/llm/providers/implementations/OpenRouterProvider.js.map +1 -0
- package/dist/core/llm/routing/IModelRouter.d.ts +129 -0
- package/dist/core/llm/routing/IModelRouter.d.ts.map +1 -0
- package/dist/core/llm/routing/IModelRouter.js +14 -0
- package/dist/core/llm/routing/IModelRouter.js.map +1 -0
- package/dist/core/llm/routing/ModelRouter.d.ts +157 -0
- package/dist/core/llm/routing/ModelRouter.d.ts.map +1 -0
- package/dist/core/llm/routing/ModelRouter.js +190 -0
- package/dist/core/llm/routing/ModelRouter.js.map +1 -0
- package/dist/core/llm/streaming/StreamingBatcher.d.ts +54 -0
- package/dist/core/llm/streaming/StreamingBatcher.d.ts.map +1 -0
- package/dist/core/llm/streaming/StreamingBatcher.js +173 -0
- package/dist/core/llm/streaming/StreamingBatcher.js.map +1 -0
- package/dist/core/llm/streaming/StreamingReconstructor.d.ts +69 -0
- package/dist/core/llm/streaming/StreamingReconstructor.d.ts.map +1 -0
- package/dist/core/llm/streaming/StreamingReconstructor.js +102 -0
- package/dist/core/llm/streaming/StreamingReconstructor.js.map +1 -0
- package/dist/core/marketplace/IMarketplace.d.ts +500 -0
- package/dist/core/marketplace/IMarketplace.d.ts.map +1 -0
- package/dist/core/marketplace/IMarketplace.js +10 -0
- package/dist/core/marketplace/IMarketplace.js.map +1 -0
- package/dist/core/marketplace/Marketplace.d.ts +122 -0
- package/dist/core/marketplace/Marketplace.d.ts.map +1 -0
- package/dist/core/marketplace/Marketplace.js +591 -0
- package/dist/core/marketplace/Marketplace.js.map +1 -0
- package/dist/core/marketplace/index.d.ts +8 -0
- package/dist/core/marketplace/index.d.ts.map +1 -0
- package/dist/core/marketplace/index.js +8 -0
- package/dist/core/marketplace/index.js.map +1 -0
- package/dist/core/observability/ITracer.d.ts +317 -0
- package/dist/core/observability/ITracer.d.ts.map +1 -0
- package/dist/core/observability/ITracer.js +55 -0
- package/dist/core/observability/ITracer.js.map +1 -0
- package/dist/core/observability/Tracer.d.ts +76 -0
- package/dist/core/observability/Tracer.d.ts.map +1 -0
- package/dist/core/observability/Tracer.js +360 -0
- package/dist/core/observability/Tracer.js.map +1 -0
- package/dist/core/observability/index.d.ts +9 -0
- package/dist/core/observability/index.d.ts.map +1 -0
- package/dist/core/observability/index.js +8 -0
- package/dist/core/observability/index.js.map +1 -0
- package/dist/core/orchestration/AgentOrchestrator.d.ts +243 -0
- package/dist/core/orchestration/AgentOrchestrator.d.ts.map +1 -0
- package/dist/core/orchestration/AgentOrchestrator.js +648 -0
- package/dist/core/orchestration/AgentOrchestrator.js.map +1 -0
- package/dist/core/orchestration/IAgentOrchestrator.d.ts +44 -0
- package/dist/core/orchestration/IAgentOrchestrator.d.ts.map +1 -0
- package/dist/core/orchestration/IAgentOrchestrator.js +4 -0
- package/dist/core/orchestration/IAgentOrchestrator.js.map +1 -0
- package/dist/core/orchestration/helpers.d.ts +12 -0
- package/dist/core/orchestration/helpers.d.ts.map +1 -0
- package/dist/core/orchestration/helpers.js +36 -0
- package/dist/core/orchestration/helpers.js.map +1 -0
- package/dist/core/planning/IPlanningEngine.d.ts +524 -0
- package/dist/core/planning/IPlanningEngine.d.ts.map +1 -0
- package/dist/core/planning/IPlanningEngine.js +32 -0
- package/dist/core/planning/IPlanningEngine.js.map +1 -0
- package/dist/core/planning/PlanningEngine.d.ts +161 -0
- package/dist/core/planning/PlanningEngine.d.ts.map +1 -0
- package/dist/core/planning/PlanningEngine.js +783 -0
- package/dist/core/planning/PlanningEngine.js.map +1 -0
- package/dist/core/planning/index.d.ts +25 -0
- package/dist/core/planning/index.d.ts.map +1 -0
- package/dist/core/planning/index.js +25 -0
- package/dist/core/planning/index.js.map +1 -0
- package/dist/core/sandbox/CodeSandbox.d.ts +86 -0
- package/dist/core/sandbox/CodeSandbox.d.ts.map +1 -0
- package/dist/core/sandbox/CodeSandbox.js +475 -0
- package/dist/core/sandbox/CodeSandbox.js.map +1 -0
- package/dist/core/sandbox/ICodeSandbox.d.ts +249 -0
- package/dist/core/sandbox/ICodeSandbox.d.ts.map +1 -0
- package/dist/core/sandbox/ICodeSandbox.js +24 -0
- package/dist/core/sandbox/ICodeSandbox.js.map +1 -0
- package/dist/core/sandbox/index.d.ts +9 -0
- package/dist/core/sandbox/index.d.ts.map +1 -0
- package/dist/core/sandbox/index.js +8 -0
- package/dist/core/sandbox/index.js.map +1 -0
- package/dist/core/storage/IStorageAdapter.d.ts +483 -0
- package/dist/core/storage/IStorageAdapter.d.ts.map +1 -0
- package/dist/core/storage/IStorageAdapter.js +19 -0
- package/dist/core/storage/IStorageAdapter.js.map +1 -0
- package/dist/core/storage/InMemoryStorageAdapter.d.ts +192 -0
- package/dist/core/storage/InMemoryStorageAdapter.d.ts.map +1 -0
- package/dist/core/storage/InMemoryStorageAdapter.js +343 -0
- package/dist/core/storage/InMemoryStorageAdapter.js.map +1 -0
- package/dist/core/storage/SqlStorageAdapter.d.ts +262 -0
- package/dist/core/storage/SqlStorageAdapter.d.ts.map +1 -0
- package/dist/core/storage/SqlStorageAdapter.js +485 -0
- package/dist/core/storage/SqlStorageAdapter.js.map +1 -0
- package/dist/core/storage/index.d.ts +14 -0
- package/dist/core/storage/index.d.ts.map +1 -0
- package/dist/core/storage/index.js +14 -0
- package/dist/core/storage/index.js.map +1 -0
- package/dist/core/streaming/IStreamClient.d.ts +72 -0
- package/dist/core/streaming/IStreamClient.d.ts.map +1 -0
- package/dist/core/streaming/IStreamClient.js +12 -0
- package/dist/core/streaming/IStreamClient.js.map +1 -0
- package/dist/core/streaming/StreamingManager.d.ts +242 -0
- package/dist/core/streaming/StreamingManager.d.ts.map +1 -0
- package/dist/core/streaming/StreamingManager.js +282 -0
- package/dist/core/streaming/StreamingManager.js.map +1 -0
- package/dist/core/structured/IStructuredOutputManager.d.ts +701 -0
- package/dist/core/structured/IStructuredOutputManager.d.ts.map +1 -0
- package/dist/core/structured/IStructuredOutputManager.js +74 -0
- package/dist/core/structured/IStructuredOutputManager.js.map +1 -0
- package/dist/core/structured/StructuredOutputManager.d.ts +140 -0
- package/dist/core/structured/StructuredOutputManager.d.ts.map +1 -0
- package/dist/core/structured/StructuredOutputManager.js +1015 -0
- package/dist/core/structured/StructuredOutputManager.js.map +1 -0
- package/dist/core/structured/index.d.ts +34 -0
- package/dist/core/structured/index.d.ts.map +1 -0
- package/dist/core/structured/index.js +34 -0
- package/dist/core/structured/index.js.map +1 -0
- package/dist/core/tools/ITool.d.ts +228 -0
- package/dist/core/tools/ITool.d.ts.map +1 -0
- package/dist/core/tools/ITool.js +11 -0
- package/dist/core/tools/ITool.js.map +1 -0
- package/dist/core/tools/IToolOrchestrator.d.ts +131 -0
- package/dist/core/tools/IToolOrchestrator.d.ts.map +1 -0
- package/dist/core/tools/IToolOrchestrator.js +14 -0
- package/dist/core/tools/IToolOrchestrator.js.map +1 -0
- package/dist/core/tools/ToolExecutor.d.ts +143 -0
- package/dist/core/tools/ToolExecutor.d.ts.map +1 -0
- package/dist/core/tools/ToolExecutor.js +364 -0
- package/dist/core/tools/ToolExecutor.js.map +1 -0
- package/dist/core/tools/ToolOrchestrator.d.ts +142 -0
- package/dist/core/tools/ToolOrchestrator.d.ts.map +1 -0
- package/dist/core/tools/ToolOrchestrator.js +373 -0
- package/dist/core/tools/ToolOrchestrator.js.map +1 -0
- package/dist/core/tools/permissions/IToolPermissionManager.d.ts +195 -0
- package/dist/core/tools/permissions/IToolPermissionManager.d.ts.map +1 -0
- package/dist/core/tools/permissions/IToolPermissionManager.js +14 -0
- package/dist/core/tools/permissions/IToolPermissionManager.js.map +1 -0
- package/dist/core/tools/permissions/ToolPermissionManager.d.ts +203 -0
- package/dist/core/tools/permissions/ToolPermissionManager.d.ts.map +1 -0
- package/dist/core/tools/permissions/ToolPermissionManager.js +298 -0
- package/dist/core/tools/permissions/ToolPermissionManager.js.map +1 -0
- package/dist/core/ui/IUIComponent.d.ts +11 -0
- package/dist/core/ui/IUIComponent.d.ts.map +1 -0
- package/dist/core/ui/IUIComponent.js +2 -0
- package/dist/core/ui/IUIComponent.js.map +1 -0
- package/dist/core/usage/UsageLedger.d.ts +81 -0
- package/dist/core/usage/UsageLedger.d.ts.map +1 -0
- package/dist/core/usage/UsageLedger.js +135 -0
- package/dist/core/usage/UsageLedger.js.map +1 -0
- package/dist/core/workflows/IWorkflowEngine.d.ts +42 -0
- package/dist/core/workflows/IWorkflowEngine.d.ts.map +1 -0
- package/dist/core/workflows/IWorkflowEngine.js +2 -0
- package/dist/core/workflows/IWorkflowEngine.js.map +1 -0
- package/dist/core/workflows/WorkflowEngine.d.ts +28 -0
- package/dist/core/workflows/WorkflowEngine.d.ts.map +1 -0
- package/dist/core/workflows/WorkflowEngine.js +309 -0
- package/dist/core/workflows/WorkflowEngine.js.map +1 -0
- package/dist/core/workflows/WorkflowTypes.d.ts +180 -0
- package/dist/core/workflows/WorkflowTypes.d.ts.map +1 -0
- package/dist/core/workflows/WorkflowTypes.js +26 -0
- package/dist/core/workflows/WorkflowTypes.js.map +1 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.d.ts +70 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.d.ts.map +1 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.js +566 -0
- package/dist/core/workflows/runtime/WorkflowRuntime.js.map +1 -0
- package/dist/core/workflows/storage/IWorkflowStore.d.ts +75 -0
- package/dist/core/workflows/storage/IWorkflowStore.d.ts.map +1 -0
- package/dist/core/workflows/storage/IWorkflowStore.js +2 -0
- package/dist/core/workflows/storage/IWorkflowStore.js.map +1 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.d.ts +14 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.d.ts.map +1 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.js +130 -0
- package/dist/core/workflows/storage/InMemoryWorkflowStore.js.map +1 -0
- package/dist/extensions/ExtensionLoader.d.ts +119 -0
- package/dist/extensions/ExtensionLoader.d.ts.map +1 -0
- package/dist/extensions/ExtensionLoader.js +297 -0
- package/dist/extensions/ExtensionLoader.js.map +1 -0
- package/dist/extensions/ExtensionManager.d.ts +49 -0
- package/dist/extensions/ExtensionManager.d.ts.map +1 -0
- package/dist/extensions/ExtensionManager.js +197 -0
- package/dist/extensions/ExtensionManager.js.map +1 -0
- package/dist/extensions/ExtensionRegistry.d.ts +39 -0
- package/dist/extensions/ExtensionRegistry.d.ts.map +1 -0
- package/dist/extensions/ExtensionRegistry.js +103 -0
- package/dist/extensions/ExtensionRegistry.js.map +1 -0
- package/dist/extensions/MultiRegistryLoader.d.ts +61 -0
- package/dist/extensions/MultiRegistryLoader.d.ts.map +1 -0
- package/dist/extensions/MultiRegistryLoader.js +169 -0
- package/dist/extensions/MultiRegistryLoader.js.map +1 -0
- package/dist/extensions/RegistryConfig.d.ts +86 -0
- package/dist/extensions/RegistryConfig.d.ts.map +1 -0
- package/dist/extensions/RegistryConfig.js +99 -0
- package/dist/extensions/RegistryConfig.js.map +1 -0
- package/dist/extensions/events.d.ts +19 -0
- package/dist/extensions/events.d.ts.map +1 -0
- package/dist/extensions/events.js +2 -0
- package/dist/extensions/events.js.map +1 -0
- package/dist/extensions/index.d.ts +9 -0
- package/dist/extensions/index.d.ts.map +1 -0
- package/dist/extensions/index.js +9 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/manifest.d.ts +52 -0
- package/dist/extensions/manifest.d.ts.map +1 -0
- package/dist/extensions/manifest.js +2 -0
- package/dist/extensions/manifest.js.map +1 -0
- package/dist/extensions/types.d.ts +294 -0
- package/dist/extensions/types.d.ts.map +1 -0
- package/dist/extensions/types.js +12 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/logging/ILogger.d.ts +8 -0
- package/dist/logging/ILogger.d.ts.map +1 -0
- package/dist/logging/ILogger.js +2 -0
- package/dist/logging/ILogger.js.map +1 -0
- package/dist/logging/PinoLogger.d.ts +12 -0
- package/dist/logging/PinoLogger.d.ts.map +1 -0
- package/dist/logging/PinoLogger.js +22 -0
- package/dist/logging/PinoLogger.js.map +1 -0
- package/dist/logging/loggerFactory.d.ts +6 -0
- package/dist/logging/loggerFactory.d.ts.map +1 -0
- package/dist/logging/loggerFactory.js +14 -0
- package/dist/logging/loggerFactory.js.map +1 -0
- package/dist/rag/EmbeddingManager.d.ts +81 -0
- package/dist/rag/EmbeddingManager.d.ts.map +1 -0
- package/dist/rag/EmbeddingManager.js +412 -0
- package/dist/rag/EmbeddingManager.js.map +1 -0
- package/dist/rag/IEmbeddingManager.d.ts +277 -0
- package/dist/rag/IEmbeddingManager.d.ts.map +1 -0
- package/dist/rag/IEmbeddingManager.js +19 -0
- package/dist/rag/IEmbeddingManager.js.map +1 -0
- package/dist/rag/IRetrievalAugmentor.d.ts +208 -0
- package/dist/rag/IRetrievalAugmentor.d.ts.map +1 -0
- package/dist/rag/IRetrievalAugmentor.js +21 -0
- package/dist/rag/IRetrievalAugmentor.js.map +1 -0
- package/dist/rag/IVectorStore.d.ts +351 -0
- package/dist/rag/IVectorStore.d.ts.map +1 -0
- package/dist/rag/IVectorStore.js +15 -0
- package/dist/rag/IVectorStore.js.map +1 -0
- package/dist/rag/IVectorStoreManager.d.ts +121 -0
- package/dist/rag/IVectorStoreManager.d.ts.map +1 -0
- package/dist/rag/IVectorStoreManager.js +13 -0
- package/dist/rag/IVectorStoreManager.js.map +1 -0
- package/dist/rag/RetrievalAugmentor.d.ts +99 -0
- package/dist/rag/RetrievalAugmentor.d.ts.map +1 -0
- package/dist/rag/RetrievalAugmentor.js +674 -0
- package/dist/rag/RetrievalAugmentor.js.map +1 -0
- package/dist/rag/VectorStoreManager.d.ts +90 -0
- package/dist/rag/VectorStoreManager.d.ts.map +1 -0
- package/dist/rag/VectorStoreManager.js +283 -0
- package/dist/rag/VectorStoreManager.js.map +1 -0
- package/dist/rag/implementations/index.d.ts +9 -0
- package/dist/rag/implementations/index.d.ts.map +1 -0
- package/dist/rag/implementations/index.js +9 -0
- package/dist/rag/implementations/index.js.map +1 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.d.ts +132 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.d.ts.map +1 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.js +539 -0
- package/dist/rag/implementations/vector_stores/InMemoryVectorStore.js.map +1 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.d.ts +265 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.d.ts.map +1 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.js +755 -0
- package/dist/rag/implementations/vector_stores/SqlVectorStore.js.map +1 -0
- package/dist/rag/implementations/vector_stores/index.d.ts +10 -0
- package/dist/rag/implementations/vector_stores/index.d.ts.map +1 -0
- package/dist/rag/implementations/vector_stores/index.js +12 -0
- package/dist/rag/implementations/vector_stores/index.js.map +1 -0
- package/dist/rag/index.d.ts +95 -0
- package/dist/rag/index.d.ts.map +1 -0
- package/dist/rag/index.js +97 -0
- package/dist/rag/index.js.map +1 -0
- package/dist/services/user_auth/AuthService.d.ts +13 -0
- package/dist/services/user_auth/AuthService.d.ts.map +1 -0
- package/dist/services/user_auth/AuthService.js +24 -0
- package/dist/services/user_auth/AuthService.js.map +1 -0
- package/dist/services/user_auth/SubscriptionService.d.ts +14 -0
- package/dist/services/user_auth/SubscriptionService.d.ts.map +1 -0
- package/dist/services/user_auth/SubscriptionService.js +34 -0
- package/dist/services/user_auth/SubscriptionService.js.map +1 -0
- package/dist/services/user_auth/types.d.ts +30 -0
- package/dist/services/user_auth/types.d.ts.map +1 -0
- package/dist/services/user_auth/types.js +2 -0
- package/dist/services/user_auth/types.js.map +1 -0
- package/dist/stubs/prismaClient.d.ts +35 -0
- package/dist/stubs/prismaClient.d.ts.map +1 -0
- package/dist/stubs/prismaClient.js +47 -0
- package/dist/stubs/prismaClient.js.map +1 -0
- package/dist/types/rateLimitTypes.d.ts +70 -0
- package/dist/types/rateLimitTypes.d.ts.map +1 -0
- package/dist/types/rateLimitTypes.js +55 -0
- package/dist/types/rateLimitTypes.js.map +1 -0
- package/dist/utils/errors.d.ts +80 -0
- package/dist/utils/errors.d.ts.map +1 -0
- package/dist/utils/errors.js +201 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/uuid.d.ts +11 -0
- package/dist/utils/uuid.d.ts.map +1 -0
- package/dist/utils/uuid.js +64 -0
- package/dist/utils/uuid.js.map +1 -0
- package/package.json +84 -0
|
@@ -0,0 +1,872 @@
|
|
|
1
|
+
// File: backend/agentos/core/llm/PromptEngine.ts
|
|
2
|
+
/**
|
|
3
|
+
* @fileoverview Implements the sophisticated PromptEngine that serves as the core of
|
|
4
|
+
* AgentOS's adaptive and contextual prompting system. This implementation provides
|
|
5
|
+
* intelligent prompt construction with dynamic contextual element selection,
|
|
6
|
+
* token budgeting, multi-modal content integration, and optimization strategies.
|
|
7
|
+
*
|
|
8
|
+
* The PromptEngine orchestrates the entire prompt construction pipeline:
|
|
9
|
+
* 1. Context Analysis: Evaluates execution context against persona-defined criteria.
|
|
10
|
+
* 2. Element Selection: Dynamically selects applicable contextual prompt elements.
|
|
11
|
+
* 3. Content Augmentation: Integrates selected elements with base prompt components.
|
|
12
|
+
* 4. Token Management: Applies intelligent budgeting and content optimization.
|
|
13
|
+
* 5. Template Formatting: Renders final prompts using model-specific templates.
|
|
14
|
+
* 6. Quality Assurance: Validates output and reports issues/optimizations.
|
|
15
|
+
*
|
|
16
|
+
* @module backend/agentos/core/llm/PromptEngine
|
|
17
|
+
* @implements {IPromptEngine}
|
|
18
|
+
*/
|
|
19
|
+
import { ContextualElementType, PromptEngineError, } from './IPromptEngine.js';
|
|
20
|
+
import { MessageRole } from '../conversation/ConversationMessage.js'; // Corrected import: Used alias and added MessageRole
|
|
21
|
+
/**
|
|
22
|
+
* Comprehensive implementation of the IPromptEngine interface, providing
|
|
23
|
+
* sophisticated adaptive prompting capabilities for AgentOS GMIs.
|
|
24
|
+
*
|
|
25
|
+
* @class PromptEngine
|
|
26
|
+
* @implements {IPromptEngine}
|
|
27
|
+
*/
|
|
28
|
+
export class PromptEngine {
|
|
29
|
+
constructor() {
|
|
30
|
+
this.isInitialized = false;
|
|
31
|
+
this.cache = new Map();
|
|
32
|
+
this.statistics = this.getInitialStatistics();
|
|
33
|
+
this.defaultTemplates = {
|
|
34
|
+
'openai_chat': this.createOpenAIChatTemplate(),
|
|
35
|
+
'anthropic_messages': this.createAnthropicMessagesTemplate(),
|
|
36
|
+
'generic_completion': this.createGenericCompletionTemplate(),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async initialize(config, utilityAI) {
|
|
40
|
+
if (this.isInitialized) {
|
|
41
|
+
console.warn('PromptEngine: Re-initializing an already initialized engine. State will be reset.');
|
|
42
|
+
this.cache.clear();
|
|
43
|
+
this.statistics = this.getInitialStatistics();
|
|
44
|
+
}
|
|
45
|
+
this.validateEngineConfiguration(config);
|
|
46
|
+
this.config = Object.freeze({ ...config });
|
|
47
|
+
this.utilityAI = utilityAI;
|
|
48
|
+
this.config = Object.freeze({
|
|
49
|
+
...this.config,
|
|
50
|
+
availableTemplates: {
|
|
51
|
+
...this.defaultTemplates,
|
|
52
|
+
...(config.availableTemplates || {}),
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
if (this.config.performance.enableCaching) {
|
|
56
|
+
this.setupCacheEviction();
|
|
57
|
+
}
|
|
58
|
+
this.isInitialized = true;
|
|
59
|
+
console.log(`PromptEngine initialized successfully. Default template: '${this.config.defaultTemplateName}'. Available templates: ${Object.keys(this.config.availableTemplates).length}.`);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Sets the current execution context for implicit persona-aware operations (e.g., tool filtering).
|
|
63
|
+
* Passing undefined clears the context.
|
|
64
|
+
*/
|
|
65
|
+
setCurrentExecutionContext(ctx) {
|
|
66
|
+
this.currentExecutionContext = ctx;
|
|
67
|
+
}
|
|
68
|
+
ensureInitialized() {
|
|
69
|
+
if (!this.isInitialized) {
|
|
70
|
+
throw new PromptEngineError('PromptEngine is not initialized. Call initialize() first.', 'ENGINE_NOT_INITIALIZED', 'PromptEngineCore');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
getInitialStatistics() {
|
|
74
|
+
return {
|
|
75
|
+
totalPromptsConstructed: 0,
|
|
76
|
+
totalConstructionTimeMs: 0,
|
|
77
|
+
cacheHits: 0,
|
|
78
|
+
cacheMisses: 0,
|
|
79
|
+
contextualElementSelections: {},
|
|
80
|
+
tokenCountingOperations: 0,
|
|
81
|
+
errorsByType: {},
|
|
82
|
+
performanceTimers: {}, // Timers will be added with averageTimeMs initialized to 0
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
async constructPrompt(baseComponents, modelTargetInfo, executionContext, templateName) {
|
|
86
|
+
this.ensureInitialized();
|
|
87
|
+
const constructionStart = Date.now();
|
|
88
|
+
this.statistics.totalPromptsConstructed++;
|
|
89
|
+
const result = {
|
|
90
|
+
prompt: [],
|
|
91
|
+
wasTruncatedOrSummarized: false,
|
|
92
|
+
issues: [],
|
|
93
|
+
metadata: {
|
|
94
|
+
constructionTimeMs: 0,
|
|
95
|
+
selectedContextualElementIds: [],
|
|
96
|
+
templateUsed: templateName || modelTargetInfo.promptFormatType || this.config.defaultTemplateName,
|
|
97
|
+
totalSystemPromptsApplied: 0,
|
|
98
|
+
historyMessagesIncluded: 0,
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
if (this.config.performance.enableCaching) {
|
|
102
|
+
const cacheKey = this.generateCacheKey(baseComponents, modelTargetInfo, executionContext, result.metadata.templateUsed);
|
|
103
|
+
result.cacheKey = cacheKey;
|
|
104
|
+
const cached = this.cache.get(cacheKey);
|
|
105
|
+
if (cached && (Date.now() - cached.timestamp) < this.config.performance.cacheTimeoutSeconds * 1000) {
|
|
106
|
+
this.statistics.cacheHits++;
|
|
107
|
+
cached.accessCount++;
|
|
108
|
+
return JSON.parse(JSON.stringify(cached.result));
|
|
109
|
+
}
|
|
110
|
+
this.statistics.cacheMisses++;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
let selectedElements = [];
|
|
114
|
+
// Corrected: use contextualPromptElements directly from IPersonaDefinition
|
|
115
|
+
if (executionContext?.activePersona?.contextualPromptElements) {
|
|
116
|
+
const timerId = 'contextualElementSelection';
|
|
117
|
+
this.startPerformanceTimer(timerId);
|
|
118
|
+
// Corrected: use contextualPromptElements directly
|
|
119
|
+
for (const element of executionContext.activePersona.contextualPromptElements) {
|
|
120
|
+
if (element.criteria && await this.evaluateCriteria(element.criteria, executionContext)) {
|
|
121
|
+
selectedElements.push(element);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
selectedElements.sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
|
125
|
+
const maxElementsOverall = 10; // Example
|
|
126
|
+
selectedElements = selectedElements.slice(0, maxElementsOverall);
|
|
127
|
+
result.metadata.selectedContextualElementIds = selectedElements.map(el => el.id || 'unnamed_contextual_element');
|
|
128
|
+
this.recordPerformanceTimer(timerId, Date.now() - constructionStart); // Pass actual duration
|
|
129
|
+
selectedElements.forEach(el => this.statistics.contextualElementSelections[el.id || el.type] = (this.statistics.contextualElementSelections[el.id || el.type] || 0) + 1);
|
|
130
|
+
}
|
|
131
|
+
const augmentedComponents = this.augmentBaseComponents(baseComponents, selectedElements);
|
|
132
|
+
const timerIdBudget = 'tokenBudgeting';
|
|
133
|
+
const budgetStart = Date.now();
|
|
134
|
+
this.startPerformanceTimer(timerIdBudget);
|
|
135
|
+
const { optimizedComponents, modifications } = await this.applyTokenBudget(augmentedComponents, modelTargetInfo, result.issues || []);
|
|
136
|
+
result.wasTruncatedOrSummarized = modifications.wasModified;
|
|
137
|
+
result.modificationDetails = modifications.details;
|
|
138
|
+
this.recordPerformanceTimer(timerIdBudget, Date.now() - budgetStart);
|
|
139
|
+
const timerIdTemplate = 'templateApplication';
|
|
140
|
+
const templateStart = Date.now();
|
|
141
|
+
this.startPerformanceTimer(timerIdTemplate);
|
|
142
|
+
const templateFn = this.config.availableTemplates[result.metadata.templateUsed];
|
|
143
|
+
if (!templateFn) {
|
|
144
|
+
throw new PromptEngineError(`Template '${result.metadata.templateUsed}' not found.`, 'TEMPLATE_NOT_FOUND', 'TemplateApplication');
|
|
145
|
+
}
|
|
146
|
+
result.prompt = await templateFn(optimizedComponents, modelTargetInfo, selectedElements, this.config, (content, modelId) => this.estimateTokenCount(content, modelId || modelTargetInfo.modelId));
|
|
147
|
+
this.recordPerformanceTimer(timerIdTemplate, Date.now() - templateStart);
|
|
148
|
+
result.estimatedTokenCount = await this.estimateTokenCount(typeof result.prompt === 'string' ? result.prompt : JSON.stringify(result.prompt), modelTargetInfo.modelId);
|
|
149
|
+
result.metadata.totalSystemPromptsApplied = optimizedComponents.systemPrompts?.length || 0;
|
|
150
|
+
result.metadata.historyMessagesIncluded = optimizedComponents.conversationHistory?.length || 0;
|
|
151
|
+
if (optimizedComponents.retrievedContext) {
|
|
152
|
+
result.metadata.ragContextTokensUsed = await this.estimateTokenCount(typeof optimizedComponents.retrievedContext === 'string' ? optimizedComponents.retrievedContext : JSON.stringify(optimizedComponents.retrievedContext), modelTargetInfo.modelId);
|
|
153
|
+
}
|
|
154
|
+
if (optimizedComponents.tools && optimizedComponents.tools.length > 0 && modelTargetInfo.toolSupport.supported) {
|
|
155
|
+
result.formattedToolSchemas = this.formatToolSchemasForModel(optimizedComponents.tools, modelTargetInfo);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
const err = (error instanceof PromptEngineError) ? error :
|
|
160
|
+
new PromptEngineError(error instanceof Error ? error.message : 'Unknown error during prompt construction.', 'UNHANDLED_CONSTRUCTION_ERROR', 'ConstructPromptCore', error);
|
|
161
|
+
result.issues = result.issues || [];
|
|
162
|
+
result.issues.push({
|
|
163
|
+
type: 'error',
|
|
164
|
+
code: err.code,
|
|
165
|
+
message: err.message,
|
|
166
|
+
details: err.details,
|
|
167
|
+
component: err.component || 'ConstructPromptPipeline',
|
|
168
|
+
});
|
|
169
|
+
this.statistics.errorsByType[err.code] = (this.statistics.errorsByType[err.code] || 0) + 1;
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
result.metadata.constructionTimeMs = Date.now() - constructionStart;
|
|
173
|
+
this.statistics.totalConstructionTimeMs += result.metadata.constructionTimeMs;
|
|
174
|
+
}
|
|
175
|
+
if (result.cacheKey && this.config.performance.enableCaching && (result.issues?.every(i => i.type !== 'error'))) {
|
|
176
|
+
this.cache.set(result.cacheKey, {
|
|
177
|
+
key: result.cacheKey,
|
|
178
|
+
result: JSON.parse(JSON.stringify(result)),
|
|
179
|
+
timestamp: Date.now(),
|
|
180
|
+
accessCount: 0,
|
|
181
|
+
modelId: modelTargetInfo.modelId,
|
|
182
|
+
estimatedTokenCount: result.estimatedTokenCount || 0,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
async evaluateCriteria(criteria, context) {
|
|
188
|
+
this.ensureInitialized();
|
|
189
|
+
const timerId = 'evaluateCriteria';
|
|
190
|
+
const evalStart = Date.now();
|
|
191
|
+
this.startPerformanceTimer(timerId);
|
|
192
|
+
let overallMatch = true;
|
|
193
|
+
if (criteria.mood && context.currentMood !== criteria.mood)
|
|
194
|
+
overallMatch = false;
|
|
195
|
+
if (overallMatch && criteria.userSkillLevel && context.userSkillLevel !== criteria.userSkillLevel)
|
|
196
|
+
overallMatch = false;
|
|
197
|
+
if (overallMatch && criteria.taskHint && !context.taskHint?.includes(criteria.taskHint))
|
|
198
|
+
overallMatch = false;
|
|
199
|
+
if (overallMatch && criteria.taskComplexity && context.taskComplexity !== criteria.taskComplexity)
|
|
200
|
+
overallMatch = false;
|
|
201
|
+
if (overallMatch && criteria.language && context.language !== criteria.language)
|
|
202
|
+
overallMatch = false;
|
|
203
|
+
if (overallMatch && criteria.conversationSignals && criteria.conversationSignals.length > 0) {
|
|
204
|
+
// Corrected: Added type for 's'
|
|
205
|
+
if (!criteria.conversationSignals.every((s) => context.conversationSignals?.includes(s))) {
|
|
206
|
+
overallMatch = false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (overallMatch && criteria.workingMemoryQuery) {
|
|
210
|
+
console.warn("Working memory query evaluation in PromptEngine is a placeholder.");
|
|
211
|
+
}
|
|
212
|
+
this.recordPerformanceTimer(timerId, Date.now() - evalStart);
|
|
213
|
+
return overallMatch;
|
|
214
|
+
}
|
|
215
|
+
async estimateTokenCount(content, modelId) {
|
|
216
|
+
this.ensureInitialized();
|
|
217
|
+
this.statistics.tokenCountingOperations++;
|
|
218
|
+
const timerId = 'estimateTokenCount';
|
|
219
|
+
const estimateStart = Date.now();
|
|
220
|
+
this.startPerformanceTimer(timerId);
|
|
221
|
+
if (!content)
|
|
222
|
+
return 0;
|
|
223
|
+
let count = Math.ceil(content.length / 4);
|
|
224
|
+
if (modelId?.includes('gpt-4'))
|
|
225
|
+
count = Math.ceil(content.length / 3.8);
|
|
226
|
+
else if (modelId?.includes('claude'))
|
|
227
|
+
count = Math.ceil(content.length / 4.2);
|
|
228
|
+
this.recordPerformanceTimer(timerId, Date.now() - estimateStart);
|
|
229
|
+
return count;
|
|
230
|
+
}
|
|
231
|
+
async registerTemplate(templateName, templateFunction) {
|
|
232
|
+
this.ensureInitialized();
|
|
233
|
+
if (!templateName || typeof templateName !== 'string' || templateName.trim() === '') {
|
|
234
|
+
throw new PromptEngineError('Template name must be a non-empty string.', 'INVALID_TEMPLATE_NAME', 'RegisterTemplate');
|
|
235
|
+
}
|
|
236
|
+
if (typeof templateFunction !== 'function') {
|
|
237
|
+
throw new PromptEngineError('Template function must be a valid function.', 'INVALID_TEMPLATE_FUNCTION', 'RegisterTemplate');
|
|
238
|
+
}
|
|
239
|
+
const mutableTemplates = this.config.availableTemplates;
|
|
240
|
+
if (mutableTemplates[templateName]) {
|
|
241
|
+
console.warn(`PromptEngine: Overwriting existing template '${templateName}'.`);
|
|
242
|
+
}
|
|
243
|
+
mutableTemplates[templateName] = templateFunction;
|
|
244
|
+
console.log(`PromptEngine: Template '${templateName}' registered.`);
|
|
245
|
+
}
|
|
246
|
+
async validatePromptConfiguration(components, modelTargetInfo, executionContext) {
|
|
247
|
+
this.ensureInitialized();
|
|
248
|
+
const issues = [];
|
|
249
|
+
const recommendations = [];
|
|
250
|
+
if (components.visionInputs && components.visionInputs.length > 0 && !modelTargetInfo.visionSupport?.supported) {
|
|
251
|
+
issues.push({ type: 'error', code: 'VISION_NOT_SUPPORTED', message: `Model ${modelTargetInfo.modelId} does not support vision inputs.`, component: 'visionInputs' });
|
|
252
|
+
}
|
|
253
|
+
if (components.tools && components.tools.length > 0 && !modelTargetInfo.toolSupport.supported) {
|
|
254
|
+
issues.push({ type: 'error', code: 'TOOLS_NOT_SUPPORTED', message: `Model ${modelTargetInfo.modelId} does not support tools/functions.`, component: 'tools' });
|
|
255
|
+
}
|
|
256
|
+
let estimatedTokens = 0;
|
|
257
|
+
if (components.systemPrompts)
|
|
258
|
+
estimatedTokens += (await Promise.all(components.systemPrompts.map(sp => this.estimateTokenCount(sp.content, modelTargetInfo.modelId)))).reduce((a, b) => a + b, 0);
|
|
259
|
+
if (components.userInput)
|
|
260
|
+
estimatedTokens += await this.estimateTokenCount(components.userInput, modelTargetInfo.modelId);
|
|
261
|
+
if (components.conversationHistory)
|
|
262
|
+
estimatedTokens += await this.calculateTokensForMessages(components.conversationHistory, modelTargetInfo.modelId); // Corrected: Call fixed calculateTokensForMessages
|
|
263
|
+
if (estimatedTokens > modelTargetInfo.maxContextTokens) {
|
|
264
|
+
issues.push({ type: 'warning', code: 'POTENTIAL_TOKEN_OVERFLOW', message: `Estimated initial token count (${estimatedTokens}) exceeds model's max context (${modelTargetInfo.maxContextTokens}). Relying on truncation/summarization.`, component: 'OverallPrompt' });
|
|
265
|
+
}
|
|
266
|
+
else if (estimatedTokens > (modelTargetInfo.optimalContextTokens || modelTargetInfo.maxContextTokens) * 0.8) {
|
|
267
|
+
recommendations.push(`Consider reducing initial prompt length; current estimate (${estimatedTokens}) is >80% of optimal/max context.`);
|
|
268
|
+
}
|
|
269
|
+
if (!components.systemPrompts || components.systemPrompts.length === 0) {
|
|
270
|
+
recommendations.push("Consider adding a system prompt to guide the GMI's behavior more effectively.");
|
|
271
|
+
}
|
|
272
|
+
// Corrected: Use contextualPromptElements directly
|
|
273
|
+
if (executionContext?.activePersona?.contextualPromptElements) {
|
|
274
|
+
recommendations.push("Review persona's contextual elements to ensure they align with expected execution contexts.");
|
|
275
|
+
}
|
|
276
|
+
return { isValid: !issues.some(i => i.type === 'error'), issues, recommendations };
|
|
277
|
+
}
|
|
278
|
+
async clearCache(selectivePattern) {
|
|
279
|
+
this.ensureInitialized();
|
|
280
|
+
if (!this.config.performance.enableCaching) {
|
|
281
|
+
console.warn("PromptEngine: Cache clearing attempted but caching is disabled.");
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (selectivePattern) {
|
|
285
|
+
let clearedCount = 0;
|
|
286
|
+
const regex = new RegExp(selectivePattern);
|
|
287
|
+
for (const key of this.cache.keys()) {
|
|
288
|
+
if (regex.test(key)) {
|
|
289
|
+
this.cache.delete(key);
|
|
290
|
+
clearedCount++;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
console.log(`PromptEngine: Cleared ${clearedCount} cache entries matching pattern '${selectivePattern}'.`);
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
this.cache.clear();
|
|
297
|
+
console.log("PromptEngine: All cache entries cleared.");
|
|
298
|
+
}
|
|
299
|
+
this.statistics.cacheHits = 0;
|
|
300
|
+
this.statistics.cacheMisses = 0;
|
|
301
|
+
}
|
|
302
|
+
async getEngineStatistics() {
|
|
303
|
+
this.ensureInitialized();
|
|
304
|
+
const totalCacheAccesses = this.statistics.cacheHits + this.statistics.cacheMisses;
|
|
305
|
+
const cacheEffectiveness = totalCacheAccesses > 0 ? this.statistics.cacheHits / totalCacheAccesses : 0;
|
|
306
|
+
const contextualElementUsageWithAvgTime = {};
|
|
307
|
+
for (const key in this.statistics.contextualElementSelections) {
|
|
308
|
+
contextualElementUsageWithAvgTime[key] = {
|
|
309
|
+
count: this.statistics.contextualElementSelections[key],
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
// Calculate averageTimeMs for performanceTimers before returning
|
|
313
|
+
const calculatedPerformanceTimers = {};
|
|
314
|
+
for (const key in this.statistics.performanceTimers) {
|
|
315
|
+
const timer = this.statistics.performanceTimers[key];
|
|
316
|
+
calculatedPerformanceTimers[key] = {
|
|
317
|
+
...timer,
|
|
318
|
+
averageTimeMs: timer.count > 0 ? timer.totalTimeMs / timer.count : 0,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
totalPromptsConstructed: this.statistics.totalPromptsConstructed,
|
|
323
|
+
averageConstructionTimeMs: this.statistics.totalPromptsConstructed > 0 ? this.statistics.totalConstructionTimeMs / this.statistics.totalPromptsConstructed : 0,
|
|
324
|
+
cacheStats: {
|
|
325
|
+
hits: this.statistics.cacheHits,
|
|
326
|
+
misses: this.statistics.cacheMisses,
|
|
327
|
+
currentSize: this.cache.size,
|
|
328
|
+
maxSize: this.config.performance.maxCacheSizeBytes,
|
|
329
|
+
effectivenessRatio: cacheEffectiveness,
|
|
330
|
+
},
|
|
331
|
+
tokenCountingStats: {
|
|
332
|
+
operations: this.statistics.tokenCountingOperations,
|
|
333
|
+
},
|
|
334
|
+
contextualElementUsage: contextualElementUsageWithAvgTime,
|
|
335
|
+
errorRatePerType: { ...this.statistics.errorsByType },
|
|
336
|
+
performanceTimers: calculatedPerformanceTimers, // Use calculated version
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
validateEngineConfiguration(config) {
|
|
340
|
+
if (!config.defaultTemplateName || typeof config.defaultTemplateName !== 'string') {
|
|
341
|
+
throw new PromptEngineError('Invalid `defaultTemplateName` in configuration.', 'INVALID_CONFIG_PARAM', 'Initialization');
|
|
342
|
+
}
|
|
343
|
+
if (!config.availableTemplates || typeof config.availableTemplates !== 'object') {
|
|
344
|
+
throw new PromptEngineError('Invalid `availableTemplates` in configuration.', 'INVALID_CONFIG_PARAM', 'Initialization');
|
|
345
|
+
}
|
|
346
|
+
if (!config.tokenCounting || typeof config.tokenCounting.strategy !== 'string') {
|
|
347
|
+
throw new PromptEngineError('Invalid `tokenCounting` strategy in configuration.', 'INVALID_CONFIG_PARAM', 'Initialization');
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
generateCacheKey(components, modelInfo, executionContext, templateName) {
|
|
351
|
+
/**
|
|
352
|
+
* Generates a stable cache key for a prospective prompt construction result.
|
|
353
|
+
* Key Composition Strategy (intentional truncation for privacy & size):
|
|
354
|
+
* - First 50 chars of each system prompt concatenated (order sensitive)
|
|
355
|
+
* - First 100 chars of user input
|
|
356
|
+
* - Last turn content excerpt (first 50 chars) for light history sensitivity
|
|
357
|
+
* - Tool id list (joined)
|
|
358
|
+
* - Model id, template name, persona id, mood, task hint
|
|
359
|
+
*
|
|
360
|
+
* Hashing: Simple 32‑bit additive hash -> base36 to keep key short; collision risk acceptable for cache.
|
|
361
|
+
*
|
|
362
|
+
* NOTE: Omits retrievedContext & full history intentionally to avoid large keys and leaking RAG content into logs.
|
|
363
|
+
*/
|
|
364
|
+
const relevantData = {
|
|
365
|
+
system: components.systemPrompts?.map(p => p.content.substring(0, 50)).join(';'),
|
|
366
|
+
userInput: components.userInput?.substring(0, 100),
|
|
367
|
+
historyLastTurn: components.conversationHistory?.[components.conversationHistory.length - 1]?.content?.toString().substring(0, 50),
|
|
368
|
+
tools: components.tools?.map(t => t.id).join(','),
|
|
369
|
+
modelId: modelInfo.modelId,
|
|
370
|
+
template: templateName,
|
|
371
|
+
personaId: executionContext?.activePersona.id,
|
|
372
|
+
mood: executionContext?.currentMood,
|
|
373
|
+
task: executionContext?.taskHint,
|
|
374
|
+
};
|
|
375
|
+
const keyString = Object.values(relevantData).filter(v => v !== undefined).join('||');
|
|
376
|
+
let hash = 0;
|
|
377
|
+
for (let i = 0; i < keyString.length; i++) {
|
|
378
|
+
const char = keyString.charCodeAt(i);
|
|
379
|
+
hash = ((hash << 5) - hash) + char;
|
|
380
|
+
hash |= 0;
|
|
381
|
+
}
|
|
382
|
+
return `promptcache:${modelInfo.modelId}:${hash.toString(36)}`;
|
|
383
|
+
}
|
|
384
|
+
setupCacheEviction() {
|
|
385
|
+
/**
|
|
386
|
+
* Periodic passive cache eviction loop. Strategy:
|
|
387
|
+
* - Run every half of timeout window (min 60s)
|
|
388
|
+
* - Drop entries whose age > configured timeout.
|
|
389
|
+
* No size‑based LRU yet; maxCacheSizeBytes reserved for future implementation.
|
|
390
|
+
*/
|
|
391
|
+
const interval = (this.config.performance.cacheTimeoutSeconds / 2) * 1000;
|
|
392
|
+
setInterval(() => {
|
|
393
|
+
const now = Date.now();
|
|
394
|
+
for (const [key, entry] of this.cache.entries()) {
|
|
395
|
+
if ((now - entry.timestamp) > this.config.performance.cacheTimeoutSeconds * 1000) {
|
|
396
|
+
this.cache.delete(key);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}, Math.max(interval, 60000));
|
|
400
|
+
}
|
|
401
|
+
startPerformanceTimer(timerId) {
|
|
402
|
+
if (!this.statistics.performanceTimers[timerId]) {
|
|
403
|
+
// Initialize with averageTimeMs
|
|
404
|
+
this.statistics.performanceTimers[timerId] = { count: 0, totalTimeMs: 0, averageTimeMs: 0 };
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
recordPerformanceTimer(timerId, durationMs) {
|
|
408
|
+
const DUMMY_DURATION = 10;
|
|
409
|
+
const actualDuration = durationMs !== undefined ? durationMs : DUMMY_DURATION;
|
|
410
|
+
const timer = this.statistics.performanceTimers[timerId];
|
|
411
|
+
if (timer) {
|
|
412
|
+
timer.count++;
|
|
413
|
+
timer.totalTimeMs += actualDuration;
|
|
414
|
+
// averageTimeMs will be calculated in getEngineStatistics to avoid repetitive division
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
augmentBaseComponents(base, selectedElements) {
|
|
418
|
+
/**
|
|
419
|
+
* Applies selected contextual elements onto the immutable base components producing a mutable augmented copy.
|
|
420
|
+
* Merging Rules:
|
|
421
|
+
* - System prompt augmenters append as new system prompts with synthetic source tag.
|
|
422
|
+
* - Few‑shot examples accumulate under customComponents.fewShotExamples.
|
|
423
|
+
* - User prompt augmentation concatenates onto existing userInput (newline separated).
|
|
424
|
+
* - All other element types fall back to a dynamic bucket keyed by normalized type.
|
|
425
|
+
* Sorting: Final systemPrompts sorted ascending by priority to preserve intended ordering.
|
|
426
|
+
*/
|
|
427
|
+
const augmented = JSON.parse(JSON.stringify(base));
|
|
428
|
+
if (!augmented.systemPrompts)
|
|
429
|
+
augmented.systemPrompts = [];
|
|
430
|
+
if (!augmented.customComponents)
|
|
431
|
+
augmented.customComponents = {};
|
|
432
|
+
for (const element of selectedElements) {
|
|
433
|
+
switch (element.type) {
|
|
434
|
+
case ContextualElementType.SYSTEM_INSTRUCTION_ADDON:
|
|
435
|
+
case ContextualElementType.BEHAVIORAL_GUIDANCE:
|
|
436
|
+
case ContextualElementType.TASK_SPECIFIC_INSTRUCTION:
|
|
437
|
+
case ContextualElementType.ERROR_HANDLING_GUIDANCE:
|
|
438
|
+
case ContextualElementType.ETHICAL_GUIDELINE:
|
|
439
|
+
case ContextualElementType.OUTPUT_FORMAT_SPEC:
|
|
440
|
+
case ContextualElementType.REASONING_PROTOCOL:
|
|
441
|
+
augmented.systemPrompts.push({ content: element.content, priority: element.priority || 100, source: `contextual:${element.id || element.type}` });
|
|
442
|
+
break;
|
|
443
|
+
case ContextualElementType.FEW_SHOT_EXAMPLE:
|
|
444
|
+
if (!augmented.customComponents.fewShotExamples)
|
|
445
|
+
augmented.customComponents.fewShotExamples = [];
|
|
446
|
+
augmented.customComponents.fewShotExamples.push(element.content);
|
|
447
|
+
break;
|
|
448
|
+
case ContextualElementType.USER_PROMPT_AUGMENTATION:
|
|
449
|
+
augmented.userInput = `${augmented.userInput || ''}\n${element.content}`.trim();
|
|
450
|
+
break;
|
|
451
|
+
default: {
|
|
452
|
+
const typeKey = element.type.toString().toLowerCase().replace(/_/g, '');
|
|
453
|
+
if (!augmented.customComponents[typeKey])
|
|
454
|
+
augmented.customComponents[typeKey] = [];
|
|
455
|
+
augmented.customComponents[typeKey].push(element.content);
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
augmented.systemPrompts.sort((a, b) => (a.priority || 0) - (b.priority || 0));
|
|
461
|
+
return augmented;
|
|
462
|
+
}
|
|
463
|
+
async applyTokenBudget(components, modelInfo, issues) {
|
|
464
|
+
/**
|
|
465
|
+
* Enforces token budget across prompt sections (system, userInput, history, RAG context, tools).
|
|
466
|
+
* Allocation Heuristics (percentages of overall budget):
|
|
467
|
+
* - system: 20%, user: 15%, history: 35%, rag: 20%, tools: 10%
|
|
468
|
+
* Summarization: Uses UtilityAI if available & trigger ratio exceeded; else truncation fallback.
|
|
469
|
+
* Failure Handling: On summarization errors pushes warning issue & falls back to truncation.
|
|
470
|
+
* Returns cloned optimized components plus modification descriptors for telemetry.
|
|
471
|
+
*/
|
|
472
|
+
const optimized = JSON.parse(JSON.stringify(components));
|
|
473
|
+
const modifications = {
|
|
474
|
+
wasModified: false,
|
|
475
|
+
details: { truncatedComponents: [], summarizedComponents: [], removedComponents: [], originalEstimatedTokenCount: 0 }
|
|
476
|
+
};
|
|
477
|
+
const budget = modelInfo.optimalContextTokens || modelInfo.maxContextTokens;
|
|
478
|
+
let currentTokens = await this.calculateTotalTokens(optimized, modelInfo.modelId);
|
|
479
|
+
modifications.details.originalEstimatedTokenCount = currentTokens;
|
|
480
|
+
const budgets = {
|
|
481
|
+
system: 0.20 * budget,
|
|
482
|
+
userInput: 0.15 * budget,
|
|
483
|
+
history: 0.35 * budget,
|
|
484
|
+
rag: 0.20 * budget,
|
|
485
|
+
tools: 0.10 * budget,
|
|
486
|
+
};
|
|
487
|
+
if (optimized.conversationHistory && optimized.conversationHistory.length > 0) {
|
|
488
|
+
let historyTokens = await this.calculateTokensForMessages(optimized.conversationHistory, modelInfo.modelId);
|
|
489
|
+
if (historyTokens > budgets.history || currentTokens > budget) {
|
|
490
|
+
const originalCount = optimized.conversationHistory.length;
|
|
491
|
+
if (this.utilityAI && this.config.historyManagement.summarizationTriggerRatio > 0 && (historyTokens / budgets.history > this.config.historyManagement.summarizationTriggerRatio)) {
|
|
492
|
+
try {
|
|
493
|
+
const { summaryMessages, finalTokenCount } = await this.utilityAI.summarizeConversationHistory(optimized.conversationHistory, (currentTokens > budget) ? budgets.history - (currentTokens - budget) : budgets.history, modelInfo, this.config.historyManagement.preserveImportantMessages);
|
|
494
|
+
optimized.conversationHistory = summaryMessages;
|
|
495
|
+
modifications.details.summarizedComponents.push('conversationHistory');
|
|
496
|
+
modifications.wasModified = true;
|
|
497
|
+
currentTokens = currentTokens - historyTokens + finalTokenCount;
|
|
498
|
+
historyTokens = finalTokenCount;
|
|
499
|
+
}
|
|
500
|
+
catch (e) {
|
|
501
|
+
issues?.push({ type: 'warning', code: 'HISTORY_SUMMARIZATION_FAILED', message: `History summarization failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
502
|
+
optimized.conversationHistory = this.truncateMessages(optimized.conversationHistory, budgets.history, (content) => this.estimateTokenCount(content, modelInfo.modelId));
|
|
503
|
+
modifications.details.truncatedComponents.push('conversationHistory');
|
|
504
|
+
modifications.wasModified = true;
|
|
505
|
+
const newHistoryTokens = await this.calculateTokensForMessages(optimized.conversationHistory, modelInfo.modelId);
|
|
506
|
+
currentTokens = currentTokens - historyTokens + newHistoryTokens;
|
|
507
|
+
historyTokens = newHistoryTokens;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
optimized.conversationHistory = this.truncateMessages(optimized.conversationHistory, budgets.history, (content) => this.estimateTokenCount(content, modelInfo.modelId));
|
|
512
|
+
if (optimized.conversationHistory.length < originalCount) {
|
|
513
|
+
modifications.details.truncatedComponents.push('conversationHistory');
|
|
514
|
+
modifications.wasModified = true;
|
|
515
|
+
}
|
|
516
|
+
const newHistoryTokens = await this.calculateTokensForMessages(optimized.conversationHistory, modelInfo.modelId);
|
|
517
|
+
currentTokens = currentTokens - historyTokens + newHistoryTokens;
|
|
518
|
+
historyTokens = newHistoryTokens;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (optimized.retrievedContext) {
|
|
523
|
+
const contextStr = typeof optimized.retrievedContext === 'string' ? optimized.retrievedContext : optimized.retrievedContext.map(r => r.content).join('\n');
|
|
524
|
+
let ragTokens = await this.estimateTokenCount(contextStr, modelInfo.modelId);
|
|
525
|
+
if (ragTokens > budgets.rag || currentTokens > budget) {
|
|
526
|
+
if (this.utilityAI) {
|
|
527
|
+
try {
|
|
528
|
+
const { summary, finalTokenCount } = await this.utilityAI.summarizeRAGContext(optimized.retrievedContext, (currentTokens > budget) ? budgets.rag - (currentTokens - budget) : budgets.rag, modelInfo, this.config.contextManagement.preserveSourceAttributionInSummary);
|
|
529
|
+
optimized.retrievedContext = summary;
|
|
530
|
+
modifications.details.summarizedComponents.push('retrievedContext');
|
|
531
|
+
modifications.wasModified = true;
|
|
532
|
+
currentTokens = currentTokens - ragTokens + finalTokenCount;
|
|
533
|
+
ragTokens = finalTokenCount;
|
|
534
|
+
}
|
|
535
|
+
catch (e) {
|
|
536
|
+
issues?.push({ type: 'warning', code: 'RAG_SUMMARIZATION_FAILED', message: `RAG summarization failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
537
|
+
optimized.retrievedContext = contextStr.substring(0, Math.floor(contextStr.length * (budgets.rag / ragTokens)));
|
|
538
|
+
modifications.details.truncatedComponents.push('retrievedContext');
|
|
539
|
+
modifications.wasModified = true;
|
|
540
|
+
const newRagTokens = await this.estimateTokenCount(optimized.retrievedContext, modelInfo.modelId);
|
|
541
|
+
currentTokens = currentTokens - ragTokens + newRagTokens;
|
|
542
|
+
ragTokens = newRagTokens;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
optimized.retrievedContext = contextStr.substring(0, Math.floor(contextStr.length * (budgets.rag / ragTokens)));
|
|
547
|
+
modifications.details.truncatedComponents.push('retrievedContext');
|
|
548
|
+
modifications.wasModified = true;
|
|
549
|
+
const newRagTokens = await this.estimateTokenCount(optimized.retrievedContext, modelInfo.modelId);
|
|
550
|
+
currentTokens = currentTokens - ragTokens + newRagTokens;
|
|
551
|
+
ragTokens = newRagTokens;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (currentTokens > budget && issues) {
|
|
556
|
+
issues.push({ type: 'warning', code: 'TOKEN_BUDGET_EXCEEDED_POST_OPT', message: `Prompt still exceeds budget (${currentTokens}/${budget}) after initial optimizations. Quality may be affected.` });
|
|
557
|
+
}
|
|
558
|
+
return { optimizedComponents: optimized, modifications };
|
|
559
|
+
}
|
|
560
|
+
async calculateTotalTokens(components, modelId) {
|
|
561
|
+
let total = 0;
|
|
562
|
+
if (components.systemPrompts)
|
|
563
|
+
total += (await Promise.all(components.systemPrompts.map(sp => this.estimateTokenCount(sp.content, modelId)))).reduce((a, b) => a + b, 0);
|
|
564
|
+
if (components.userInput)
|
|
565
|
+
total += await this.estimateTokenCount(components.userInput, modelId);
|
|
566
|
+
if (components.conversationHistory)
|
|
567
|
+
total += await this.calculateTokensForMessages(components.conversationHistory, modelId);
|
|
568
|
+
if (components.retrievedContext) {
|
|
569
|
+
const contextStr = typeof components.retrievedContext === 'string' ? components.retrievedContext : components.retrievedContext.map(r => r.content).join('\n');
|
|
570
|
+
total += await this.estimateTokenCount(contextStr, modelId);
|
|
571
|
+
}
|
|
572
|
+
if (components.tools)
|
|
573
|
+
total += components.tools.length * 50;
|
|
574
|
+
return total;
|
|
575
|
+
}
|
|
576
|
+
async calculateTokensForMessages(messages, modelId) {
|
|
577
|
+
if (!messages)
|
|
578
|
+
return 0;
|
|
579
|
+
let sum = 0;
|
|
580
|
+
for (const msg of messages) {
|
|
581
|
+
// Corrected: Handle different types of msg.content
|
|
582
|
+
if (typeof msg.content === 'string') {
|
|
583
|
+
sum += await this.estimateTokenCount(msg.content, modelId);
|
|
584
|
+
}
|
|
585
|
+
else if (Array.isArray(msg.content)) { // Multi-part content
|
|
586
|
+
for (const part of msg.content) { // Use MessageContentPart type
|
|
587
|
+
if (part.type === 'text' && typeof part.text === 'string') {
|
|
588
|
+
sum += await this.estimateTokenCount(part.text, modelId);
|
|
589
|
+
}
|
|
590
|
+
else if (part.type === 'image_url' && part.image_url) {
|
|
591
|
+
sum += 70; // Base cost for image URL
|
|
592
|
+
if (part.image_url.detail === 'high')
|
|
593
|
+
sum += 65; // Additional for high-res
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
else if (msg.content === null) {
|
|
598
|
+
// No content tokens, but message overhead still applies
|
|
599
|
+
}
|
|
600
|
+
else if (typeof msg.content === 'object' && msg.content !== null) {
|
|
601
|
+
// This case should not be common if msg.content is Array for multi-part, but as a fallback:
|
|
602
|
+
sum += await this.estimateTokenCount(JSON.stringify(msg.content), modelId);
|
|
603
|
+
}
|
|
604
|
+
sum += 5; // Overhead for role, name, etc.
|
|
605
|
+
}
|
|
606
|
+
return sum;
|
|
607
|
+
}
|
|
608
|
+
truncateMessages(messages, targetTokenCount, _estimateFn) {
|
|
609
|
+
let currentTokens = messages.reduce((sum, msg) => sum + (typeof msg.content === 'string' ? msg.content.length : (Array.isArray(msg.content) ? JSON.stringify(msg.content).length : 50)), 0) / 4; // More robust rough estimate
|
|
610
|
+
while (currentTokens > targetTokenCount && messages.length > 1) {
|
|
611
|
+
const removedMsg = messages.shift();
|
|
612
|
+
currentTokens -= (typeof removedMsg?.content === 'string' ? removedMsg.content.length : (Array.isArray(removedMsg?.content) ? JSON.stringify(removedMsg?.content).length : 50)) / 4;
|
|
613
|
+
}
|
|
614
|
+
return messages;
|
|
615
|
+
}
|
|
616
|
+
formatToolSchemasForModel(tools, modelInfo) {
|
|
617
|
+
/**
|
|
618
|
+
* Normalizes internal ITool definitions to provider‑specific function/tool schema payloads.
|
|
619
|
+
* Currently supports:
|
|
620
|
+
* - openai_functions: Emits array of { type: 'function', function: { name, description, parameters } }
|
|
621
|
+
* Fallback path returns simplified definitions for unsupported formats with a console warning.
|
|
622
|
+
*
|
|
623
|
+
* Tool Schema Manifest Filtering:
|
|
624
|
+
* If `config.toolSchemaManifest` specifies rules for the active persona, apply them BEFORE formatting:
|
|
625
|
+
* - model override list (exact allowed IDs) takes highest precedence.
|
|
626
|
+
* - enabledToolIds whitelist applied if present (intersection).
|
|
627
|
+
* - disabledToolIds removed at end.
|
|
628
|
+
* Unknown IDs in manifest are ignored. If filtering results in empty set, returns [].
|
|
629
|
+
*/
|
|
630
|
+
if (!modelInfo.toolSupport.supported || !tools || tools.length === 0) {
|
|
631
|
+
return [];
|
|
632
|
+
}
|
|
633
|
+
// Manifest filtering
|
|
634
|
+
let filtered = tools;
|
|
635
|
+
const filteringReasons = {};
|
|
636
|
+
const personaId = this.currentExecutionContext?.activePersona?.id || undefined;
|
|
637
|
+
const manifestEntry = personaId ? this.config.toolSchemaManifest?.[personaId] : undefined;
|
|
638
|
+
if (manifestEntry) {
|
|
639
|
+
const { modelOverrides, enabledToolIds, disabledToolIds } = manifestEntry;
|
|
640
|
+
if (modelOverrides && modelOverrides[modelInfo.modelId]) {
|
|
641
|
+
const allowedList = new Set(modelOverrides[modelInfo.modelId]);
|
|
642
|
+
filtered = filtered.filter(t => {
|
|
643
|
+
const keep = allowedList.has(t.id);
|
|
644
|
+
if (!keep)
|
|
645
|
+
filteringReasons[t.id] = 'excluded:not_in_model_override_list';
|
|
646
|
+
else
|
|
647
|
+
filteringReasons[t.id] = 'included:model_override';
|
|
648
|
+
return keep;
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
else if (enabledToolIds && enabledToolIds.length > 0) {
|
|
652
|
+
const allowed = new Set(enabledToolIds);
|
|
653
|
+
filtered = filtered.filter(t => {
|
|
654
|
+
const keep = allowed.has(t.id);
|
|
655
|
+
if (!keep)
|
|
656
|
+
filteringReasons[t.id] = 'excluded:not_in_enabled_tool_ids';
|
|
657
|
+
else
|
|
658
|
+
filteringReasons[t.id] = 'included:enabled_tool_ids';
|
|
659
|
+
return keep;
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
if (disabledToolIds && disabledToolIds.length > 0) {
|
|
663
|
+
const blocked = new Set(disabledToolIds);
|
|
664
|
+
filtered = filtered.filter(t => {
|
|
665
|
+
const blockedOut = blocked.has(t.id);
|
|
666
|
+
if (blockedOut)
|
|
667
|
+
filteringReasons[t.id] = 'excluded:disabled_tool_ids';
|
|
668
|
+
return !blockedOut;
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (filtered.length === 0)
|
|
673
|
+
return [];
|
|
674
|
+
switch (modelInfo.toolSupport.format) {
|
|
675
|
+
case 'openai_functions':
|
|
676
|
+
return filtered.map(tool => ({
|
|
677
|
+
type: 'function',
|
|
678
|
+
function: this.buildToolDefinition(tool),
|
|
679
|
+
_filteringReason: filteringReasons[tool.id],
|
|
680
|
+
}));
|
|
681
|
+
default:
|
|
682
|
+
console.warn(`PromptEngine: Tool format '${modelInfo.toolSupport.format}' not fully supported for schema generation. Returning normalized definitions.`);
|
|
683
|
+
return filtered.map(tool => ({ ...this.buildToolDefinition(tool), _filteringReason: filteringReasons[tool.id] }));
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
buildToolDefinition(tool) {
|
|
687
|
+
return {
|
|
688
|
+
name: tool.name || tool.id,
|
|
689
|
+
description: tool.description || tool.displayName || tool.name,
|
|
690
|
+
parameters: tool.inputSchema && Object.keys(tool.inputSchema).length > 0
|
|
691
|
+
? tool.inputSchema
|
|
692
|
+
: { type: 'object', properties: {}, additionalProperties: false },
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
serializeToolArguments(args) {
|
|
696
|
+
if (typeof args === 'string') {
|
|
697
|
+
return args;
|
|
698
|
+
}
|
|
699
|
+
try {
|
|
700
|
+
return JSON.stringify(args ?? {});
|
|
701
|
+
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
console.warn('PromptEngine: Failed to stringify tool arguments for function call.', error);
|
|
704
|
+
return '{}';
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
normalizeToolCalls(toolCalls) {
|
|
708
|
+
if (!toolCalls || toolCalls.length === 0) {
|
|
709
|
+
return undefined;
|
|
710
|
+
}
|
|
711
|
+
return toolCalls.map(call => ({
|
|
712
|
+
id: call.id,
|
|
713
|
+
type: 'function',
|
|
714
|
+
function: {
|
|
715
|
+
name: call.name,
|
|
716
|
+
arguments: this.serializeToolArguments(call.arguments),
|
|
717
|
+
},
|
|
718
|
+
}));
|
|
719
|
+
}
|
|
720
|
+
createOpenAIChatTemplate() {
|
|
721
|
+
return async (components, modelInfo, _selectedElements, _config, _estimateTokenCountFn) => {
|
|
722
|
+
const messages = [];
|
|
723
|
+
if (components.systemPrompts && components.systemPrompts.length > 0) {
|
|
724
|
+
const combinedSystemContent = components.systemPrompts.map(p => p.content).join("\n\n").trim();
|
|
725
|
+
if (combinedSystemContent) {
|
|
726
|
+
messages.push({ role: 'system', content: combinedSystemContent });
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
if (components.conversationHistory) {
|
|
730
|
+
components.conversationHistory.forEach(msg => {
|
|
731
|
+
let role = 'user';
|
|
732
|
+
if (msg.role === MessageRole.ASSISTANT)
|
|
733
|
+
role = 'assistant';
|
|
734
|
+
else if (msg.role === MessageRole.SYSTEM)
|
|
735
|
+
role = 'system';
|
|
736
|
+
else if (msg.role === MessageRole.TOOL)
|
|
737
|
+
role = 'tool';
|
|
738
|
+
const chatMsg = { role, content: null };
|
|
739
|
+
if (typeof msg.content === 'string') {
|
|
740
|
+
chatMsg.content = msg.content;
|
|
741
|
+
}
|
|
742
|
+
else if (Array.isArray(msg.content)) {
|
|
743
|
+
chatMsg.content = msg.content; // Use MessageContentPart
|
|
744
|
+
}
|
|
745
|
+
else if (msg.content === null && msg.tool_calls) {
|
|
746
|
+
// Fine for tool_calls
|
|
747
|
+
}
|
|
748
|
+
else if (msg.content) {
|
|
749
|
+
chatMsg.content = JSON.stringify(msg.content);
|
|
750
|
+
}
|
|
751
|
+
if (msg.name)
|
|
752
|
+
chatMsg.name = msg.name;
|
|
753
|
+
if (msg.tool_call_id)
|
|
754
|
+
chatMsg.tool_call_id = msg.tool_call_id;
|
|
755
|
+
const normalizedToolCalls = this.normalizeToolCalls(msg.tool_calls);
|
|
756
|
+
if (normalizedToolCalls) {
|
|
757
|
+
chatMsg.tool_calls = normalizedToolCalls;
|
|
758
|
+
if (chatMsg.content === undefined) {
|
|
759
|
+
chatMsg.content = null;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
messages.push(chatMsg);
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
const userMessageParts = []; // Use MessageContentPart
|
|
766
|
+
if (components.userInput) {
|
|
767
|
+
userMessageParts.push({ type: 'text', text: components.userInput });
|
|
768
|
+
}
|
|
769
|
+
if (components.visionInputs && modelInfo.visionSupport?.supported) {
|
|
770
|
+
components.visionInputs.forEach(vis => {
|
|
771
|
+
userMessageParts.push({
|
|
772
|
+
type: 'image_url',
|
|
773
|
+
image_url: { url: vis.type === 'base64' ? `data:${vis.mimeType || 'image/jpeg'};base64,${vis.data}` : vis.data } // Corrected: vis.mimeType
|
|
774
|
+
});
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
if (userMessageParts.length > 0) {
|
|
778
|
+
messages.push({ role: 'user', content: userMessageParts.length === 1 && userMessageParts[0].type === 'text' ? userMessageParts[0].text : userMessageParts });
|
|
779
|
+
}
|
|
780
|
+
if (components.retrievedContext) {
|
|
781
|
+
const ragContent = typeof components.retrievedContext === 'string' ? components.retrievedContext : components.retrievedContext.map(r => `Source: ${r.source}\nContent: ${r.content}`).join('\n\n');
|
|
782
|
+
if (messages.length > 0 && messages[messages.length - 1].role === 'user') {
|
|
783
|
+
const lastUserMsg = messages[messages.length - 1];
|
|
784
|
+
const newUserContent = `Context:\n${ragContent}\n\nUser Query: ${lastUserMsg.content}`;
|
|
785
|
+
messages[messages.length - 1].content = newUserContent;
|
|
786
|
+
}
|
|
787
|
+
else {
|
|
788
|
+
messages.push({ role: 'user', content: `Based on the following context:\n${ragContent}\n\nPlease respond to the implicit or explicit user query.` });
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
return messages;
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
createAnthropicMessagesTemplate() {
|
|
795
|
+
return async (components, modelInfo, _selectedElements, _config, _estimateTokenCountFn) => {
|
|
796
|
+
const messages = [];
|
|
797
|
+
let systemPrompt = '';
|
|
798
|
+
if (components.systemPrompts && components.systemPrompts.length > 0) {
|
|
799
|
+
systemPrompt = components.systemPrompts.map(p => p.content).join("\n\n").trim();
|
|
800
|
+
}
|
|
801
|
+
if (components.conversationHistory) {
|
|
802
|
+
components.conversationHistory.forEach(msg => {
|
|
803
|
+
let role = 'user';
|
|
804
|
+
if (msg.role === MessageRole.ASSISTANT)
|
|
805
|
+
role = 'assistant';
|
|
806
|
+
if (msg.role === MessageRole.USER || msg.role === MessageRole.ASSISTANT) {
|
|
807
|
+
const contentParts = []; // Use MessageContentPart
|
|
808
|
+
if (typeof msg.content === 'string') {
|
|
809
|
+
contentParts.push({ type: 'text', text: msg.content });
|
|
810
|
+
}
|
|
811
|
+
else if (Array.isArray(msg.content)) {
|
|
812
|
+
msg.content.forEach((part) => contentParts.push(part)); // Type assertion
|
|
813
|
+
}
|
|
814
|
+
messages.push({ role, content: contentParts });
|
|
815
|
+
}
|
|
816
|
+
else if (msg.role === MessageRole.TOOL) {
|
|
817
|
+
messages.push({
|
|
818
|
+
role: 'user',
|
|
819
|
+
content: [
|
|
820
|
+
{
|
|
821
|
+
type: 'tool_result',
|
|
822
|
+
tool_use_id: msg.tool_call_id,
|
|
823
|
+
content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
|
|
824
|
+
},
|
|
825
|
+
]
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
const currentUserInputParts = []; // Use MessageContentPart
|
|
831
|
+
if (components.userInput)
|
|
832
|
+
currentUserInputParts.push({ type: 'text', text: components.userInput });
|
|
833
|
+
if (components.visionInputs && modelInfo.visionSupport?.supported) {
|
|
834
|
+
components.visionInputs.forEach(vis => {
|
|
835
|
+
currentUserInputParts.push({
|
|
836
|
+
type: 'image', // Anthropic uses 'image' type for content block
|
|
837
|
+
source: {
|
|
838
|
+
type: vis.type === 'base64' ? 'base64' : 'url', // This is Anthropic's image source type
|
|
839
|
+
media_type: vis.mimeType || (vis.data.startsWith('data:image/jpeg') ? 'image/jpeg' : 'image/png'), // Corrected: vis.mimeType
|
|
840
|
+
data: vis.type === 'base64' ? vis.data : (vis.data.startsWith('data:') && vis.data.includes(',')) ? vis.data.split(',')[1] : vis.data
|
|
841
|
+
}
|
|
842
|
+
}); // Use 'as any' if 'image' type with 'source' is not yet in MessageContentPart
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
if (currentUserInputParts.length > 0) {
|
|
846
|
+
messages.push({ role: 'user', content: currentUserInputParts });
|
|
847
|
+
}
|
|
848
|
+
const formatted = { messages };
|
|
849
|
+
if (systemPrompt) {
|
|
850
|
+
formatted.system = systemPrompt;
|
|
851
|
+
}
|
|
852
|
+
if (components.tools && modelInfo.toolSupport.format === 'anthropic_tools') {
|
|
853
|
+
formatted.tools = this.formatToolSchemasForModel(components.tools, modelInfo);
|
|
854
|
+
}
|
|
855
|
+
return formatted;
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
createGenericCompletionTemplate() {
|
|
859
|
+
return async (components, _modelInfo, _selectedElements, _config, _estimateTokenCountFn) => {
|
|
860
|
+
let promptString = "";
|
|
861
|
+
if (components.systemPrompts)
|
|
862
|
+
promptString += components.systemPrompts.map(p => p.content).join("\n") + "\n\n";
|
|
863
|
+
if (components.conversationHistory) {
|
|
864
|
+
promptString += components.conversationHistory.map(m => `${m.role}: ${typeof m.content === 'string' ? m.content : JSON.stringify(m.content)}`).join("\n") + "\n\n";
|
|
865
|
+
}
|
|
866
|
+
if (components.userInput)
|
|
867
|
+
promptString += `user: ${components.userInput}\nassistant:`;
|
|
868
|
+
return promptString;
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
//# sourceMappingURL=PromptEngine.js.map
|