UNPKG

@aaswe/codebase-ai

Version:

AI-Assisted Software Engineering (AASWE) - Rich codebase context for IDE LLMs

363 lines 13.9 kB
"use strict"; /** * Layer 3: AI/LLM Integration & Reasoning - Main Integration * * This module provides the main integration point for Layer 3 services, * combining RAG Engine, GraphCypher QA, and SPARQL Query Engine into * a unified AI reasoning system. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Layer3AIService = exports.SPARQLQueryEngine = exports.GraphCypherQAChain = exports.ContextManager = exports.RAGEngine = void 0; var langchain_rag_1 = require("./langchain-rag"); Object.defineProperty(exports, "RAGEngine", { enumerable: true, get: function () { return langchain_rag_1.RAGEngine; } }); Object.defineProperty(exports, "ContextManager", { enumerable: true, get: function () { return langchain_rag_1.ContextManager; } }); var graph_cypher_qa_1 = require("./graph-cypher-qa"); Object.defineProperty(exports, "GraphCypherQAChain", { enumerable: true, get: function () { return graph_cypher_qa_1.GraphCypherQAChain; } }); var sparql_query_engine_1 = require("./sparql-query-engine"); Object.defineProperty(exports, "SPARQLQueryEngine", { enumerable: true, get: function () { return sparql_query_engine_1.SPARQLQueryEngine; } }); // Main Layer 3 Integration Service const events_1 = require("events"); const langchain_rag_2 = require("./langchain-rag"); const graph_cypher_qa_2 = require("./graph-cypher-qa"); const sparql_query_engine_2 = require("./sparql-query-engine"); const logger_1 = __importDefault(require("../../utils/logger")); /** * Layer 3 AI Integration Service * * Provides unified access to all Layer 3 AI services with intelligent * query routing and response coordination. */ class Layer3AIService extends events_1.EventEmitter { config; ragEngine; graphCypherQA; sparqlEngine; rdfStore; neo4jService; isInitialized = false; constructor(config, rdfStore, neo4jService) { super(); this.config = config; this.rdfStore = rdfStore; this.neo4jService = neo4jService; } /** * Initialize all Layer 3 services */ async initialize() { try { logger_1.default.info('Initializing Layer 3 AI Integration Service'); // Initialize RAG Engine this.ragEngine = new langchain_rag_2.RAGEngine({ llm: { provider: this.config.rag.provider, model: this.config.rag.model, temperature: this.config.rag.temperature || 0.1, maxTokens: this.config.rag.maxTokens || 1000 }, vectorStore: { type: 'memory', dimensions: 1536, similarity: 'cosine' }, retrieval: { topK: 5, scoreThreshold: 0.7, maxTokens: 4000, contextWindow: 8000 }, embeddings: { provider: 'openai', model: 'text-embedding-ada-002', dimensions: 1536 }, cache: { enabled: true, ttl: 300000, maxSize: 1000 } }); logger_1.default.info('RAG Engine initialized successfully'); // Initialize GraphCypher QA const driver = this.neo4jService.getDriver(); if (!driver) { throw new Error('Neo4j driver not available'); } this.graphCypherQA = new graph_cypher_qa_2.GraphCypherQAChain({ neo4j: { uri: this.config.graphCypher.neo4jUrl, user: this.config.graphCypher.username || 'neo4j', password: this.config.graphCypher.password || 'password', database: this.config.graphCypher.database || 'neo4j' }, llm: { provider: this.config.rag.provider, model: this.config.rag.model, temperature: 0.1, maxTokens: 1000 }, queryGeneration: { maxRetries: 3, timeoutMs: 30000, validateSyntax: true, optimizeQuery: true }, schema: { cacheEnabled: true, cacheTtl: 300000, includeIndexes: true, includeConstraints: true, maxNodes: 1000, maxRelationships: 1000 }, response: { includeQuery: true, includeExplanation: true, maxResults: 100, formatResults: true } }, driver); logger_1.default.info('GraphCypher QA initialized successfully'); // Initialize SPARQL Engine this.sparqlEngine = new sparql_query_engine_2.SPARQLQueryEngine({ rdf: { timeout: 30000, maxResults: 1000 }, llm: { provider: this.config.sparql.provider, model: this.config.sparql.model, temperature: 0.1, maxTokens: 1000 }, queryGeneration: { maxRetries: 3, timeoutMs: 30000, validateSyntax: true, optimizeQuery: true }, prefixes: { 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'owl': 'http://www.w3.org/2002/07/owl#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'code': 'http://example.org/code#', 'module': 'http://example.org/module#' }, response: { includeQuery: true, includeExplanation: true, formatResults: true, maxResults: 100 }, caching: { enabled: true, ttl: 300000, maxSize: 1000 } }, this.rdfStore); await this.sparqlEngine.initialize(); logger_1.default.info('SPARQL Engine initialized successfully'); this.isInitialized = true; this.emit('initialized'); logger_1.default.info('Layer 3 AI Integration Service initialized successfully'); } catch (error) { logger_1.default.error('Failed to initialize Layer 3 AI Integration Service', error); throw error; } } /** * Process AI query with intelligent routing */ async query(request) { if (!this.isInitialized) { throw new Error('Layer 3 AI Service not initialized'); } const startTime = Date.now(); try { // Determine query type if auto const queryType = request.type === 'auto' ? this.determineQueryType(request.query) : request.type; let response; switch (queryType) { case 'rag': response = await this.processRAGQuery(request); break; case 'cypher': response = await this.processCypherQuery(request); break; case 'sparql': response = await this.processSPARQLQuery(request); break; default: throw new Error(`Unsupported query type: ${queryType}`); } response.executionTime = Date.now() - startTime; this.emit('query:completed', response); return response; } catch (error) { const errorResponse = { query: request.query, type: request.type, response: `Error processing query: ${error instanceof Error ? error.message : String(error)}`, confidence: 0, executionTime: Date.now() - startTime }; this.emit('query:error', errorResponse); return errorResponse; } } /** * Determine appropriate query type based on query content */ determineQueryType(query) { const lowerQuery = query.toLowerCase(); // Graph relationship queries if (lowerQuery.includes('relationship') || lowerQuery.includes('depends on') || lowerQuery.includes('calls') || lowerQuery.includes('connected to') || lowerQuery.includes('flow') || lowerQuery.includes('path between')) { return 'cypher'; } // Semantic/ontology queries if (lowerQuery.includes('pattern') || lowerQuery.includes('type of') || lowerQuery.includes('instance of') || lowerQuery.includes('semantic') || lowerQuery.includes('ontology') || lowerQuery.includes('class') && lowerQuery.includes('property')) { return 'sparql'; } // Default to RAG for general queries return 'rag'; } /** * Process RAG query */ async processRAGQuery(request) { if (!this.ragEngine) { throw new Error('RAG Engine not initialized'); } const ragResponse = await this.ragEngine.query({ query: request.query, intent: 'code_explanation', scope: 'project' }); return { query: request.query, type: 'rag', response: ragResponse.answer, confidence: ragResponse.sources.length > 0 ? 0.8 : 0.3, sources: ragResponse.sources?.map(s => s.document.metadata?.source || 'unknown'), executionTime: 0, // Will be set by caller metadata: { contextUsed: ragResponse.context.retrievedDocuments, processingTime: ragResponse.context.processingTime } }; } /** * Process Cypher query */ async processCypherQuery(request) { if (!this.graphCypherQA) { throw new Error('GraphCypher QA not initialized'); } const cypherResponse = await this.graphCypherQA.query(request.query); return { query: request.query, type: 'cypher', response: cypherResponse.formattedResponse, confidence: cypherResponse.interpretedQuery.entities.length > 0 ? 0.8 : 0.3, sources: cypherResponse.executionResult.success ? ['Neo4j Graph Database'] : [], executionTime: 0, // Will be set by caller metadata: { cypherQuery: cypherResponse.generatedCypher.cypher, resultCount: cypherResponse.executionResult.summary.recordsReturned, executionTime: cypherResponse.executionResult.summary.executionTime } }; } /** * Process SPARQL query */ async processSPARQLQuery(request) { if (!this.sparqlEngine) { throw new Error('SPARQL Engine not initialized'); } const sparqlResponse = await this.sparqlEngine.query(request.query); return { query: request.query, type: 'sparql', response: sparqlResponse.formattedResponse, confidence: sparqlResponse.interpretedQuery.confidence, sources: sparqlResponse.executionResult.success ? ['RDF Knowledge Store'] : [], executionTime: 0, // Will be set by caller metadata: { sparqlQuery: sparqlResponse.generatedSPARQL.sparql, resultCount: sparqlResponse.executionResult.summary.resultCount, executionTime: sparqlResponse.executionResult.summary.executionTime } }; } /** * Get service health status */ async getHealth() { const services = { rag: this.ragEngine ? true : false, cypher: this.graphCypherQA ? true : false, sparql: this.sparqlEngine ? true : false }; const healthyCount = Object.values(services).filter(Boolean).length; let status; if (healthyCount === 3) { status = 'healthy'; } else if (healthyCount >= 1) { status = 'degraded'; } else { status = 'unhealthy'; } return { status, services }; } /** * Get combined metrics from all services */ getMetrics() { return { rag: this.ragEngine?.getMetrics(), cypher: this.graphCypherQA?.getMetrics(), sparql: this.sparqlEngine?.getMetrics() }; } /** * Shutdown all services */ async shutdown() { logger_1.default.info('Shutting down Layer 3 AI Integration Service'); if (this.ragEngine) { await this.ragEngine.shutdown(); } if (this.graphCypherQA) { await this.graphCypherQA.shutdown(); } if (this.sparqlEngine) { await this.sparqlEngine.shutdown(); } this.removeAllListeners(); this.isInitialized = false; logger_1.default.info('Layer 3 AI Integration Service shutdown completed'); } } exports.Layer3AIService = Layer3AIService; //# sourceMappingURL=index.js.map