diff --git a/include/bolt/ai/ai_code_generator.hpp b/include/bolt/ai/ai_code_generator.hpp index 419d560a..08f09652 100644 --- a/include/bolt/ai/ai_code_generator.hpp +++ b/include/bolt/ai/ai_code_generator.hpp @@ -1,11 +1,12 @@ -#ifndef BOLT_AI_CODE_GENERATOR_HPP -#define BOLT_AI_CODE_GENERATOR_HPP +#ifndef BOLT_AI_AI_CODE_GENERATOR_HPP_ +#define BOLT_AI_AI_CODE_GENERATOR_HPP_ -#include -#include -#include #include +#include +#include #include +#include + #include "bolt/ai/ai_completion_provider.hpp" namespace bolt { @@ -39,48 +40,31 @@ struct GeneratedCode { * AI-powered code generator interface */ class AICodeGenerator { -public: + public: virtual ~AICodeGenerator() = default; - + // Function generation - virtual GeneratedCode generateFunction( - const std::string& description, - const CodeGenerationContext& context = {} - ) = 0; - + virtual GeneratedCode generateFunction(const std::string& description, + const CodeGenerationContext& context = {}) = 0; + // Class generation - virtual GeneratedCode generateClass( - const std::string& className, - const std::string& description, - const CodeGenerationContext& context = {} - ) = 0; - + virtual GeneratedCode generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context = {}) = 0; + // Method generation - virtual GeneratedCode generateMethod( - const std::string& methodName, - const std::string& description, - const std::string& className, - const CodeGenerationContext& context = {} - ) = 0; - + virtual GeneratedCode generateMethod(const std::string& methodName, const std::string& description, + const std::string& className, const CodeGenerationContext& context = {}) = 0; + // Template/boilerplate generation - virtual GeneratedCode generateTemplate( - const std::string& templateType, - const CodeGenerationContext& context = {} - ) = 0; - + virtual GeneratedCode generateTemplate(const std::string& templateType, + const CodeGenerationContext& context = {}) = 0; + // Documentation generation - virtual std::string generateDocumentation( - const std::string& code, - const CodeGenerationContext& context = {} - ) = 0; - + virtual std::string generateDocumentation(const std::string& code, const CodeGenerationContext& context = {}) = 0; + // Code explanation - virtual std::string explainCode( - const std::string& code, - const CodeGenerationContext& context = {} - ) = 0; - + virtual std::string explainCode(const std::string& code, const CodeGenerationContext& context = {}) = 0; + // Utility methods virtual bool isReady() const = 0; virtual bool initialize() = 0; @@ -91,62 +75,43 @@ class AICodeGenerator { * Template-based code generator for common patterns */ class TemplateCodeGenerator : public AICodeGenerator { -private: + private: struct CodeTemplate { std::string name; std::string pattern; std::vector placeholders; std::string description; }; - + std::unordered_map templates_; bool initialized_ = false; - + void loadDefaultTemplates(); - std::string processTemplate(const CodeTemplate& tmpl, - const std::unordered_map& values) const; - -public: + std::string processTemplate(const CodeTemplate& tmpl, + const std::unordered_map& values) const; + + public: TemplateCodeGenerator(); - + // AICodeGenerator interface - GeneratedCode generateFunction( - const std::string& description, - const CodeGenerationContext& context = {} - ) override; - - GeneratedCode generateClass( - const std::string& className, - const std::string& description, - const CodeGenerationContext& context = {} - ) override; - - GeneratedCode generateMethod( - const std::string& methodName, - const std::string& description, - const std::string& className, - const CodeGenerationContext& context = {} - ) override; - - GeneratedCode generateTemplate( - const std::string& templateType, - const CodeGenerationContext& context = {} - ) override; - - std::string generateDocumentation( - const std::string& code, - const CodeGenerationContext& context = {} - ) override; - - std::string explainCode( - const std::string& code, - const CodeGenerationContext& context = {} - ) override; - + GeneratedCode generateFunction(const std::string& description, const CodeGenerationContext& context = {}) override; + + GeneratedCode generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context = {}) override; + + GeneratedCode generateMethod(const std::string& methodName, const std::string& description, + const std::string& className, const CodeGenerationContext& context = {}) override; + + GeneratedCode generateTemplate(const std::string& templateType, const CodeGenerationContext& context = {}) override; + + std::string generateDocumentation(const std::string& code, const CodeGenerationContext& context = {}) override; + + std::string explainCode(const std::string& code, const CodeGenerationContext& context = {}) override; + bool isReady() const override { return initialized_; } bool initialize() override; void shutdown() override { initialized_ = false; } - + // Template management void addTemplate(const std::string& name, const CodeTemplate& tmpl); std::vector getAvailableTemplates() const; @@ -156,71 +121,55 @@ class TemplateCodeGenerator : public AICodeGenerator { * AI-enhanced code generator that uses AI completion providers */ class AIEnhancedCodeGenerator : public AICodeGenerator { -private: + private: std::unique_ptr aiProvider_; std::unique_ptr templateGenerator_; bool initialized_ = false; - - std::string createGenerationPrompt( - const std::string& type, - const std::string& description, - const CodeGenerationContext& context - ) const; - - GeneratedCode processAIResponse( - const std::vector& completions, - const std::string& generatorType - ) const; - -public: + + std::string createGenerationPrompt(const std::string& type, const std::string& description, + const CodeGenerationContext& context) const; + + GeneratedCode processAIResponse(const std::vector& completions, + const std::string& generatorType) const; + + public: AIEnhancedCodeGenerator(); explicit AIEnhancedCodeGenerator(std::unique_ptr provider); - + void setAIProvider(std::unique_ptr provider); - - // AICodeGenerator interface - GeneratedCode generateFunction( - const std::string& description, - const CodeGenerationContext& context = {} - ) override; - - GeneratedCode generateClass( - const std::string& className, - const std::string& description, - const CodeGenerationContext& context = {} - ) override; - - GeneratedCode generateMethod( - const std::string& methodName, - const std::string& description, - const std::string& className, - const CodeGenerationContext& context = {} - ) override; - - GeneratedCode generateTemplate( - const std::string& templateType, - const CodeGenerationContext& context = {} - ) override; - - std::string generateDocumentation( - const std::string& code, - const CodeGenerationContext& context = {} - ) override; - - std::string explainCode( - const std::string& code, - const CodeGenerationContext& context = {} - ) override; - + + // AICodeGenerator interface. Unless noted, a call asks the AI provider first when it is ready, and the template + // generator answers when the provider has nothing and fallback is enabled. + + // A function matching the description. + GeneratedCode generateFunction(const std::string& description, const CodeGenerationContext& context = {}) override; + + // A class called className. + GeneratedCode generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context = {}) override; + + // A method called methodName for the class className. + GeneratedCode generateMethod(const std::string& methodName, const std::string& description, + const std::string& className, const CodeGenerationContext& context = {}) override; + + // Never uses the AI provider: always produced by the template generator, whatever the fallback setting. + GeneratedCode generateTemplate(const std::string& templateType, const CodeGenerationContext& context = {}) override; + + // Documentation text for the code: the provider's first completion. + std::string generateDocumentation(const std::string& code, const CodeGenerationContext& context = {}) override; + + // An explanation of the code: the provider's first completion. + std::string explainCode(const std::string& code, const CodeGenerationContext& context = {}) override; + bool isReady() const override; bool initialize() override; void shutdown() override; - + // Configuration void setFallbackToTemplate(bool enabled) { fallbackToTemplate_ = enabled; } bool isFallbackToTemplateEnabled() const { return fallbackToTemplate_; } - -private: + + private: bool fallbackToTemplate_ = true; }; @@ -228,32 +177,28 @@ class AIEnhancedCodeGenerator : public AICodeGenerator { * Code generation service manager */ class CodeGenerationService { -private: + private: std::unique_ptr generator_; static std::unique_ptr instance_; - + CodeGenerationService() = default; - -public: + + public: static CodeGenerationService& getInstance(); - + void setGenerator(std::unique_ptr generator); AICodeGenerator* getGenerator() const { return generator_.get(); } - + // Convenience methods - GeneratedCode generateFunction(const std::string& description, - const CodeGenerationContext& context = {}); - GeneratedCode generateClass(const std::string& className, - const std::string& description, - const CodeGenerationContext& context = {}); - std::string generateDocumentation(const std::string& code, - const CodeGenerationContext& context = {}); - std::string explainCode(const std::string& code, - const CodeGenerationContext& context = {}); - + GeneratedCode generateFunction(const std::string& description, const CodeGenerationContext& context = {}); + GeneratedCode generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context = {}); + std::string generateDocumentation(const std::string& code, const CodeGenerationContext& context = {}); + std::string explainCode(const std::string& code, const CodeGenerationContext& context = {}); + bool isReady() const; }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_AI_CODE_GENERATOR_HPP \ No newline at end of file +#endif // BOLT_AI_AI_CODE_GENERATOR_HPP_ diff --git a/include/bolt/ai/ai_completion_provider.hpp b/include/bolt/ai/ai_completion_provider.hpp index 7e736771..f60ea4db 100644 --- a/include/bolt/ai/ai_completion_provider.hpp +++ b/include/bolt/ai/ai_completion_provider.hpp @@ -13,9 +13,9 @@ namespace bolt { struct CodeContext { std::string filePath; std::string content; - size_t cursorPosition; - size_t line; - size_t column; + size_t cursorPosition = 0; + size_t line = 0; + size_t column = 0; std::string language; }; diff --git a/include/bolt/ai/ai_refactoring_engine.hpp b/include/bolt/ai/ai_refactoring_engine.hpp index c340344a..3c72095f 100644 --- a/include/bolt/ai/ai_refactoring_engine.hpp +++ b/include/bolt/ai/ai_refactoring_engine.hpp @@ -1,13 +1,14 @@ -#ifndef BOLT_AI_REFACTORING_ENGINE_HPP -#define BOLT_AI_REFACTORING_ENGINE_HPP +#ifndef BOLT_AI_AI_REFACTORING_ENGINE_HPP_ +#define BOLT_AI_AI_REFACTORING_ENGINE_HPP_ -#include -#include -#include #include +#include #include -#include "bolt/core/code_analyzer.hpp" +#include +#include + #include "bolt/ai/ai_completion_provider.hpp" +#include "bolt/core/code_analyzer.hpp" namespace bolt { @@ -29,18 +30,18 @@ struct AIRefactoringSuggestion { std::string refactoringType; std::string aiReasoning; std::vector alternativeApproaches; - + // Priority and impact assessment enum class Priority { LOW, MEDIUM, HIGH, CRITICAL }; enum class Impact { MINIMAL, MODERATE, SIGNIFICANT, MAJOR }; - + Priority priority = Priority::MEDIUM; Impact impact = Impact::MODERATE; - + // Difficulty estimation enum class Difficulty { EASY, MODERATE, HARD, EXPERT }; Difficulty difficulty = Difficulty::MODERATE; - + // Estimated time to implement (in minutes) int estimatedTimeMinutes = 30; }; @@ -49,62 +50,42 @@ struct AIRefactoringSuggestion { * AI-powered refactoring suggestion engine */ class AIRefactoringEngine { -public: + public: virtual ~AIRefactoringEngine() = default; - + // Generate AI-enhanced refactoring suggestions - virtual std::vector generateSuggestions( - const std::string& code, - const std::string& filePath = "", - const std::string& language = "cpp" - ) = 0; - + virtual std::vector generateSuggestions(const std::string& code, + const std::string& filePath = "", + const std::string& language = "cpp") = 0; + // Analyze specific refactoring patterns - virtual std::vector findExtractMethodOpportunities( - const std::string& code, - const std::string& filePath = "" - ) = 0; - - virtual std::vector findComplexityReductions( - const std::string& code, - const std::string& filePath = "" - ) = 0; - - virtual std::vector findDuplicationRemoval( - const std::string& code, - const std::string& filePath = "" - ) = 0; - - virtual std::vector findDesignPatternOpportunities( - const std::string& code, - const std::string& filePath = "" - ) = 0; - + virtual std::vector findExtractMethodOpportunities(const std::string& code, + const std::string& filePath = "") = 0; + + virtual std::vector findComplexityReductions(const std::string& code, + const std::string& filePath = "") = 0; + + virtual std::vector findDuplicationRemoval(const std::string& code, + const std::string& filePath = "") = 0; + + virtual std::vector findDesignPatternOpportunities(const std::string& code, + const std::string& filePath = "") = 0; + // Performance-focused refactoring - virtual std::vector findPerformanceOptimizations( - const std::string& code, - const std::string& filePath = "" - ) = 0; - + virtual std::vector findPerformanceOptimizations(const std::string& code, + const std::string& filePath = "") = 0; + // Security-focused refactoring - virtual std::vector findSecurityImprovements( - const std::string& code, - const std::string& filePath = "" - ) = 0; - + virtual std::vector findSecurityImprovements(const std::string& code, + const std::string& filePath = "") = 0; + // Apply refactoring suggestion - virtual std::string applyRefactoring( - const std::string& code, - const AIRefactoringSuggestion& suggestion - ) = 0; - + virtual std::string applyRefactoring(const std::string& code, const AIRefactoringSuggestion& suggestion) = 0; + // Validate refactoring result - virtual bool validateRefactoring( - const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion - ) = 0; - + virtual bool validateRefactoring(const std::string& originalCode, const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion) = 0; + virtual bool isReady() const = 0; virtual bool initialize() = 0; virtual void shutdown() = 0; @@ -114,75 +95,53 @@ class AIRefactoringEngine { * Template-based refactoring engine with pattern recognition */ class TemplateRefactoringEngine : public AIRefactoringEngine { -private: + private: struct RefactoringPattern { std::string name; std::string description; std::regex pattern; std::function suggestionGenerator; }; - + std::vector patterns_; bool initialized_ = false; - + void loadDefaultPatterns(); - AIRefactoringSuggestion createExtractMethodSuggestion( - const std::smatch& match, const std::string& filePath) const; - AIRefactoringSuggestion createComplexityReductionSuggestion( - const std::smatch& match, const std::string& filePath) const; - AIRefactoringSuggestion createDuplicationRemovalSuggestion( - const std::smatch& match, const std::string& filePath) const; - -public: + AIRefactoringSuggestion createExtractMethodSuggestion(const std::smatch& match, const std::string& filePath) const; + AIRefactoringSuggestion createComplexityReductionSuggestion(const std::smatch& match, + const std::string& filePath) const; + AIRefactoringSuggestion createDuplicationRemovalSuggestion(const std::smatch& match, + const std::string& filePath) const; + + public: TemplateRefactoringEngine(); - - std::vector generateSuggestions( - const std::string& code, - const std::string& filePath = "", - const std::string& language = "cpp" - ) override; - - std::vector findExtractMethodOpportunities( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findComplexityReductions( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findDuplicationRemoval( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findDesignPatternOpportunities( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findPerformanceOptimizations( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findSecurityImprovements( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::string applyRefactoring( - const std::string& code, - const AIRefactoringSuggestion& suggestion - ) override; - - bool validateRefactoring( - const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion - ) override; - + + std::vector generateSuggestions(const std::string& code, const std::string& filePath = "", + const std::string& language = "cpp") override; + + std::vector findExtractMethodOpportunities(const std::string& code, + const std::string& filePath = "") override; + + std::vector findComplexityReductions(const std::string& code, + const std::string& filePath = "") override; + + std::vector findDuplicationRemoval(const std::string& code, + const std::string& filePath = "") override; + + std::vector findDesignPatternOpportunities(const std::string& code, + const std::string& filePath = "") override; + + std::vector findPerformanceOptimizations(const std::string& code, + const std::string& filePath = "") override; + + std::vector findSecurityImprovements(const std::string& code, + const std::string& filePath = "") override; + + std::string applyRefactoring(const std::string& code, const AIRefactoringSuggestion& suggestion) override; + + bool validateRefactoring(const std::string& originalCode, const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion) override; + bool isReady() const override { return initialized_; } bool initialize() override; void shutdown() override { initialized_ = false; } @@ -192,89 +151,69 @@ class TemplateRefactoringEngine : public AIRefactoringEngine { * AI-enhanced refactoring engine using AI completion providers */ class AIEnhancedRefactoringEngine : public AIRefactoringEngine { -private: + private: std::unique_ptr aiProvider_; std::unique_ptr templateEngine_; bool initialized_ = false; bool fallbackToTemplate_ = true; - - std::string createRefactoringPrompt( - const std::string& code, - const std::string& refactoringType, - const std::string& context = "" - ) const; - - std::vector processAIRefactoringResponse( - const std::vector& completions, - const std::string& originalCode, - const std::string& filePath, - const std::string& refactoringType - ) const; - - AIRefactoringSuggestion parseRefactoringSuggestion( - const std::string& response, - const std::string& originalCode, - const std::string& filePath, - const std::string& refactoringType - ) const; - -public: + + std::string createRefactoringPrompt(const std::string& code, const std::string& refactoringType, + const std::string& context = "") const; + + std::vector processAIRefactoringResponse(const std::vector& completions, + const std::string& originalCode, + const std::string& filePath, + const std::string& refactoringType) const; + + AIRefactoringSuggestion parseRefactoringSuggestion(const std::string& response, const std::string& originalCode, + const std::string& filePath, + const std::string& refactoringType) const; + + public: AIEnhancedRefactoringEngine(); explicit AIEnhancedRefactoringEngine(std::unique_ptr provider); - + void setAIProvider(std::unique_ptr provider); - - std::vector generateSuggestions( - const std::string& code, - const std::string& filePath = "", - const std::string& language = "cpp" - ) override; - - std::vector findExtractMethodOpportunities( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findComplexityReductions( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findDuplicationRemoval( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findDesignPatternOpportunities( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findPerformanceOptimizations( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::vector findSecurityImprovements( - const std::string& code, - const std::string& filePath = "" - ) override; - - std::string applyRefactoring( - const std::string& code, - const AIRefactoringSuggestion& suggestion - ) override; - - bool validateRefactoring( - const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion - ) override; - + + // The AI provider's suggestions when it is ready, followed by the template engine's when fallback is enabled. + std::vector generateSuggestions(const std::string& code, const std::string& filePath = "", + const std::string& language = "cpp") override; + + // Extract-method candidates; answered by the template engine (fallback enabled) even with an AI provider. + std::vector findExtractMethodOpportunities(const std::string& code, + const std::string& filePath = "") override; + + // Complexity reductions, from the template engine when fallback is enabled. + std::vector findComplexityReductions(const std::string& code, + const std::string& filePath = "") override; + + // Duplicated-code removal, from the template engine when fallback is enabled. + std::vector findDuplicationRemoval(const std::string& code, + const std::string& filePath = "") override; + + // Design-pattern opportunities, from the template engine when fallback is enabled. + std::vector findDesignPatternOpportunities(const std::string& code, + const std::string& filePath = "") override; + + // Performance optimizations, from the template engine when fallback is enabled. + std::vector findPerformanceOptimizations(const std::string& code, + const std::string& filePath = "") override; + + // Security improvements, from the template engine when fallback is enabled. + std::vector findSecurityImprovements(const std::string& code, + const std::string& filePath = "") override; + + // Applied by the template engine; returns the code unchanged when there is none. + std::string applyRefactoring(const std::string& code, const AIRefactoringSuggestion& suggestion) override; + + // Validated by the template engine; false when there is none. + bool validateRefactoring(const std::string& originalCode, const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion) override; + bool isReady() const override; bool initialize() override; void shutdown() override; - + // Configuration void setFallbackToTemplate(bool enabled) { fallbackToTemplate_ = enabled; } bool isFallbackToTemplateEnabled() const { return fallbackToTemplate_; } @@ -284,32 +223,29 @@ class AIEnhancedRefactoringEngine : public AIRefactoringEngine { * Refactoring service manager that integrates with the existing code analyzer */ class RefactoringService { -private: + private: std::unique_ptr engine_; static std::unique_ptr instance_; - + RefactoringService() = default; - -public: + + public: static RefactoringService& getInstance(); - + void setEngine(std::unique_ptr engine); AIRefactoringEngine* getEngine() const { return engine_.get(); } - + // Convenience methods - std::vector analyzeCode(const std::string& code, - const std::string& filePath = ""); + std::vector analyzeCode(const std::string& code, const std::string& filePath = ""); std::vector findAllOpportunities(const std::string& code, - const std::string& filePath = ""); - - std::string applyRefactoring(const std::string& code, - const AIRefactoringSuggestion& suggestion); - bool validateRefactoring(const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion); - + const std::string& filePath = ""); + + std::string applyRefactoring(const std::string& code, const AIRefactoringSuggestion& suggestion); + bool validateRefactoring(const std::string& originalCode, const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion); + bool isReady() const; - + // Statistics and reporting struct RefactoringStats { size_t totalSuggestionsGenerated = 0; @@ -317,14 +253,14 @@ class RefactoringService { size_t successfulRefactorings = 0; double averageConfidenceScore = 0.0; }; - + RefactoringStats getStatistics() const; void resetStatistics(); - -private: + + private: mutable RefactoringStats stats_; }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_AI_REFACTORING_ENGINE_HPP \ No newline at end of file +#endif // BOLT_AI_AI_REFACTORING_ENGINE_HPP_ diff --git a/include/bolt/ai/enhanced_ai_manager.hpp b/include/bolt/ai/enhanced_ai_manager.hpp index 5b614755..999d5664 100644 --- a/include/bolt/ai/enhanced_ai_manager.hpp +++ b/include/bolt/ai/enhanced_ai_manager.hpp @@ -91,6 +91,11 @@ class EnhancedAIManager { bool initialize_active_provider(); void update_stats(const bolt::drawkern::AIInferenceResponse& response); + // Copy of the stored history for session_id; empty when the id is empty or unknown. Never creates a session. + std::vector session_history_snapshot(const std::string& session_id) const; + // Answers with direct_inference_ (which must be set), records the exchange in the session and updates the stats. + bolt::drawkern::AIInferenceResponse chat_with_direct_inference(const std::string& message, + const std::string& session_id); }; // Auto-detection and setup utilities diff --git a/src/bolt/ai/ai_code_generator.cpp b/src/bolt/ai/ai_code_generator.cpp index 814950dc..28acab8e 100644 --- a/src/bolt/ai/ai_code_generator.cpp +++ b/src/bolt/ai/ai_code_generator.cpp @@ -1,10 +1,50 @@ #include "bolt/ai/ai_code_generator.hpp" + #include -#include +#include #include +#include namespace bolt { +namespace { + +// Asks a ready AI provider for up to maxSuggestions completions of the prompt, written in the given language. +std::vector requestCompletions(AICompletionProvider& provider, const std::string& prompt, + const std::string& language, size_t maxSuggestions) { + CodeContext aiContext; + aiContext.content = prompt; + aiContext.language = language; + aiContext.cursorPosition = prompt.length(); + + return provider.generateCompletions(aiContext, prompt, maxSuggestions); +} + +// The label of the provider's first completion for the prompt "instruction + code"; no value when the provider is +// missing, not ready or returns no completions. +std::optional firstCompletionLabel(AICompletionProvider* provider, const std::string& instruction, + const std::string& code, const std::string& language) { + if (provider && provider->isReady()) { + std::string prompt = instruction + code; + auto completions = requestCompletions(*provider, prompt, language, 1); + if (!completions.empty()) { + return completions[0].label; + } + } + return std::nullopt; +} + +// Result returned when neither the AI provider nor the template generator can produce code. +GeneratedCode makeUnavailableResult(const std::string& message) { + GeneratedCode result; + result.code = message; + result.confidence = 0.0; + result.generatorType = "none"; + return result; +} + +} // namespace + // TemplateCodeGenerator implementation TemplateCodeGenerator::TemplateCodeGenerator() { loadDefaultTemplates(); @@ -59,7 +99,8 @@ class {CLASS_NAME} { {BODY} return {DEFAULT_RETURN}; })"; - methodTemplate.placeholders = {"DESCRIPTION", "RETURN_TYPE", "CLASS_NAME", "METHOD_NAME", "PARAMETERS", "BODY", "DEFAULT_RETURN"}; + methodTemplate.placeholders = {"DESCRIPTION", "RETURN_TYPE", "CLASS_NAME", "METHOD_NAME", + "PARAMETERS", "BODY", "DEFAULT_RETURN"}; templates_["cpp_method"] = methodTemplate; // Header Guard Template @@ -90,36 +131,32 @@ bool TemplateCodeGenerator::initialize() { return initialized_; } -std::string TemplateCodeGenerator::processTemplate( - const CodeTemplate& tmpl, - const std::unordered_map& values) const { - +std::string TemplateCodeGenerator::processTemplate(const CodeTemplate& tmpl, + const std::unordered_map& values) const { std::string result = tmpl.pattern; - + for (const auto& placeholder : tmpl.placeholders) { std::string token = "{" + placeholder + "}"; auto it = values.find(placeholder); std::string replacement = (it != values.end()) ? it->second : "/* TODO: " + placeholder + " */"; - + size_t pos = 0; while ((pos = result.find(token, pos)) != std::string::npos) { result.replace(pos, token.length(), replacement); pos += replacement.length(); } } - + return result; } -GeneratedCode TemplateCodeGenerator::generateFunction( - const std::string& description, - const CodeGenerationContext& context) { - +GeneratedCode TemplateCodeGenerator::generateFunction(const std::string& description, + const CodeGenerationContext& context) { GeneratedCode result; result.generatorType = "template"; result.confidence = 0.8; result.description = "Generated function from template"; - + std::unordered_map values; values["DESCRIPTION"] = description.empty() ? "Generated function" : description; values["RETURN_TYPE"] = context.language == "cpp" ? "void" : "void"; @@ -127,7 +164,7 @@ GeneratedCode TemplateCodeGenerator::generateFunction( values["PARAMETERS"] = ""; values["BODY"] = " // TODO: Implement function logic"; values["DEFAULT_RETURN"] = context.language == "cpp" ? "" : ""; - + // Try to extract function name from description std::regex namePattern(R"(\b(\w+)\s*function|\bfunction\s+(\w+)|\b(\w+)\(\))"); std::smatch match; @@ -139,49 +176,43 @@ GeneratedCode TemplateCodeGenerator::generateFunction( } } } - + result.code = processTemplate(templates_.at("cpp_function"), values); result.suggestions.push_back("Consider adding parameter validation"); result.suggestions.push_back("Add proper error handling"); - + return result; } -GeneratedCode TemplateCodeGenerator::generateClass( - const std::string& className, - const std::string& description, - const CodeGenerationContext& context) { - +GeneratedCode TemplateCodeGenerator::generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context) { GeneratedCode result; result.generatorType = "template"; result.confidence = 0.8; result.description = "Generated class from template"; - + std::unordered_map values; values["DESCRIPTION"] = description.empty() ? "Generated class" : description; values["CLASS_NAME"] = className.empty() ? "GeneratedClass" : className; values["PRIVATE_MEMBERS"] = " // TODO: Add private member variables"; values["PUBLIC_METHODS"] = " // TODO: Add public methods"; - + result.code = processTemplate(templates_.at("cpp_class"), values); result.suggestions.push_back("Consider using RAII principles"); result.suggestions.push_back("Add copy/move constructors if needed"); result.suggestions.push_back("Consider making destructor virtual if inheritance is expected"); - + return result; } -GeneratedCode TemplateCodeGenerator::generateMethod( - const std::string& methodName, - const std::string& description, - const std::string& className, - const CodeGenerationContext& context) { - +GeneratedCode TemplateCodeGenerator::generateMethod(const std::string& methodName, const std::string& description, + const std::string& className, + const CodeGenerationContext& context) { GeneratedCode result; result.generatorType = "template"; result.confidence = 0.8; result.description = "Generated method from template"; - + std::unordered_map values; values["DESCRIPTION"] = description.empty() ? "Generated method" : description; values["RETURN_TYPE"] = "void"; @@ -190,36 +221,34 @@ GeneratedCode TemplateCodeGenerator::generateMethod( values["PARAMETERS"] = ""; values["BODY"] = " // TODO: Implement method logic"; values["DEFAULT_RETURN"] = ""; - + result.code = processTemplate(templates_.at("cpp_method"), values); result.suggestions.push_back("Consider const-correctness"); result.suggestions.push_back("Add parameter validation"); - + return result; } -GeneratedCode TemplateCodeGenerator::generateTemplate( - const std::string& templateType, - const CodeGenerationContext& context) { - +GeneratedCode TemplateCodeGenerator::generateTemplate(const std::string& templateType, + const CodeGenerationContext& context) { GeneratedCode result; result.generatorType = "template"; result.confidence = 0.9; - + if (templates_.find(templateType) != templates_.end()) { std::unordered_map values; - + if (templateType == "header_guard") { std::string guardName = context.fileType; std::transform(guardName.begin(), guardName.end(), guardName.begin(), ::toupper); std::replace(guardName.begin(), guardName.end(), '.', '_'); - + values["GUARD_NAME"] = guardName + "_HPP"; values["INCLUDES"] = "#include \n#include "; values["NAMESPACE"] = "bolt"; values["CONTENT"] = "// TODO: Add your declarations here"; } - + result.code = processTemplate(templates_.at(templateType), values); result.description = "Generated " + templateType + " template"; } else { @@ -227,19 +256,17 @@ GeneratedCode TemplateCodeGenerator::generateTemplate( result.description = "Template not available"; result.confidence = 0.1; } - + return result; } -std::string TemplateCodeGenerator::generateDocumentation( - const std::string& code, - const CodeGenerationContext& context) { - +std::string TemplateCodeGenerator::generateDocumentation(const std::string& code, + const CodeGenerationContext& context) { std::ostringstream doc; doc << "/**\n"; doc << " * Auto-generated documentation\n"; doc << " * \n"; - + // Simple analysis of the code to generate basic documentation if (code.find("class ") != std::string::npos) { doc << " * This class provides functionality for code management.\n"; @@ -253,43 +280,40 @@ std::string TemplateCodeGenerator::generateDocumentation( } else { doc << " * Code documentation\n"; } - + doc << " */"; return doc.str(); } -std::string TemplateCodeGenerator::explainCode( - const std::string& code, - const CodeGenerationContext& context) { - +std::string TemplateCodeGenerator::explainCode(const std::string& code, const CodeGenerationContext& context) { std::ostringstream explanation; explanation << "Code Explanation:\n\n"; - + // Basic pattern recognition if (code.find("class ") != std::string::npos) { explanation << "This code defines a C++ class. Classes are fundamental building blocks "; explanation << "in object-oriented programming that encapsulate data and behavior.\n\n"; } - + if (code.find("public:") != std::string::npos) { explanation << "The 'public:' section contains members that can be accessed from outside the class.\n\n"; } - + if (code.find("private:") != std::string::npos) { explanation << "The 'private:' section contains members that can only be accessed from within the class.\n\n"; } - + if (code.find("for") != std::string::npos) { explanation << "This code contains a for loop, which is used for iterative operations.\n\n"; } - + if (code.find("if") != std::string::npos) { explanation << "This code contains conditional logic using if statements.\n\n"; } - + explanation << "Note: This is a basic template-based explanation. "; explanation << "For more detailed analysis, consider using an AI-powered explanation service."; - + return explanation.str(); } @@ -306,14 +330,10 @@ std::vector TemplateCodeGenerator::getAvailableTemplates() const { } // AIEnhancedCodeGenerator implementation -AIEnhancedCodeGenerator::AIEnhancedCodeGenerator() - : templateGenerator_(std::make_unique()) { -} +AIEnhancedCodeGenerator::AIEnhancedCodeGenerator() : templateGenerator_(std::make_unique()) {} AIEnhancedCodeGenerator::AIEnhancedCodeGenerator(std::unique_ptr provider) - : aiProvider_(std::move(provider)) - , templateGenerator_(std::make_unique()) { -} + : aiProvider_(std::move(provider)), templateGenerator_(std::make_unique()) {} void AIEnhancedCodeGenerator::setAIProvider(std::unique_ptr provider) { aiProvider_ = std::move(provider); @@ -321,23 +341,22 @@ void AIEnhancedCodeGenerator::setAIProvider(std::unique_ptrinitialize(); } - + if (aiProvider_) { result &= aiProvider_->initialize(); } - + initialized_ = result; return result; } bool AIEnhancedCodeGenerator::isReady() const { - return initialized_ && - ((aiProvider_ && aiProvider_->isReady()) || - (fallbackToTemplate_ && templateGenerator_ && templateGenerator_->isReady())); + return initialized_ && ((aiProvider_ && aiProvider_->isReady()) || + (fallbackToTemplate_ && templateGenerator_ && templateGenerator_->isReady())); } void AIEnhancedCodeGenerator::shutdown() { @@ -350,47 +369,42 @@ void AIEnhancedCodeGenerator::shutdown() { initialized_ = false; } -std::string AIEnhancedCodeGenerator::createGenerationPrompt( - const std::string& type, - const std::string& description, - const CodeGenerationContext& context) const { - +std::string AIEnhancedCodeGenerator::createGenerationPrompt(const std::string& type, const std::string& description, + const CodeGenerationContext& context) const { std::ostringstream prompt; prompt << "Generate " << type << " in " << context.language << ":\n"; prompt << "Description: " << description << "\n"; - + if (!context.projectContext.empty()) { prompt << "Project context: " << context.projectContext << "\n"; } - + if (!context.existingCode.empty()) { prompt << "Existing code context:\n" << context.existingCode << "\n"; } - + if (!context.requirements.empty()) { prompt << "Requirements:\n"; for (const auto& req : context.requirements) { prompt << "- " << req << "\n"; } } - + prompt << "\nPlease provide clean, well-documented code following best practices."; - + return prompt.str(); } -GeneratedCode AIEnhancedCodeGenerator::processAIResponse( - const std::vector& completions, - const std::string& generatorType) const { - +GeneratedCode AIEnhancedCodeGenerator::processAIResponse(const std::vector& completions, + const std::string& generatorType) const { GeneratedCode result; result.generatorType = "ai_enhanced"; - + if (!completions.empty()) { result.code = completions[0].label; result.confidence = completions[0].score; result.description = "AI-generated code"; - + // Extract suggestions from other completions for (size_t i = 1; i < std::min(completions.size(), static_cast(3)); ++i) { result.suggestions.push_back("Alternative: " + completions[i].label.substr(0, 50) + "..."); @@ -400,174 +414,108 @@ GeneratedCode AIEnhancedCodeGenerator::processAIResponse( result.confidence = 0.0; result.description = "AI generation failed"; } - + return result; } -GeneratedCode AIEnhancedCodeGenerator::generateFunction( - const std::string& description, - const CodeGenerationContext& context) { - +GeneratedCode AIEnhancedCodeGenerator::generateFunction(const std::string& description, + const CodeGenerationContext& context) { if (aiProvider_ && aiProvider_->isReady()) { std::string prompt = createGenerationPrompt("function", description, context); - - CodeContext aiContext; - aiContext.content = prompt; - aiContext.language = context.language; - aiContext.cursorPosition = prompt.length(); - - auto completions = aiProvider_->generateCompletions(aiContext, prompt, 3); + auto completions = requestCompletions(*aiProvider_, prompt, context.language, 3); if (!completions.empty()) { return processAIResponse(completions, "function"); } } - + // Fallback to template generation if (fallbackToTemplate_ && templateGenerator_) { auto result = templateGenerator_->generateFunction(description, context); result.description += " (fallback to template)"; return result; } - - GeneratedCode result; - result.code = "// Code generation not available"; - result.confidence = 0.0; - result.generatorType = "none"; - return result; + + return makeUnavailableResult("// Code generation not available"); } -GeneratedCode AIEnhancedCodeGenerator::generateClass( - const std::string& className, - const std::string& description, - const CodeGenerationContext& context) { - +GeneratedCode AIEnhancedCodeGenerator::generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context) { if (aiProvider_ && aiProvider_->isReady()) { std::string prompt = createGenerationPrompt("class named " + className, description, context); - - CodeContext aiContext; - aiContext.content = prompt; - aiContext.language = context.language; - aiContext.cursorPosition = prompt.length(); - - auto completions = aiProvider_->generateCompletions(aiContext, prompt, 3); + auto completions = requestCompletions(*aiProvider_, prompt, context.language, 3); if (!completions.empty()) { return processAIResponse(completions, "class"); } } - + // Fallback to template generation if (fallbackToTemplate_ && templateGenerator_) { auto result = templateGenerator_->generateClass(className, description, context); result.description += " (fallback to template)"; return result; } - - GeneratedCode result; - result.code = "// Code generation not available"; - result.confidence = 0.0; - result.generatorType = "none"; - return result; + + return makeUnavailableResult("// Code generation not available"); } -GeneratedCode AIEnhancedCodeGenerator::generateMethod( - const std::string& methodName, - const std::string& description, - const std::string& className, - const CodeGenerationContext& context) { - +GeneratedCode AIEnhancedCodeGenerator::generateMethod(const std::string& methodName, const std::string& description, + const std::string& className, + const CodeGenerationContext& context) { if (aiProvider_ && aiProvider_->isReady()) { - std::string prompt = createGenerationPrompt("method " + methodName + " for class " + className, description, context); - - CodeContext aiContext; - aiContext.content = prompt; - aiContext.language = context.language; - aiContext.cursorPosition = prompt.length(); - - auto completions = aiProvider_->generateCompletions(aiContext, prompt, 3); + std::string prompt = + createGenerationPrompt("method " + methodName + " for class " + className, description, context); + auto completions = requestCompletions(*aiProvider_, prompt, context.language, 3); if (!completions.empty()) { return processAIResponse(completions, "method"); } } - + // Fallback to template generation if (fallbackToTemplate_ && templateGenerator_) { auto result = templateGenerator_->generateMethod(methodName, description, className, context); result.description += " (fallback to template)"; return result; } - - GeneratedCode result; - result.code = "// Code generation not available"; - result.confidence = 0.0; - result.generatorType = "none"; - return result; + + return makeUnavailableResult("// Code generation not available"); } -GeneratedCode AIEnhancedCodeGenerator::generateTemplate( - const std::string& templateType, - const CodeGenerationContext& context) { - +GeneratedCode AIEnhancedCodeGenerator::generateTemplate(const std::string& templateType, + const CodeGenerationContext& context) { // Template generation always falls back to template generator if (templateGenerator_) { return templateGenerator_->generateTemplate(templateType, context); } - - GeneratedCode result; - result.code = "// Template generation not available"; - result.confidence = 0.0; - result.generatorType = "none"; - return result; + + return makeUnavailableResult("// Template generation not available"); } -std::string AIEnhancedCodeGenerator::generateDocumentation( - const std::string& code, - const CodeGenerationContext& context) { - - if (aiProvider_ && aiProvider_->isReady()) { - std::string prompt = "Generate comprehensive documentation for this code:\n\n" + code; - - CodeContext aiContext; - aiContext.content = prompt; - aiContext.language = context.language; - aiContext.cursorPosition = prompt.length(); - - auto completions = aiProvider_->generateCompletions(aiContext, prompt, 1); - if (!completions.empty()) { - return completions[0].label; - } +std::string AIEnhancedCodeGenerator::generateDocumentation(const std::string& code, + const CodeGenerationContext& context) { + if (auto text = firstCompletionLabel(aiProvider_.get(), "Generate comprehensive documentation for this code:\n\n", + code, context.language)) { + return *text; } - + // Fallback to template generation if (fallbackToTemplate_ && templateGenerator_) { return templateGenerator_->generateDocumentation(code, context); } - + return "// Documentation generation not available"; } -std::string AIEnhancedCodeGenerator::explainCode( - const std::string& code, - const CodeGenerationContext& context) { - - if (aiProvider_ && aiProvider_->isReady()) { - std::string prompt = "Explain this code in detail:\n\n" + code; - - CodeContext aiContext; - aiContext.content = prompt; - aiContext.language = context.language; - aiContext.cursorPosition = prompt.length(); - - auto completions = aiProvider_->generateCompletions(aiContext, prompt, 1); - if (!completions.empty()) { - return completions[0].label; - } +std::string AIEnhancedCodeGenerator::explainCode(const std::string& code, const CodeGenerationContext& context) { + if (auto text = + firstCompletionLabel(aiProvider_.get(), "Explain this code in detail:\n\n", code, context.language)) { + return *text; } - + // Fallback to template generation if (fallbackToTemplate_ && templateGenerator_) { return templateGenerator_->explainCode(code, context); } - + return "Code explanation not available"; } @@ -590,54 +538,44 @@ void CodeGenerationService::setGenerator(std::unique_ptr genera } } -GeneratedCode CodeGenerationService::generateFunction( - const std::string& description, - const CodeGenerationContext& context) { - +GeneratedCode CodeGenerationService::generateFunction(const std::string& description, + const CodeGenerationContext& context) { if (generator_) { return generator_->generateFunction(description, context); } - + GeneratedCode result; result.code = "// Code generation service not available"; result.confidence = 0.0; return result; } -GeneratedCode CodeGenerationService::generateClass( - const std::string& className, - const std::string& description, - const CodeGenerationContext& context) { - +GeneratedCode CodeGenerationService::generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context) { if (generator_) { return generator_->generateClass(className, description, context); } - + GeneratedCode result; result.code = "// Code generation service not available"; result.confidence = 0.0; return result; } -std::string CodeGenerationService::generateDocumentation( - const std::string& code, - const CodeGenerationContext& context) { - +std::string CodeGenerationService::generateDocumentation(const std::string& code, + const CodeGenerationContext& context) { if (generator_) { return generator_->generateDocumentation(code, context); } - + return "// Documentation generation service not available"; } -std::string CodeGenerationService::explainCode( - const std::string& code, - const CodeGenerationContext& context) { - +std::string CodeGenerationService::explainCode(const std::string& code, const CodeGenerationContext& context) { if (generator_) { return generator_->explainCode(code, context); } - + return "Code explanation service not available"; } @@ -645,4 +583,4 @@ bool CodeGenerationService::isReady() const { return generator_ && generator_->isReady(); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/ai/enhanced_ai_manager.cpp b/src/bolt/ai/enhanced_ai_manager.cpp index 1dfa36e4..813bceb4 100644 --- a/src/bolt/ai/enhanced_ai_manager.cpp +++ b/src/bolt/ai/enhanced_ai_manager.cpp @@ -1,28 +1,30 @@ #include "bolt/ai/enhanced_ai_manager.hpp" -#include "bolt/ai/ai_http_client.hpp" -#include "bolt/ai/direct_gguf_inference.hpp" + #include #include #include +#include "bolt/ai/ai_http_client.hpp" +#include "bolt/ai/direct_gguf_inference.hpp" + namespace bolt { namespace ai { // New GGUF direct loading methods bool EnhancedAIManager::load_gguf_model(const std::string& model_path) { std::cout << "📥 Loading GGUF model: " << model_path << std::endl; - + if (!direct_inference_) { direct_inference_ = std::make_unique(); } - + if (direct_inference_->load_model(model_path)) { use_direct_inference_ = true; current_provider_ = "direct_gguf"; std::cout << "✅ GGUF model loaded successfully!" << std::endl; return true; } - + std::cout << "❌ Failed to load GGUF model" << std::endl; return false; } @@ -43,7 +45,7 @@ std::string EnhancedAIManager::get_model_info() const { bool EnhancedAIManager::auto_detect_models() { std::cout << "🔍 Auto-detecting GGUF models..." << std::endl; - + direct_inference_ = bolt::ai::DirectGGUFFactory::create_auto_detect(); if (direct_inference_->is_loaded()) { use_direct_inference_ = true; @@ -51,22 +53,22 @@ bool EnhancedAIManager::auto_detect_models() { std::cout << "✅ Auto-detected and loaded GGUF model!" << std::endl; return true; } - + std::cout << "⚠️ No GGUF models found for auto-detection" << std::endl; return false; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt namespace bolt { namespace ai { EnhancedAIManager::EnhancedAIManager() { config_manager_ = std::make_unique(); - + std::cout << "🔧 Initializing Enhanced AI Manager..." << std::endl; - + // Try direct GGUF inference first direct_inference_ = bolt::ai::DirectGGUFFactory::create_auto_detect(); if (direct_inference_->is_loaded()) { @@ -75,14 +77,14 @@ EnhancedAIManager::EnhancedAIManager() { std::cout << "✅ Direct GGUF model loaded - using direct inference!" << std::endl; } else { std::cout << "📋 No direct models found, loading HTTP providers..." << std::endl; - + // Load configuration config_manager_->load_config(); - + // Initialize with active provider initialize_active_provider(); } - + std::cout << "✅ Enhanced AI Manager initialized" << std::endl; } @@ -95,14 +97,13 @@ EnhancedAIManager::~EnhancedAIManager() { bool EnhancedAIManager::initialize_active_provider() { std::string active_provider = config_manager_->get_active_provider(); bolt::ai::AIHttpConfig config = config_manager_->get_active_config(); - + try { http_client_ = std::make_unique(config); current_provider_ = active_provider; - - std::cout << "🔄 Initialized AI provider: " << active_provider - << " (" << config.base_url << ")" << std::endl; - + + std::cout << "🔄 Initialized AI provider: " << active_provider << " (" << config.base_url << ")" << std::endl; + return true; } catch (const std::exception& e) { std::cerr << "❌ Failed to initialize AI provider: " << e.what() << std::endl; @@ -110,67 +111,69 @@ bool EnhancedAIManager::initialize_active_provider() { } } +std::vector EnhancedAIManager::session_history_snapshot(const std::string& session_id) const { + std::vector history; + if (!session_id.empty()) { + auto it = session_history_.find(session_id); + if (it != session_history_.end()) { + history = it->second; + } + } + return history; +} + +bolt::drawkern::AIInferenceResponse EnhancedAIManager::chat_with_direct_inference(const std::string& message, + const std::string& session_id) { + auto response = direct_inference_->chat(message, session_history_snapshot(session_id)); + if (!session_id.empty()) { + session_history_[session_id].push_back("Human: " + message); + if (response.success) + session_history_[session_id].push_back("AI: " + response.response); + } + update_stats(response); + return response; +} + bolt::drawkern::AIInferenceResponse EnhancedAIManager::chat(const std::string& message, const std::string& session_id) { // Use direct GGUF inference if available and loaded if (use_direct_inference_ && direct_inference_ && direct_inference_->is_loaded()) { - std::vector history; - if (!session_id.empty() && session_history_.find(session_id) != session_history_.end()) { - history = session_history_[session_id]; - } - auto response = direct_inference_->chat(message, history); - if (!session_id.empty()) { - session_history_[session_id].push_back("Human: " + message); - if (response.success) session_history_[session_id].push_back("AI: " + response.response); - } - update_stats(response); - return response; + return chat_with_direct_inference(message, session_id); } // Minimal RWKV direct stub: not a real inference; returns helpful message if (use_rwkv_direct_ && !rwkv_model_path_.empty()) { bolt::drawkern::AIInferenceResponse response; response.success = true; - response.response = "[RWKV stub] Model loaded: " + rwkv_model_path_ + ". Real RWKV generation will be added next phase."; + response.response = + "[RWKV stub] Model loaded: " + rwkv_model_path_ + ". Real RWKV generation will be added next phase."; update_stats(response); return response; } - + // Try HTTP client if (http_client_) { - if (!session_id.empty()) session_history_[session_id].push_back("Human: " + message); + if (!session_id.empty()) + session_history_[session_id].push_back("Human: " + message); auto response = http_client_->chat(message, session_id); if (!response.success && direct_inference_) { std::cout << "🔄 HTTP failed, using intelligent fallback..." << std::endl; - std::vector history; - if (!session_id.empty() && session_history_.find(session_id) != session_history_.end()) { - history = session_history_[session_id]; - } - response = direct_inference_->chat(message, history); + response = direct_inference_->chat(message, session_history_snapshot(session_id)); } if (response.success && !session_id.empty()) { session_history_[session_id].push_back("AI: " + response.response); auto& history = session_history_[session_id]; - if (history.size() > 40) history.erase(history.begin(), history.begin() + (history.size() - 40)); + if (history.size() > 40) + history.erase(history.begin(), history.begin() + (history.size() - 40)); } update_stats(response); return response; } - + // Final fallback to direct inference (even without loaded model) if (direct_inference_) { - std::vector history; - if (!session_id.empty() && session_history_.find(session_id) != session_history_.end()) { - history = session_history_[session_id]; - } - auto response = direct_inference_->chat(message, history); - if (!session_id.empty()) { - session_history_[session_id].push_back("Human: " + message); - if (response.success) session_history_[session_id].push_back("AI: " + response.response); - } - update_stats(response); - return response; + return chat_with_direct_inference(message, session_id); } - + bolt::drawkern::AIInferenceResponse error_response; error_response.error = "No AI provider available"; error_response.success = false; @@ -178,7 +181,8 @@ bolt::drawkern::AIInferenceResponse EnhancedAIManager::chat(const std::string& m return error_response; } -bolt::drawkern::AIInferenceResponse EnhancedAIManager::complete_code(const std::string& code, const std::string& language) { +bolt::drawkern::AIInferenceResponse EnhancedAIManager::complete_code(const std::string& code, + const std::string& language) { if (!http_client_) { bolt::drawkern::AIInferenceResponse error_response; error_response.error = "No AI provider initialized"; @@ -190,17 +194,19 @@ bolt::drawkern::AIInferenceResponse EnhancedAIManager::complete_code(const std:: return response; } -bolt::drawkern::AIInferenceResponse EnhancedAIManager::analyze_code(const std::string& code, const std::string& language) { - std::string analysis_prompt = "Please analyze this " + language + " code and provide feedback:\n\n" + code + - "\n\nPlease provide:\n1. Code quality assessment\n2. Potential improvements\n3. Any bugs or issues\n4. Best practices suggestions"; +bolt::drawkern::AIInferenceResponse EnhancedAIManager::analyze_code(const std::string& code, + const std::string& language) { + std::string analysis_prompt = "Please analyze this " + language + " code and provide feedback:\n\n" + code + + "\n\nPlease provide:\n1. Code quality assessment\n2. Potential improvements\n3. Any " + "bugs or issues\n4. Best practices suggestions"; return chat(analysis_prompt, "analysis_session"); } bool EnhancedAIManager::switch_provider(const std::string& provider_name) { - if (!config_manager_->list_providers().size() || - std::find(config_manager_->list_providers().begin(), - config_manager_->list_providers().end(), - provider_name) == config_manager_->list_providers().end()) { + // list_providers() returns a new vector each time, so keep one copy: + // iterators taken from different calls must not be compared. + const auto providers = config_manager_->list_providers(); + if (std::find(providers.begin(), providers.end(), provider_name) == providers.end()) { std::cerr << "❌ Provider not found: " << provider_name << std::endl; return false; } @@ -224,7 +230,8 @@ bool EnhancedAIManager::test_all_providers() { for (const auto& [name, success] : results) { std::string status = success ? "✅ Working" : "❌ Failed"; std::cout << " " << name << ": " << status << std::endl; - if (success) any_working = true; + if (success) + any_working = true; } if (!any_working) { std::cout << "\n⚠️ No working AI providers found!" << std::endl; @@ -324,7 +331,8 @@ void EnhancedAIManager::update_stats(const bolt::drawkern::AIInferenceResponse& stats_.total_tokens_generated += response.tokens_generated; stats_.total_tokens_processed += response.tokens_processed; if (stats_.successful_requests > 0) { - float total_time = stats_.average_inference_time_ms * (stats_.successful_requests - 1) + response.inference_time_ms; + float total_time = + stats_.average_inference_time_ms * (stats_.successful_requests - 1) + response.inference_time_ms; stats_.average_inference_time_ms = total_time / stats_.successful_requests; } } else { @@ -391,7 +399,7 @@ bool quick_setup_wizard() { return found; } -} // namespace AutoSetup +} // namespace AutoSetup -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/koboldcpp_provider.cpp b/src/bolt/ai/koboldcpp_provider.cpp index 5264087f..1697a472 100644 --- a/src/bolt/ai/koboldcpp_provider.cpp +++ b/src/bolt/ai/koboldcpp_provider.cpp @@ -1,10 +1,11 @@ #include "bolt/ai/koboldcpp_provider.hpp" -#include -#include + #include #include -#include #include +#include +#include +#include #ifdef BOLT_HAVE_CURL #include @@ -26,12 +27,164 @@ static size_t KoboldWriteCallback(void* contents, size_t size, size_t nmemb, std } #endif +namespace { + +// Writes text to out with the characters ", \, newline, carriage return and tab escaped for a JSON string. +void appendJsonEscaped(std::ostream& out, const std::string& text) { + for (char c : text) { + switch (c) { + case '"': + out << "\\\""; + break; + case '\\': + out << "\\\\"; + break; + case '\n': + out << "\\n"; + break; + case '\r': + out << "\\r"; + break; + case '\t': + out << "\\t"; + break; + default: + out << c; + break; + } + } +} + +#ifdef BOLT_HAVE_JSONCPP +// What a reply reader is given: the parsed reply with jsoncpp, the raw reply text without it. +using ReplySource = Json::Value; + +// Parses a JSON document; on failure returns false and leaves the parser's message in errors. +bool parseJson(const std::string& text, Json::Value& root, std::string& errors) { + Json::CharReaderBuilder builder; + std::istringstream s(text); + return Json::parseFromStream(builder, s, &root, &errors); +} + +// First element of the array member root[key]; nullptr when the member is missing, not an array or empty. +const Json::Value* firstArrayElement(const Json::Value& root, const char* key) { + if (root.isMember(key) && root[key].isArray() && root[key].size() > 0) { + return &root[key][0]; + } + return nullptr; +} +#else +using ReplySource = std::string; + +// Without jsoncpp: copies what follows key_prefix (for example "text":") up to the next double quote into +// result.text and marks the result successful; leaves result untouched when either end is missing. +void extractStringField(const std::string& response_str, const std::string& key_prefix, KoboldCppResponse& result) { + auto pos = response_str.find(key_prefix); + if (pos != std::string::npos) { + pos += key_prefix.size(); + auto end_pos = response_str.find("\"", pos); + if (end_pos != std::string::npos) { + result.text = response_str.substr(pos, end_pos - pos); + result.success = true; + } + } +} +#endif + +// Reads the reply of /v1/completions into result. +void readOpenAICompletionReply(const ReplySource& reply, KoboldCppResponse& result) { +#ifdef BOLT_HAVE_JSONCPP + if (const Json::Value* choice = firstArrayElement(reply, "choices")) { + result.text = choice->get("text", "").asString(); + result.success = true; + } + if (reply.isMember("usage")) { + result.tokens_used = reply["usage"].get("total_tokens", 0).asInt(); + } + if (reply.isMember("model")) { + result.model_name = reply["model"].asString(); + } +#else + // Simple text extraction without jsoncpp + extractStringField(reply, "\"text\":\"", result); + if (!result.success) { + result.error = "No jsoncpp available and simple parse failed"; + } +#endif +} + +// Reads the reply of /v1/chat/completions into result. +void readOpenAIChatReply(const ReplySource& reply, KoboldCppResponse& result) { +#ifdef BOLT_HAVE_JSONCPP + if (const Json::Value* choice = firstArrayElement(reply, "choices")) { + if (choice->isMember("message")) { + result.text = (*choice)["message"].get("content", "").asString(); + } else { + result.text = choice->get("text", "").asString(); + } + result.success = true; + } + if (reply.isMember("model")) { + result.model_name = reply["model"].asString(); + } +#else + extractStringField(reply, "\"content\":\"", result); +#endif +} + +// Reads the reply of the KoboldAI native /api/v1/generate into result. +void readKoboldAIGenerateReply(const ReplySource& reply, KoboldCppResponse& result) { +#ifdef BOLT_HAVE_JSONCPP + if (const Json::Value* generated = firstArrayElement(reply, "results")) { + result.text = generated->get("text", "").asString(); + result.success = true; + } +#else + extractStringField(reply, "\"text\":\"", result); +#endif +} + +// Builds the response for a POST started at start: the elapsed time, then the "empty response" error, the JSON +// parse error, or whatever read_reply takes from the server's reply. +KoboldCppResponse finishRequest(std::chrono::high_resolution_clock::time_point start, const std::string& response_str, + void (*read_reply)(const ReplySource&, KoboldCppResponse&)) { + KoboldCppResponse result; + auto end = std::chrono::high_resolution_clock::now(); + result.latency_ms = std::chrono::duration(end - start).count(); + + if (response_str.empty()) { + result.success = false; + result.error = "Empty response from server"; + return result; + } + +#ifdef BOLT_HAVE_JSONCPP + Json::Value root; + std::string errors; + if (!parseJson(response_str, root, errors)) { + result.error = "JSON parse error: " + errors; + } else if (!root.isObject()) { + // Valid JSON, but not the object every endpoint replies with (for + // example a bare array or string). Looking up members in it throws. + result.success = false; + result.error = "Unexpected response from server: not a JSON object"; + } else { + read_reply(root, result); + } +#else + read_reply(response_str, result); +#endif + + return result; +} + +} // namespace + // ── Constructors / Destructor ────────────────────────────────── KoboldCppProvider::KoboldCppProvider() = default; -KoboldCppProvider::KoboldCppProvider(const KoboldCppConfig& config) - : config_(config) {} +KoboldCppProvider::KoboldCppProvider(const KoboldCppConfig& config) : config_(config) {} KoboldCppProvider::KoboldCppProvider(const std::string& endpoint) { config_.endpoint = endpoint; @@ -48,8 +201,9 @@ bool KoboldCppProvider::isReady() const { } bool KoboldCppProvider::initialize() { - if (initialized_) return true; - + if (initialized_) + return true; + // Test connection and detect API mode if (test_connection()) { if (config_.api_mode == KoboldCppConfig::APIMode::AUTO_DETECT) { @@ -67,22 +221,19 @@ void KoboldCppProvider::shutdown() { initialized_ = false; } -std::vector KoboldCppProvider::generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions) -{ +std::vector KoboldCppProvider::generateCompletions(const CodeContext& context, + const std::string& prefix, size_t maxSuggestions) { if (!initialized_) { return {}; } - + std::string prompt = build_code_prompt(context, prefix); auto response = complete(prompt, std::min(config_.max_tokens, 100)); - + if (!response.success || response.text.empty()) { return {}; } - + return parse_completions(response.text, maxSuggestions); } @@ -93,9 +244,8 @@ KoboldCppResponse KoboldCppProvider::complete(const std::string& prompt) { } KoboldCppResponse KoboldCppProvider::complete(const std::string& prompt, int max_tokens) { - auto mode = (config_.api_mode == KoboldCppConfig::APIMode::AUTO_DETECT) - ? detected_mode_ : config_.api_mode; - + auto mode = (config_.api_mode == KoboldCppConfig::APIMode::AUTO_DETECT) ? detected_mode_ : config_.api_mode; + if (mode == KoboldCppConfig::APIMode::KOBOLDAI_NATIVE) { return send_koboldai_generate(prompt, max_tokens); } @@ -109,16 +259,15 @@ KoboldCppResponse KoboldCppProvider::chat(const std::string& message) { } KoboldCppResponse KoboldCppProvider::chat(const std::string& message, const std::string& system_prompt) { - std::vector> messages; + std::vector> messages; messages.push_back({"system", system_prompt}); messages.push_back({"user", message}); return chat(messages); } -KoboldCppResponse KoboldCppProvider::chat(const std::vector>& messages) { - auto mode = (config_.api_mode == KoboldCppConfig::APIMode::AUTO_DETECT) - ? detected_mode_ : config_.api_mode; - +KoboldCppResponse KoboldCppProvider::chat(const std::vector>& messages) { + auto mode = (config_.api_mode == KoboldCppConfig::APIMode::AUTO_DETECT) ? detected_mode_ : config_.api_mode; + if (mode == KoboldCppConfig::APIMode::KOBOLDAI_NATIVE) { // Build a prompt from messages for the native API std::ostringstream prompt; @@ -142,25 +291,29 @@ KoboldCppResponse KoboldCppProvider::chat(const std::vector> word) { - if (!callback(word + " ")) return false; + if (!callback(word + " ")) + return false; } return true; } bool KoboldCppProvider::chat_streaming(const std::string& message, StreamCallback callback) { auto response = chat(message); - if (!response.success) return false; - + if (!response.success) + return false; + std::istringstream stream(response.text); std::string word; while (stream >> word) { - if (!callback(word + " ")) return false; + if (!callback(word + " ")) + return false; } return true; } @@ -175,50 +328,44 @@ bool KoboldCppProvider::test_connection() { KoboldCppServerInfo KoboldCppProvider::get_server_info() { KoboldCppServerInfo info; - + // Try /api/extra/version std::string version_response = http_get(config_.endpoint + "/api/extra/version"); if (!version_response.empty()) { info.connected = true; #ifdef BOLT_HAVE_JSONCPP Json::Value root; - Json::CharReaderBuilder builder; - std::istringstream s(version_response); std::string errors; - if (Json::parseFromStream(builder, s, &root, &errors)) { + if (parseJson(version_response, root, errors)) { info.version = root.get("result", "unknown").asString(); } #endif } - + // Try /api/extra/true_max_context_length std::string ctx_response = http_get(config_.endpoint + "/api/extra/true_max_context_length"); if (!ctx_response.empty()) { #ifdef BOLT_HAVE_JSONCPP Json::Value root; - Json::CharReaderBuilder builder; - std::istringstream s(ctx_response); std::string errors; - if (Json::parseFromStream(builder, s, &root, &errors)) { + if (parseJson(ctx_response, root, errors)) { info.max_context_length = root.get("value", 0).asInt(); } #endif } - + // Try /api/v1/model std::string model_response = http_get(config_.endpoint + "/api/v1/model"); if (!model_response.empty()) { #ifdef BOLT_HAVE_JSONCPP Json::Value root; - Json::CharReaderBuilder builder; - std::istringstream s(model_response); std::string errors; - if (Json::parseFromStream(builder, s, &root, &errors)) { + if (parseJson(model_response, root, errors)) { info.model_name = root.get("result", "unknown").asString(); } #endif } - + return info; } @@ -231,7 +378,7 @@ bool KoboldCppProvider::is_model_loaded() { void KoboldCppProvider::set_config(const KoboldCppConfig& config) { config_ = config; - initialized_ = false; // Force re-initialization + initialized_ = false; // Force re-initialization } void KoboldCppProvider::set_endpoint(const std::string& endpoint) { @@ -242,226 +389,67 @@ void KoboldCppProvider::set_endpoint(const std::string& endpoint) { // ── Internal: OpenAI-compatible API ──────────────────────────── KoboldCppResponse KoboldCppProvider::send_openai_completion(const std::string& prompt, int max_tokens) { - KoboldCppResponse result; auto start = std::chrono::high_resolution_clock::now(); - + std::ostringstream json; json << "{\"prompt\":\""; // Escape the prompt for JSON - for (char c : prompt) { - switch (c) { - case '"': json << "\\\""; break; - case '\\': json << "\\\\"; break; - case '\n': json << "\\n"; break; - case '\r': json << "\\r"; break; - case '\t': json << "\\t"; break; - default: json << c; break; - } - } - json << "\",\"max_tokens\":" << max_tokens - << ",\"temperature\":" << config_.temperature + appendJsonEscaped(json, prompt); + json << "\",\"max_tokens\":" << max_tokens << ",\"temperature\":" << config_.temperature << ",\"top_p\":" << config_.top_p; - + if (!config_.stop_sequences.empty()) { json << ",\"stop\":["; for (size_t i = 0; i < config_.stop_sequences.size(); ++i) { - if (i > 0) json << ","; + if (i > 0) + json << ","; json << "\"" << config_.stop_sequences[i] << "\""; } json << "]"; } json << "}"; - + std::string url = config_.endpoint + "/v1/completions"; std::string response_str = http_post(url, json.str()); - - auto end = std::chrono::high_resolution_clock::now(); - result.latency_ms = std::chrono::duration(end - start).count(); - - if (response_str.empty()) { - result.success = false; - result.error = "Empty response from server"; - return result; - } - -#ifdef BOLT_HAVE_JSONCPP - Json::Value root; - Json::CharReaderBuilder builder; - std::istringstream s(response_str); - std::string errors; - if (Json::parseFromStream(builder, s, &root, &errors)) { - if (root.isMember("choices") && root["choices"].isArray() && root["choices"].size() > 0) { - result.text = root["choices"][0].get("text", "").asString(); - result.success = true; - } - if (root.isMember("usage")) { - result.tokens_used = root["usage"].get("total_tokens", 0).asInt(); - } - if (root.isMember("model")) { - result.model_name = root["model"].asString(); - } - } else { - result.error = "JSON parse error: " + errors; - } -#else - // Simple text extraction without jsoncpp - auto pos = response_str.find("\"text\":\""); - if (pos != std::string::npos) { - pos += 8; - auto end_pos = response_str.find("\"", pos); - if (end_pos != std::string::npos) { - result.text = response_str.substr(pos, end_pos - pos); - result.success = true; - } - } - if (!result.success) { - result.error = "No jsoncpp available and simple parse failed"; - } -#endif - - return result; + return finishRequest(start, response_str, readOpenAICompletionReply); } KoboldCppResponse KoboldCppProvider::send_openai_chat( - const std::vector>& messages) -{ - KoboldCppResponse result; + const std::vector>& messages) { auto start = std::chrono::high_resolution_clock::now(); - + std::ostringstream json; json << "{\"messages\":["; for (size_t i = 0; i < messages.size(); ++i) { - if (i > 0) json << ","; + if (i > 0) + json << ","; json << "{\"role\":\"" << messages[i].first << "\",\"content\":\""; - for (char c : messages[i].second) { - switch (c) { - case '"': json << "\\\""; break; - case '\\': json << "\\\\"; break; - case '\n': json << "\\n"; break; - case '\r': json << "\\r"; break; - case '\t': json << "\\t"; break; - default: json << c; break; - } - } + appendJsonEscaped(json, messages[i].second); json << "\"}"; } - json << "],\"max_tokens\":" << config_.max_tokens - << ",\"temperature\":" << config_.temperature - << "}"; - + json << "],\"max_tokens\":" << config_.max_tokens << ",\"temperature\":" << config_.temperature << "}"; + std::string url = config_.endpoint + "/v1/chat/completions"; std::string response_str = http_post(url, json.str()); - - auto end = std::chrono::high_resolution_clock::now(); - result.latency_ms = std::chrono::duration(end - start).count(); - - if (response_str.empty()) { - result.success = false; - result.error = "Empty response from server"; - return result; - } - -#ifdef BOLT_HAVE_JSONCPP - Json::Value root; - Json::CharReaderBuilder builder; - std::istringstream s(response_str); - std::string errors; - if (Json::parseFromStream(builder, s, &root, &errors)) { - if (root.isMember("choices") && root["choices"].isArray() && root["choices"].size() > 0) { - auto& choice = root["choices"][0]; - if (choice.isMember("message")) { - result.text = choice["message"].get("content", "").asString(); - } else { - result.text = choice.get("text", "").asString(); - } - result.success = true; - } - if (root.isMember("model")) { - result.model_name = root["model"].asString(); - } - } else { - result.error = "JSON parse error: " + errors; - } -#else - auto pos = response_str.find("\"content\":\""); - if (pos != std::string::npos) { - pos += 11; - auto end_pos = response_str.find("\"", pos); - if (end_pos != std::string::npos) { - result.text = response_str.substr(pos, end_pos - pos); - result.success = true; - } - } -#endif - - return result; + return finishRequest(start, response_str, readOpenAIChatReply); } // ── Internal: KoboldAI native API ────────────────────────────── KoboldCppResponse KoboldCppProvider::send_koboldai_generate(const std::string& prompt, int max_tokens) { - KoboldCppResponse result; auto start = std::chrono::high_resolution_clock::now(); - + std::ostringstream json; json << "{\"prompt\":\""; - for (char c : prompt) { - switch (c) { - case '"': json << "\\\""; break; - case '\\': json << "\\\\"; break; - case '\n': json << "\\n"; break; - case '\r': json << "\\r"; break; - case '\t': json << "\\t"; break; - default: json << c; break; - } - } - json << "\",\"max_context_length\":" << config_.max_context_length - << ",\"max_length\":" << max_tokens - << ",\"temperature\":" << config_.temperature - << ",\"top_k\":" << config_.top_k - << ",\"top_p\":" << config_.top_p - << ",\"rep_pen\":" << config_.rep_pen - << ",\"rep_pen_range\":" << config_.rep_pen_range - << "}"; - + appendJsonEscaped(json, prompt); + json << "\",\"max_context_length\":" << config_.max_context_length << ",\"max_length\":" << max_tokens + << ",\"temperature\":" << config_.temperature << ",\"top_k\":" << config_.top_k + << ",\"top_p\":" << config_.top_p << ",\"rep_pen\":" << config_.rep_pen + << ",\"rep_pen_range\":" << config_.rep_pen_range << "}"; + std::string url = config_.endpoint + "/api/v1/generate"; std::string response_str = http_post(url, json.str()); - - auto end = std::chrono::high_resolution_clock::now(); - result.latency_ms = std::chrono::duration(end - start).count(); - - if (response_str.empty()) { - result.success = false; - result.error = "Empty response from server"; - return result; - } - -#ifdef BOLT_HAVE_JSONCPP - Json::Value root; - Json::CharReaderBuilder builder; - std::istringstream s(response_str); - std::string errors; - if (Json::parseFromStream(builder, s, &root, &errors)) { - if (root.isMember("results") && root["results"].isArray() && root["results"].size() > 0) { - result.text = root["results"][0].get("text", "").asString(); - result.success = true; - } - } else { - result.error = "JSON parse error: " + errors; - } -#else - auto pos = response_str.find("\"text\":\""); - if (pos != std::string::npos) { - pos += 8; - auto end_pos = response_str.find("\"", pos); - if (end_pos != std::string::npos) { - result.text = response_str.substr(pos, end_pos - pos); - result.success = true; - } - } -#endif - - return result; + return finishRequest(start, response_str, readKoboldAIGenerateReply); } // ── Internal: HTTP helpers ───────────────────────────────────── @@ -469,25 +457,26 @@ KoboldCppResponse KoboldCppProvider::send_koboldai_generate(const std::string& p std::string KoboldCppProvider::http_post(const std::string& url, const std::string& json_body) { #ifdef BOLT_HAVE_CURL CURL* curl = curl_easy_init(); - if (!curl) return ""; - + if (!curl) + return ""; + std::string response; struct curl_slist* headers = nullptr; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Accept: application/json"); - + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_body.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, KoboldWriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); - curl_easy_setopt(curl, CURLOPT_TIMEOUT, static_cast(config_.timeout_seconds)); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, static_cast(config_.timeout_seconds)); // NOLINT(runtime/int) curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); - + CURLcode res = curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); - + if (res != CURLE_OK) { return ""; } @@ -495,26 +484,28 @@ std::string KoboldCppProvider::http_post(const std::string& url, const std::stri #else (void)url; (void)json_body; - return ""; // No CURL support + return ""; // No CURL support #endif } std::string KoboldCppProvider::http_get(const std::string& url) { #ifdef BOLT_HAVE_CURL CURL* curl = curl_easy_init(); - if (!curl) return ""; - + if (!curl) + return ""; + std::string response; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, KoboldWriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3L); - + CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); - - if (res != CURLE_OK) return ""; + + if (res != CURLE_OK) + return ""; return response; #else (void)url; @@ -528,33 +519,33 @@ std::string KoboldCppProvider::build_code_prompt(const CodeContext& context, con std::ostringstream prompt; prompt << "// Language: " << context.language << "\n"; prompt << "// File: " << context.filePath << "\n"; - + // Include surrounding context (up to 500 chars before cursor) size_t start = (context.cursorPosition > 500) ? context.cursorPosition - 500 : 0; std::string before = context.content.substr(start, context.cursorPosition - start); - + prompt << before << prefix; return prompt.str(); } -std::vector KoboldCppProvider::parse_completions( - const std::string& response_text, size_t max) const -{ +std::vector KoboldCppProvider::parse_completions(const std::string& response_text, size_t max) const { std::vector items; - + // Split response into lines and create completion items std::istringstream stream(response_text); std::string line; size_t count = 0; - + while (std::getline(stream, line) && count < max) { // Trim whitespace size_t start = line.find_first_not_of(" \t\r\n"); - if (start == std::string::npos) continue; + if (start == std::string::npos) + continue; line = line.substr(start); - - if (line.empty()) continue; - + + if (line.empty()) + continue; + CompletionItem item; item.label = line.substr(0, std::min(line.size(), size_t(60))); item.detail = "KoboldCpp AI suggestion"; @@ -563,7 +554,7 @@ std::vector KoboldCppProvider::parse_completions( items.push_back(item); count++; } - + // If no line breaks, treat the whole response as one completion if (items.empty() && !response_text.empty()) { CompletionItem item; @@ -573,7 +564,7 @@ std::vector KoboldCppProvider::parse_completions( item.score = 100; items.push_back(item); } - + return items; } @@ -600,18 +591,18 @@ bool KoboldCppProvider::detect_api_mode() { detected_mode_ = KoboldCppConfig::APIMode::OPENAI_COMPATIBLE; return true; } - + // Fall back to KoboldAI native test = http_get(config_.endpoint + "/api/v1/model"); if (!test.empty() && test.find("error") == std::string::npos) { detected_mode_ = KoboldCppConfig::APIMode::KOBOLDAI_NATIVE; return true; } - + // Default to OpenAI-compatible detected_mode_ = KoboldCppConfig::APIMode::OPENAI_COMPATIBLE; return false; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/rwkv_wrapper.cpp b/src/bolt/ai/rwkv_wrapper.cpp index d81d9f82..1fbca00f 100644 --- a/src/bolt/ai/rwkv_wrapper.cpp +++ b/src/bolt/ai/rwkv_wrapper.cpp @@ -1,85 +1,116 @@ #include "bolt/ai/rwkv_wrapper.hpp" -#include -#include -#include + #include +#include #include +#include +#include namespace bolt { +namespace { + +// The tensor stored under name, or nullptr when the model has no such weight. +ggml_tensor* findWeight(const std::unordered_map& weights, const std::string& name) { + auto it = weights.find(name); + return it != weights.end() ? it->second : nullptr; +} + +// The previous token's embedding kept in the state for the layer; a new zero tensor for the first token, or when +// there is no state for the layer. +ggml_tensor* previousTokenOrZeros(ggml_context* ctx, const RWKVState* state, int layer_idx, int n_embd) { + ggml_tensor* last_x = + state && static_cast(layer_idx) < state->state_pp_.size() ? state->state_pp_[layer_idx] : nullptr; + + if (!last_x) { + // First token, use zeros + last_x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); + ggml_set_zero(last_x); + } + return last_x; +} + +// Interpolates the current and the previous token, x * mix + last_x * (1 - mix), built as last_x + (x - last_x) * mix. +ggml_tensor* mixWithPrevious(ggml_context* ctx, ggml_tensor* x, ggml_tensor* last_x, ggml_tensor* mix) { + auto* x_diff = ggml_sub(ctx, x, last_x); + auto* x_diff_scaled = ggml_mul(ctx, x_diff, mix); + return ggml_add(ctx, last_x, x_diff_scaled); +} + +} // namespace + void RWKVWrapper::initialize(const std::string& model_path, int ctx_size) { model_path_ = model_path; - + std::cout << "Initializing RWKV model from: " << model_path << std::endl; - + // Create GGUF loader gguf_loader_ = std::make_unique(model_path); - + // Load the GGUF file if (!gguf_loader_->load()) { throw std::runtime_error("Failed to load GGUF file: " + gguf_loader_->getError()); } - + std::cout << "GGUF file loaded successfully" << std::endl; std::cout << " Version: " << gguf_loader_->getVersion() << std::endl; std::cout << " Architecture: " << gguf_loader_->getArchitecture() << std::endl; - + // Extract model parameters n_layers_ = gguf_loader_->getNumLayers(); n_embd_ = gguf_loader_->getEmbedDim(); n_vocab_ = gguf_loader_->getVocabSize(); - + if (n_layers_ == 0 || n_embd_ == 0 || n_vocab_ == 0) { throw std::runtime_error("Invalid model parameters: n_layers=" + std::to_string(n_layers_) + - ", n_embd=" + std::to_string(n_embd_) + - ", n_vocab=" + std::to_string(n_vocab_)); + ", n_embd=" + std::to_string(n_embd_) + ", n_vocab=" + std::to_string(n_vocab_)); } - + std::cout << "Model parameters:" << std::endl; std::cout << " Layers: " << n_layers_ << std::endl; std::cout << " Embedding dim: " << n_embd_ << std::endl; std::cout << " Vocabulary size: " << n_vocab_ << std::endl; - + // Initialize tokenizer tokenizer_ = std::make_unique(); auto tokens = gguf_loader_->getMetadataStringArray("tokenizer.ggml.tokens"); auto scores = gguf_loader_->getMetadataFloatArray("tokenizer.ggml.scores"); - + if (tokens.empty()) { throw std::runtime_error("No tokenizer vocabulary found in model file"); } - + if (!tokenizer_->loadVocabulary(tokens, scores)) { throw std::runtime_error("Failed to load tokenizer vocabulary"); } - + // Calculate required memory - size_t mem_size = ctx_size * 1024 * 1024; // Convert MB to bytes - + size_t mem_size = ctx_size * 1024 * 1024; // Convert MB to bytes + // Create GGML context context_ = std::make_unique(mem_size); - + // Load model weights loadModel(model_path); - + // Initialize state state_ = std::make_unique(context_->get(), n_layers_, n_embd_); - + // Initialize random number generator std::random_device rd; rng_ = std::mt19937(rd()); - + model_loaded_ = true; std::cout << "RWKV model initialized successfully" << std::endl; } void RWKVWrapper::loadModel(const std::string& path) { std::cout << "Loading model weights..." << std::endl; - + // Get list of all tensors auto tensor_names = gguf_loader_->getTensorNames(); std::cout << "Found " << tensor_names.size() << " tensors in model file" << std::endl; - + // Load each tensor int loaded_count = 0; for (const auto& name : tensor_names) { @@ -91,15 +122,12 @@ void RWKVWrapper::loadModel(const std::string& path) { std::cerr << "Warning: Failed to load tensor: " << name << std::endl; } } - + std::cout << "Loaded " << loaded_count << " / " << tensor_names.size() << " tensors" << std::endl; - + // Verify essential weights are present - std::vector essential_weights = { - "token_embd.weight", - "output.weight" - }; - + std::vector essential_weights = {"token_embd.weight", "output.weight"}; + for (const auto& weight_name : essential_weights) { if (weights_.find(weight_name) == weights_.end()) { // Try alternative names @@ -118,7 +146,7 @@ std::vector RWKVWrapper::tokenize(const std::string& text) const { if (tokenizer_ && tokenizer_->isLoaded()) { return tokenizer_->encode(text); } - + // Fallback to character-level tokenization std::vector tokens; for (char c : text) { @@ -131,7 +159,7 @@ std::string RWKVWrapper::detokenize(const std::vector& tokens) const { if (tokenizer_ && tokenizer_->isLoaded()) { return tokenizer_->decode(tokens); } - + // Fallback to character-level detokenization std::string text; for (int token : tokens) { @@ -146,62 +174,59 @@ std::string RWKVWrapper::generate(const std::string& prompt, size_t max_tokens) return generateImproved(prompt, max_tokens, 1.0f, 0.95f); } -std::string RWKVWrapper::generateImproved(const std::string& prompt, size_t max_tokens, - float temperature, float top_p) { +std::string RWKVWrapper::generateImproved(const std::string& prompt, size_t max_tokens, float temperature, + float top_p) { if (!model_loaded_) { throw std::runtime_error("RWKV model not initialized"); } - + // Tokenize the prompt auto prompt_tokens = tokenize(prompt); - + if (prompt_tokens.empty()) { throw std::runtime_error("Empty prompt after tokenization"); } - - std::cout << "Generating " << max_tokens << " tokens (prompt: " - << prompt_tokens.size() << " tokens)" << std::endl; - + + std::cout << "Generating " << max_tokens << " tokens (prompt: " << prompt_tokens.size() << " tokens)" << std::endl; + std::vector generated_tokens = prompt_tokens; - + // Generation loop for (size_t i = 0; i < max_tokens; ++i) { // Create input tensor from last token int last_token = generated_tokens.back(); auto* input = ggml_new_tensor_1d(context_->get(), GGML_TYPE_I32, 1); memcpy(input->data, &last_token, sizeof(int)); - + // Forward pass through the model auto* logits = forwardWithLogits(input); - + if (!logits) { std::cerr << "Forward pass failed at token " << i << std::endl; break; } - + // Sample next token int next_token = sampleToken(logits, temperature, top_p); - + // Check for end of sequence - if (tokenizer_ && (next_token == tokenizer_->getEOSToken() || - next_token == tokenizer_->getPADToken())) { + if (tokenizer_ && (next_token == tokenizer_->getEOSToken() || next_token == tokenizer_->getPADToken())) { std::cout << "EOS token generated at position " << i << std::endl; break; } - + generated_tokens.push_back(next_token); - + // Progress indicator if ((i + 1) % 10 == 0) { std::cout << "." << std::flush; } } - + std::cout << std::endl; - + // Remove prompt tokens and return only generated text - std::vector output_tokens(generated_tokens.begin() + prompt_tokens.size(), - generated_tokens.end()); + std::vector output_tokens(generated_tokens.begin() + prompt_tokens.size(), generated_tokens.end()); return detokenize(output_tokens); } @@ -209,15 +234,15 @@ ggml_tensor* RWKVWrapper::forwardWithLogits(ggml_tensor* input) { if (!model_loaded_) { throw std::runtime_error("RWKV model not initialized"); } - + // Get input embeddings auto* current = getEmbeddings(input); - + if (!current) { std::cerr << "Failed to get embeddings" << std::endl; return nullptr; } - + // Process through RWKV layers for (int i = 0; i < n_layers_; i++) { current = rwkvLayer(current, i); @@ -226,31 +251,31 @@ ggml_tensor* RWKVWrapper::forwardWithLogits(ggml_tensor* input) { return nullptr; } } - + // Final layer norm current = layerNorm(current, "ln_out.weight", "ln_out.bias"); - + // Project to vocabulary logits auto* logits = projectToVocab(current); - + return logits; } ggml_tensor* RWKVWrapper::getEmbeddings(ggml_tensor* input) { // Look for embedding weight ggml_tensor* emb_weight = nullptr; - + if (weights_.find("token_embd.weight") != weights_.end()) { emb_weight = weights_["token_embd.weight"]; } else if (weights_.find("emb.weight") != weights_.end()) { emb_weight = weights_["emb.weight"]; } - + if (!emb_weight) { std::cerr << "Embedding weight not found" << std::endl; return nullptr; } - + // Use GGML's get_rows operation to extract embeddings return ggml_get_rows(context_->get(), emb_weight, input); } @@ -258,7 +283,7 @@ ggml_tensor* RWKVWrapper::getEmbeddings(ggml_tensor* input) { ggml_tensor* RWKVWrapper::projectToVocab(ggml_tensor* hidden) { // Look for output weight ggml_tensor* output_weight = nullptr; - + if (weights_.find("output.weight") != weights_.end()) { output_weight = weights_["output.weight"]; } else if (weights_.find("head.weight") != weights_.end()) { @@ -267,12 +292,12 @@ ggml_tensor* RWKVWrapper::projectToVocab(ggml_tensor* hidden) { // Weight tying: use embedding weights output_weight = weights_["token_embd.weight"]; } - + if (!output_weight) { std::cerr << "Output weight not found" << std::endl; return nullptr; } - + // Matrix multiplication: hidden @ output_weight^T return ggml_mul_mat(context_->get(), output_weight, hidden); } @@ -281,94 +306,72 @@ ggml_tensor* RWKVWrapper::rwkvLayer(ggml_tensor* x, int layer_idx) { // Time-mixing (attention-like mechanism) std::string ln1_weight = "blk." + std::to_string(layer_idx) + ".ln1.weight"; std::string ln1_bias = "blk." + std::to_string(layer_idx) + ".ln1.bias"; - + auto* x_norm = layerNorm(x, ln1_weight, ln1_bias); auto* tm_out = timeMixing(x_norm, layer_idx); - + // Residual connection auto* x1 = ggml_add(context_->get(), x, tm_out); - + // Channel-mixing (FFN-like mechanism) std::string ln2_weight = "blk." + std::to_string(layer_idx) + ".ln2.weight"; std::string ln2_bias = "blk." + std::to_string(layer_idx) + ".ln2.bias"; - + auto* x1_norm = layerNorm(x1, ln2_weight, ln2_bias); auto* cm_out = channelMixing(x1_norm, layer_idx); - + // Residual connection auto* output = ggml_add(context_->get(), x1, cm_out); - + return output; } ggml_tensor* RWKVWrapper::timeMixing(ggml_tensor* x, int layer_idx) { // RWKV time-mixing with WKV (Weighted Key-Value) operation std::string prefix = "blk." + std::to_string(layer_idx) + ".att."; - + // Get time-mixing weights - ggml_tensor* time_mix_k = weights_.find(prefix + "time_mix_k") != weights_.end() ? - weights_[prefix + "time_mix_k"] : nullptr; - ggml_tensor* time_mix_v = weights_.find(prefix + "time_mix_v") != weights_.end() ? - weights_[prefix + "time_mix_v"] : nullptr; - ggml_tensor* time_mix_r = weights_.find(prefix + "time_mix_r") != weights_.end() ? - weights_[prefix + "time_mix_r"] : nullptr; - + ggml_tensor* time_mix_k = findWeight(weights_, prefix + "time_mix_k"); + ggml_tensor* time_mix_v = findWeight(weights_, prefix + "time_mix_v"); + ggml_tensor* time_mix_r = findWeight(weights_, prefix + "time_mix_r"); + // Get weight matrices - ggml_tensor* Wk = weights_.find(prefix + "key.weight") != weights_.end() ? - weights_[prefix + "key.weight"] : nullptr; - ggml_tensor* Wv = weights_.find(prefix + "value.weight") != weights_.end() ? - weights_[prefix + "value.weight"] : nullptr; - ggml_tensor* Wr = weights_.find(prefix + "receptance.weight") != weights_.end() ? - weights_[prefix + "receptance.weight"] : nullptr; - ggml_tensor* Wout = weights_.find(prefix + "output.weight") != weights_.end() ? - weights_[prefix + "output.weight"] : nullptr; - + ggml_tensor* Wk = findWeight(weights_, prefix + "key.weight"); + ggml_tensor* Wv = findWeight(weights_, prefix + "value.weight"); + ggml_tensor* Wr = findWeight(weights_, prefix + "receptance.weight"); + ggml_tensor* Wout = findWeight(weights_, prefix + "output.weight"); + // Get decay and bonus parameters - ggml_tensor* time_decay = weights_.find(prefix + "time_decay") != weights_.end() ? - weights_[prefix + "time_decay"] : nullptr; - ggml_tensor* time_first = weights_.find(prefix + "time_first") != weights_.end() ? - weights_[prefix + "time_first"] : nullptr; - + ggml_tensor* time_decay = findWeight(weights_, prefix + "time_decay"); + ggml_tensor* time_first = findWeight(weights_, prefix + "time_first"); + // If weights not found, return input unchanged if (!time_mix_k || !time_mix_v || !time_mix_r || !Wk || !Wv || !Wr || !Wout) { return x; } - + // Get previous token state (state_pp_) - ggml_tensor* last_x = state_ && static_cast(layer_idx) < state_->state_pp_.size() ? - state_->state_pp_[layer_idx] : nullptr; - - if (!last_x) { - // First token, use zeros - last_x = ggml_new_tensor_1d(context_->get(), GGML_TYPE_F32, n_embd_); - ggml_set_zero(last_x); - } - + ggml_tensor* last_x = previousTokenOrZeros(context_->get(), state_.get(), layer_idx, n_embd_); + // Interpolate current and previous token: x * mix + last_x * (1 - mix) // Rewritten as: last_x + (x - last_x) * mix - auto* x_diff_k = ggml_sub(context_->get(), x, last_x); - auto* x_diff_k_scaled = ggml_mul(context_->get(), x_diff_k, time_mix_k); - auto* xk_interp = ggml_add(context_->get(), last_x, x_diff_k_scaled); - - auto* x_diff_v = ggml_sub(context_->get(), x, last_x); - auto* x_diff_v_scaled = ggml_mul(context_->get(), x_diff_v, time_mix_v); - auto* xv_interp = ggml_add(context_->get(), last_x, x_diff_v_scaled); - - auto* x_diff_r = ggml_sub(context_->get(), x, last_x); - auto* x_diff_r_scaled = ggml_mul(context_->get(), x_diff_r, time_mix_r); - auto* xr_interp = ggml_add(context_->get(), last_x, x_diff_r_scaled); - + auto* xk_interp = mixWithPrevious(context_->get(), x, last_x, time_mix_k); + + auto* xv_interp = mixWithPrevious(context_->get(), x, last_x, time_mix_v); + + auto* xr_interp = mixWithPrevious(context_->get(), x, last_x, time_mix_r); + // Compute k, v, r vectors auto* k = ggml_mul_mat(context_->get(), Wk, xk_interp); auto* v = ggml_mul_mat(context_->get(), Wv, xv_interp); auto* r = ggml_mul_mat(context_->get(), Wr, xr_interp); - + // Get state variables (last_num, last_den) - ggml_tensor* last_num = state_ && static_cast(layer_idx) < state_->state_aa_.size() ? - state_->state_aa_[layer_idx] : nullptr; - ggml_tensor* last_den = state_ && static_cast(layer_idx) < state_->state_bb_.size() ? - state_->state_bb_[layer_idx] : nullptr; - + ggml_tensor* last_num = + state_ && static_cast(layer_idx) < state_->state_aa_.size() ? state_->state_aa_[layer_idx] : nullptr; + ggml_tensor* last_den = + state_ && static_cast(layer_idx) < state_->state_bb_.size() ? state_->state_bb_[layer_idx] : nullptr; + if (!last_num || !last_den) { // Initialize state last_num = ggml_new_tensor_1d(context_->get(), GGML_TYPE_F32, n_embd_); @@ -376,41 +379,36 @@ ggml_tensor* RWKVWrapper::timeMixing(ggml_tensor* x, int layer_idx) { ggml_set_zero(last_num); ggml_set_zero(last_den); } - + // WKV operation: wkv = (last_num + exp(bonus + k) * v) / (last_den + exp(bonus + k)) auto* bonus_k = time_first ? ggml_add(context_->get(), time_first, k) : k; auto* exp_bonus_k = ggml_exp(context_->get(), bonus_k); auto* exp_bonus_k_v = ggml_mul(context_->get(), exp_bonus_k, v); - + auto* wkv_num = ggml_add(context_->get(), last_num, exp_bonus_k_v); auto* wkv_den = ggml_add(context_->get(), last_den, exp_bonus_k); auto* wkv = ggml_div(context_->get(), wkv_num, wkv_den); - + // Apply receptance gating: rwkv = sigmoid(r) * wkv auto* r_sigmoid = ggml_sigmoid(context_->get(), r); auto* rwkv = ggml_mul(context_->get(), r_sigmoid, wkv); - + // Output projection auto* output = ggml_mul_mat(context_->get(), Wout, rwkv); - + // Update state for next token if (time_decay) { - auto* exp_neg_exp_decay = ggml_exp(context_->get(), - ggml_neg(context_->get(), - ggml_exp(context_->get(), time_decay))); + auto* exp_neg_exp_decay = + ggml_exp(context_->get(), ggml_neg(context_->get(), ggml_exp(context_->get(), time_decay))); auto* exp_k = ggml_exp(context_->get(), k); auto* exp_k_v = ggml_mul(context_->get(), exp_k, v); - + // num = exp(-exp(decay)) * last_num + exp(k) * v - auto* new_num = ggml_add(context_->get(), - ggml_mul(context_->get(), exp_neg_exp_decay, last_num), - exp_k_v); - + auto* new_num = ggml_add(context_->get(), ggml_mul(context_->get(), exp_neg_exp_decay, last_num), exp_k_v); + // den = exp(-exp(decay)) * last_den + exp(k) - auto* new_den = ggml_add(context_->get(), - ggml_mul(context_->get(), exp_neg_exp_decay, last_den), - exp_k); - + auto* new_den = ggml_add(context_->get(), ggml_mul(context_->get(), exp_neg_exp_decay, last_den), exp_k); + // Update state if (state_ && static_cast(layer_idx) < state_->state_aa_.size()) { state_->state_aa_[layer_idx] = new_num; @@ -418,99 +416,80 @@ ggml_tensor* RWKVWrapper::timeMixing(ggml_tensor* x, int layer_idx) { state_->state_pp_[layer_idx] = x; } } - + return output; } ggml_tensor* RWKVWrapper::channelMixing(ggml_tensor* x, int layer_idx) { // RWKV channel-mixing (Feed-Forward with memory) std::string prefix = "blk." + std::to_string(layer_idx) + ".ffn."; - + // Get time-mixing weights for FFN - ggml_tensor* time_mix_k = weights_.find(prefix + "time_mix_k") != weights_.end() ? - weights_[prefix + "time_mix_k"] : nullptr; - ggml_tensor* time_mix_r = weights_.find(prefix + "time_mix_r") != weights_.end() ? - weights_[prefix + "time_mix_r"] : nullptr; - + ggml_tensor* time_mix_k = findWeight(weights_, prefix + "time_mix_k"); + ggml_tensor* time_mix_r = findWeight(weights_, prefix + "time_mix_r"); + // Get weight matrices - ggml_tensor* Wk = weights_.find(prefix + "key.weight") != weights_.end() ? - weights_[prefix + "key.weight"] : nullptr; - ggml_tensor* Wr = weights_.find(prefix + "receptance.weight") != weights_.end() ? - weights_[prefix + "receptance.weight"] : nullptr; - ggml_tensor* Wv = weights_.find(prefix + "value.weight") != weights_.end() ? - weights_[prefix + "value.weight"] : nullptr; - + ggml_tensor* Wk = findWeight(weights_, prefix + "key.weight"); + ggml_tensor* Wr = findWeight(weights_, prefix + "receptance.weight"); + ggml_tensor* Wv = findWeight(weights_, prefix + "value.weight"); + // If weights not found, return input unchanged if (!time_mix_k || !time_mix_r || !Wk || !Wr || !Wv) { return x; } - + // Get previous token state - ggml_tensor* last_x = state_ && static_cast(layer_idx) < state_->state_pp_.size() ? - state_->state_pp_[layer_idx] : nullptr; - - if (!last_x) { - // First token, use zeros - last_x = ggml_new_tensor_1d(context_->get(), GGML_TYPE_F32, n_embd_); - ggml_set_zero(last_x); - } - + ggml_tensor* last_x = previousTokenOrZeros(context_->get(), state_.get(), layer_idx, n_embd_); + // Interpolate current and previous token: x * mix + last_x * (1 - mix) // Rewritten as: last_x + (x - last_x) * mix - auto* x_diff_k = ggml_sub(context_->get(), x, last_x); - auto* x_diff_k_scaled = ggml_mul(context_->get(), x_diff_k, time_mix_k); - auto* xk_interp = ggml_add(context_->get(), last_x, x_diff_k_scaled); - - auto* x_diff_r = ggml_sub(context_->get(), x, last_x); - auto* x_diff_r_scaled = ggml_mul(context_->get(), x_diff_r, time_mix_r); - auto* xr_interp = ggml_add(context_->get(), last_x, x_diff_r_scaled); - + auto* xk_interp = mixWithPrevious(context_->get(), x, last_x, time_mix_k); + + auto* xr_interp = mixWithPrevious(context_->get(), x, last_x, time_mix_r); + // Compute k and r vectors auto* k = ggml_mul_mat(context_->get(), Wk, xk_interp); auto* r = ggml_mul_mat(context_->get(), Wr, xr_interp); - + // Apply squared ReLU: max(k, 0)^2 auto* k_relu = ggml_relu(context_->get(), k); auto* k_squared = ggml_sqr(context_->get(), k_relu); - + // Apply value transformation: vk = Wv @ k_squared auto* vk = ggml_mul_mat(context_->get(), Wv, k_squared); - + // Apply receptance gating: output = sigmoid(r) * vk auto* r_sigmoid = ggml_sigmoid(context_->get(), r); auto* output = ggml_mul(context_->get(), r_sigmoid, vk); - + // Update state (store current x for next token) if (state_ && static_cast(layer_idx) < state_->state_pp_.size()) { state_->state_pp_[layer_idx] = x; } - + return output; } -ggml_tensor* RWKVWrapper::layerNorm(ggml_tensor* x, const std::string& weight_name, - const std::string& bias_name) { - ggml_tensor* weight = weights_.find(weight_name) != weights_.end() ? - weights_[weight_name] : nullptr; - ggml_tensor* bias = weights_.find(bias_name) != weights_.end() ? - weights_[bias_name] : nullptr; - +ggml_tensor* RWKVWrapper::layerNorm(ggml_tensor* x, const std::string& weight_name, const std::string& bias_name) { + ggml_tensor* weight = weights_.find(weight_name) != weights_.end() ? weights_[weight_name] : nullptr; + ggml_tensor* bias = weights_.find(bias_name) != weights_.end() ? weights_[bias_name] : nullptr; + if (!weight) { // If no weight, just return input return x; } - + // Use GGML's layer norm operation auto* normed = ggml_norm(context_->get(), x, 1e-5f); - + // Scale by weight normed = ggml_mul(context_->get(), normed, weight); - + // Add bias if present if (bias) { normed = ggml_add(context_->get(), normed, bias); } - + return normed; } @@ -518,33 +497,33 @@ int RWKVWrapper::sampleToken(ggml_tensor* logits, float temperature, float top_p // Get logits data float* logits_data = ggml_get_data_f32(logits); size_t n_logits = ggml_nelements(logits); - + if (n_logits != static_cast(n_vocab_)) { std::cerr << "Logits size mismatch: " << n_logits << " vs " << n_vocab_ << std::endl; return 0; } - + // Apply temperature if (temperature != 1.0f && temperature > 0.0f) { for (size_t i = 0; i < n_logits; i++) { logits_data[i] /= temperature; } } - + // Compute softmax float max_logit = *std::max_element(logits_data, logits_data + n_logits); float sum = 0.0f; std::vector probs(n_logits); - + for (size_t i = 0; i < n_logits; i++) { probs[i] = std::exp(logits_data[i] - max_logit); sum += probs[i]; } - + for (size_t i = 0; i < n_logits; i++) { probs[i] /= sum; } - + // Top-p sampling if (top_p < 1.0f) { // Create index-probability pairs @@ -552,11 +531,10 @@ int RWKVWrapper::sampleToken(ggml_tensor* logits, float temperature, float top_p for (size_t i = 0; i < n_logits; i++) { prob_idx.push_back({probs[i], static_cast(i)}); } - + // Sort by probability (descending) - std::sort(prob_idx.begin(), prob_idx.end(), - [](const auto& a, const auto& b) { return a.first > b.first; }); - + std::sort(prob_idx.begin(), prob_idx.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + // Compute cumulative probability and find cutoff float cumsum = 0.0f; size_t cutoff = 0; @@ -567,19 +545,21 @@ int RWKVWrapper::sampleToken(ggml_tensor* logits, float temperature, float top_p break; } } - + // Zero out probabilities below cutoff std::fill(probs.begin(), probs.end(), 0.0f); for (size_t i = 0; i < cutoff; i++) { probs[prob_idx[i].second] = prob_idx[i].first; } - + // Renormalize sum = 0.0f; - for (float p : probs) sum += p; - for (float& p : probs) p /= sum; + for (float p : probs) + sum += p; + for (float& p : probs) + p /= sum; } - + // Sample from distribution std::discrete_distribution dist(probs.begin(), probs.end()); return dist(rng_); @@ -589,4 +569,4 @@ ggml_tensor* RWKVWrapper::forward(ggml_tensor* input) { return forwardWithLogits(input); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/unified_rag_manager.cpp b/src/bolt/ai/unified_rag_manager.cpp index 62921291..3c633648 100644 --- a/src/bolt/ai/unified_rag_manager.cpp +++ b/src/bolt/ai/unified_rag_manager.cpp @@ -1,11 +1,50 @@ #include "bolt/ai/unified_rag_manager.hpp" + #include -#include #include +#include namespace bolt { namespace ai { +namespace { + +// Narrative memory events for the query as results, stopping once top_k have been collected (always at least one +// when there are events). +std::vector queryNarrativeBackend(NarrativeRAGManager& narrative_rag, const std::string& query, int top_k) { + auto events = narrative_rag.queryNarrativeMemory(query); + std::vector results; + for (const auto& event : events) { + RAGResult result; + result.id = event.id; + result.content = event.description; + result.score = static_cast(event.importance) / 10.0f; + result.source = "NarrativeRAG"; + results.push_back(result); + if (results.size() >= static_cast(top_k)) + break; + } + return results; +} + +// Semantic search hits for the query as results. +std::vector queryGeneralBackend(SemanticSearchManager& general_rag, const std::string& query, int top_k, + float confidence_threshold) { + auto search_results = general_rag.search(query, top_k, confidence_threshold); + std::vector results; + for (const auto& sr : search_results) { + RAGResult result; + result.id = sr.file_path; + result.content = sr.content_preview; + result.score = sr.similarity_score; + result.source = "GeneralRAG"; + results.push_back(result); + } + return results; +} + +} // namespace + UnifiedRAGManager::UnifiedRAGManager() { general_rag_ = std::make_unique(); narrative_rag_ = std::make_unique(); @@ -13,48 +52,49 @@ UnifiedRAGManager::UnifiedRAGManager() { router_ = std::make_unique(); } -UnifiedRAGManager::UnifiedRAGManager(const UnifiedRAGConfig& config) - : config_(config) { +UnifiedRAGManager::UnifiedRAGManager(const UnifiedRAGConfig& config) : config_(config) { general_rag_ = std::make_unique(); narrative_rag_ = std::make_unique(); temporal_rag_ = std::make_unique(); router_ = std::make_unique(); } -bool UnifiedRAGManager::initialize(const std::string& general_model_path, - const std::string& narrative_model_path, +bool UnifiedRAGManager::initialize(const std::string& general_model_path, const std::string& narrative_model_path, const std::string& temporal_model_path) { bool success = true; - + if (config_.enable_general_rag) { if (!general_rag_->initialize(general_model_path)) { std::cerr << "Warning: Failed to initialize general RAG backend\n"; success = false; } } - + if (config_.enable_narrative_rag) { if (!narrative_rag_->initialize(narrative_model_path)) { std::cerr << "Warning: Failed to initialize narrative RAG backend\n"; success = false; } } - + if (config_.enable_temporal_rag) { if (!temporal_rag_->initialize(temporal_model_path)) { std::cerr << "Warning: Failed to initialize temporal RAG backend\n"; success = false; } } - + initialized_ = success; return success; } void UnifiedRAGManager::shutdown() { - if (general_rag_) general_rag_->shutdown(); - if (narrative_rag_) narrative_rag_->shutdown(); - if (temporal_rag_) temporal_rag_->shutdown(); + if (general_rag_) + general_rag_->shutdown(); + if (narrative_rag_) + narrative_rag_->shutdown(); + if (temporal_rag_) + temporal_rag_->shutdown(); initialized_ = false; } @@ -66,44 +106,40 @@ RoutingDecision UnifiedRAGManager::analyzeQuery(const std::string& query) const RAGQueryType UnifiedRAGManager::classifyQuery(const std::string& query) const { std::string lower_query = query; std::transform(lower_query.begin(), lower_query.end(), lower_query.begin(), ::tolower); - + // Narrative indicators std::vector narrative_keywords = { - "story", "character", "happened", "event", "narrative", "plot", - "dialogue", "scene", "chapter", "protagonist", "antagonist", - "castle", "adventure", "quest", "journey", "remember", "told" - }; - + "story", "character", "happened", "event", "narrative", "plot", "dialogue", "scene", "chapter", + "protagonist", "antagonist", "castle", "adventure", "quest", "journey", "remember", "told"}; + // Temporal indicators std::vector temporal_keywords = { - "trend", "forecast", "predict", "time series", "over time", - "historical", "pattern", "anomaly", "correlation", "price", - "stock", "market", "sensor", "metric", "yesterday", "last week", - "next", "future", "past", "hour", "day", "month", "year" - }; - + "trend", "forecast", "predict", "time series", "over time", "historical", "pattern", "anomaly", + "correlation", "price", "stock", "market", "sensor", "metric", "yesterday", "last week", + "next", "future", "past", "hour", "day", "month", "year"}; + int narrative_score = 0; int temporal_score = 0; - + // Count keyword matches for (const auto& keyword : narrative_keywords) { if (lower_query.find(keyword) != std::string::npos) { narrative_score++; } } - + for (const auto& keyword : temporal_keywords) { if (lower_query.find(keyword) != std::string::npos) { temporal_score++; } } - + // Check for time-related patterns (e.g., "in 2023", "from 10:00 to 12:00") std::regex time_pattern(R"(\b\d{4}\b|\b\d{1,2}:\d{2}\b)"); if (std::regex_search(lower_query, time_pattern)) { temporal_score += 2; } - + // Determine query type if (narrative_score > 0 && temporal_score > 0) { return RAGQueryType::HYBRID; @@ -126,31 +162,20 @@ std::vector UnifiedRAGManager::query(const std::string& query, int to std::cerr << "Error: UnifiedRAGManager not initialized\n"; return {}; } - + if (top_k < 0) { top_k = config_.default_top_k; } - + auto routing = routeQuery(query); - + switch (routing.query_type) { case RAGQueryType::NARRATIVE: if (config_.enable_narrative_rag && narrative_rag_->isInitialized()) { - auto events = narrative_rag_->queryNarrativeMemory(query); - std::vector results; - for (const auto& event : events) { - RAGResult result; - result.id = event.id; - result.content = event.description; - result.score = static_cast(event.importance) / 10.0f; - result.source = "NarrativeRAG"; - results.push_back(result); - if (results.size() >= static_cast(top_k)) break; - } - return results; + return queryNarrativeBackend(*narrative_rag_, query, top_k); } break; - + case RAGQueryType::TEMPORAL: if (config_.enable_temporal_rag && temporal_rag_->isInitialized()) { // For temporal queries, we'd need to parse time ranges @@ -165,111 +190,76 @@ std::vector UnifiedRAGManager::query(const std::string& query, int to return results; } break; - + case RAGQueryType::HYBRID: if (config_.enable_hybrid_queries) { return processHybridQuery(query, top_k); } break; - + default: if (config_.enable_general_rag && general_rag_->isInitialized()) { - auto search_results = general_rag_->search(query, top_k, config_.confidence_threshold); - std::vector results; - for (const auto& sr : search_results) { - RAGResult result; - result.id = sr.file_path; - result.content = sr.content_preview; - result.score = sr.similarity_score; - result.source = "GeneralRAG"; - results.push_back(result); - } - return results; + return queryGeneralBackend(*general_rag_, query, top_k, config_.confidence_threshold); } break; } - + return {}; } -std::vector UnifiedRAGManager::queryWithType(const std::string& query, - RAGQueryType type, - int top_k) { +std::vector UnifiedRAGManager::queryWithType(const std::string& query, RAGQueryType type, int top_k) { if (top_k < 0) { top_k = config_.default_top_k; } - + // Force a specific backend regardless of query classification switch (type) { case RAGQueryType::NARRATIVE: if (narrative_rag_->isInitialized()) { - auto events = narrative_rag_->queryNarrativeMemory(query); - std::vector results; - for (const auto& event : events) { - RAGResult result; - result.id = event.id; - result.content = event.description; - result.score = static_cast(event.importance) / 10.0f; - result.source = "NarrativeRAG"; - results.push_back(result); - if (results.size() >= static_cast(top_k)) break; - } - return results; + return queryNarrativeBackend(*narrative_rag_, query, top_k); } break; - + case RAGQueryType::TEMPORAL: // Temporal query implementation break; - + case RAGQueryType::GENERAL_SEMANTIC: if (general_rag_->isInitialized()) { - auto search_results = general_rag_->search(query, top_k, config_.confidence_threshold); - std::vector results; - for (const auto& sr : search_results) { - RAGResult result; - result.id = sr.file_path; - result.content = sr.content_preview; - result.score = sr.similarity_score; - result.source = "GeneralRAG"; - results.push_back(result); - } - return results; + return queryGeneralBackend(*general_rag_, query, top_k, config_.confidence_threshold); } break; - + default: break; } - + return {}; } std::vector UnifiedRAGManager::processHybridQuery(const std::string& query, int top_k) { std::vector all_results; - + // Query both narrative and temporal backends if (narrative_rag_->isInitialized()) { auto narrative_results = queryWithType(query, RAGQueryType::NARRATIVE, top_k / 2); all_results.insert(all_results.end(), narrative_results.begin(), narrative_results.end()); } - + if (temporal_rag_->isInitialized()) { auto temporal_results = queryWithType(query, RAGQueryType::TEMPORAL, top_k / 2); all_results.insert(all_results.end(), temporal_results.begin(), temporal_results.end()); } - + // Sort by score - std::sort(all_results.begin(), all_results.end(), - [](const RAGResult& a, const RAGResult& b) { - return a.score > b.score; - }); - + std::sort(all_results.begin(), all_results.end(), + [](const RAGResult& a, const RAGResult& b) { return a.score > b.score; }); + // Trim to top_k if (all_results.size() > static_cast(top_k)) { all_results.resize(top_k); } - + return all_results; } @@ -279,7 +269,7 @@ RoutingDecision UnifiedRAGManager::analyzeQuery(const std::string& query) const void UnifiedRAGManager::ingestGeneralDocument(const std::string& content, const std::string& id) { if (general_rag_ && general_rag_->isInitialized()) { - general_rag_->indexFile(id); // Assuming id is a file path + general_rag_->indexFile(id); // Assuming id is a file path } } @@ -297,25 +287,25 @@ void UnifiedRAGManager::ingestTemporalData(const TimeSeriesPoint& point) { std::unordered_map UnifiedRAGManager::getBackendStatistics() const { std::unordered_map stats; - + if (general_rag_ && general_rag_->isInitialized()) { stats["GeneralRAG_files"] = general_rag_->getIndexedFileCount(); } - + if (narrative_rag_ && narrative_rag_->isInitialized()) { stats["NarrativeRAG_events"] = narrative_rag_->getEventCount(); } - + if (temporal_rag_ && temporal_rag_->isInitialized()) { stats["TemporalRAG_points"] = temporal_rag_->getDataPointCount(); } - + return stats; } std::vector UnifiedRAGManager::getAvailableBackends() const { std::vector backends; - + if (general_rag_ && general_rag_->isInitialized()) { backends.push_back("GeneralRAG"); } @@ -325,9 +315,9 @@ std::vector UnifiedRAGManager::getAvailableBackends() const { if (temporal_rag_ && temporal_rag_->isInitialized()) { backends.push_back("TemporalRAG"); } - + return backends; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt