| 1 | import axios from 'axios'; |
| 2 | import { logger } from '../log.js'; |
| 3 | |
| 4 | const OLLAMA_ENDPOINT = 'http://localhost:11434/api/generate'; |
| 5 | |
| 6 | export async function analyzeComplianceFiles(files, selfDescription) { |
| 7 | try { |
| 8 | const prompt = `Analiza la siguiente Self-Description de GAIA-X y sus archivos generados: |
| 9 | |
| 10 | Self-Description: ${JSON.stringify(selfDescription, null, 2)} |
| 11 | Archivos: ${JSON.stringify(files, null, 2)} |
| 12 | |
| 13 | Proporciona un análisis detallado incluyendo: |
| 14 | 1. Evaluación de seguridad |
| 15 | 2. Puntuación de cumplimiento |
| 16 | 3. Recomendaciones específicas |
| 17 | 4. Compatibilidad con GAIA-X |
| 18 | |
| 19 | Formato JSON requerido para la respuesta.`; |
| 20 | |
| 21 | const analysis = await queryOllama(prompt); |
| 22 | const parsedAnalysis = parseAnalysis(analysis); |
| 23 | |
| 24 | return { |
| 25 | summary: generateSummary(parsedAnalysis), |
| 26 | detailedAnalysis: parsedAnalysis, |
| 27 | recommendations: parsedAnalysis.recommendations, |
| 28 | rawLLMResponse: analysis |
| 29 | }; |
| 30 | } catch (error) { |
| 31 | return await analyzeAnyError(error, { files, selfDescription }); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | export async function analyzeComplianceError(verifiablePresentation) { |
| 36 | try { |
| 37 | const prompt = `Analiza el siguiente Verifiable Presentation que ha fallado la validación GAIA-X: |
| 38 | |
| 39 | ${JSON.stringify(verifiablePresentation, null, 2)} |
| 40 | |
| 41 | Proporciona: |
| 42 | 1. Análisis detallado del error |
| 43 | 2. Posibles causas |
| 44 | 3. Soluciones específicas |
| 45 | 4. Pasos para prevenir este error en el futuro |
| 46 | |
| 47 | Enfócate en los requisitos del GAIA-X Trust Framework.`; |
| 48 | |
| 49 | const analysis = await queryOllama(prompt); |
| 50 | |
| 51 | return { |
| 52 | summary: extractSummary(analysis), |
| 53 | solutions: extractSolutions(analysis), |
| 54 | detailedAnalysis: analysis, |
| 55 | rawLLMResponse: analysis |
| 56 | }; |
| 57 | } catch (error) { |
| 58 | return await analyzeAnyError(error, { verifiablePresentation }); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | export async function analyzeAnyError(error, context = {}) { |
| 63 | try { |
| 64 | const prompt = `Analiza el siguiente error en el contexto de GAIA-X y proporciona una guía de solución: |
| 65 | |
| 66 | Error: ${error.message} |
| 67 | Contexto: ${JSON.stringify(context, null, 2)} |
| 68 | |
| 69 | Por favor proporciona: |
| 70 | 1. Explicación simple del error |
| 71 | 2. Posibles causas |
| 72 | 3. Pasos específicos para solucionarlo |
| 73 | 4. Recomendaciones para prevenir este error |
| 74 | 5. Enlaces o recursos relevantes |
| 75 | |
| 76 | Enfócate en proporcionar una solución práctica y clara.`; |
| 77 | |
| 78 | const analysis = await queryOllama(prompt); |
| 79 | |
| 80 | return { |
| 81 | error: error.message, |
| 82 | analysis: { |
| 83 | explanation: extractExplanation(analysis), |
| 84 | nextSteps: extractNextSteps(analysis), |
| 85 | prevention: extractPrevention(analysis), |
| 86 | resources: extractResources(analysis) |
| 87 | }, |
| 88 | rawLLMResponse: analysis |
| 89 | }; |
| 90 | } catch (aiError) { |
| 91 | // Fallback básico si el análisis LLM falla |
| 92 | return { |
| 93 | error: error.message, |
| 94 | analysis: { |
| 95 | explanation: "No se pudo realizar el análisis detallado", |
| 96 | nextSteps: [ |
| 97 | "Verificar la configuración básica", |
| 98 | "Revisar los logs para más detalles", |
| 99 | "Contactar soporte técnico si el problema persiste" |
| 100 | ], |
| 101 | prevention: ["Documentar el error para futura referencia"], |
| 102 | resources: ["https://docs.gaia-x.eu"] |
| 103 | } |
| 104 | }; |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | async function queryOllama(prompt) { |
| 109 | try { |
| 110 | const response = await axios.post(OLLAMA_ENDPOINT, { |
| 111 | model: "qwen2.5:1.5b", |
| 112 | prompt: prompt, |
| 113 | stream: false |
| 114 | }); |
| 115 | return response.data.response; |
| 116 | } catch (error) { |
| 117 | logger.error("Error llamando a Ollama:", error); |
| 118 | throw new Error("Error en la consulta al modelo de IA"); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | function parseAnalysis(rawAnalysis) { |
| 123 | try { |
| 124 | // Intentar parsear como JSON primero |
| 125 | return JSON.parse(rawAnalysis); |
| 126 | } catch { |
| 127 | // Si no es JSON, extraer información del texto |
| 128 | return { |
| 129 | securityAnalysis: { |
| 130 | score: extractScore(rawAnalysis, "security"), |
| 131 | findings: extractFindings(rawAnalysis) |
| 132 | }, |
| 133 | complianceScore: extractScore(rawAnalysis, "compliance"), |
| 134 | recommendations: extractRecommendations(rawAnalysis), |
| 135 | compatibility: { |
| 136 | level: extractCompatibilityLevel(rawAnalysis), |
| 137 | status: extractStatus(rawAnalysis) |
| 138 | } |
| 139 | }; |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | function generateSummary(analysis) { |
| 144 | return `Análisis de Compliance GAIA-X: |
| 145 | - Puntuación de Seguridad: ${analysis.securityAnalysis.score}/100 |
| 146 | - Puntuación de Compliance: ${analysis.complianceScore}/100 |
| 147 | - Nivel de Compatibilidad: ${analysis.compatibility.level} |
| 148 | - Recomendaciones Críticas: ${analysis.recommendations.filter(r => r.priority === "HIGH").length}`; |
| 149 | } |
| 150 | |
| 151 | // Funciones auxiliares para extraer información del texto |
| 152 | function extractSummary(text) { |
| 153 | // Extraer primeros párrafos como resumen |
| 154 | return text.split('\n\n')[0]; |
| 155 | } |
| 156 | |
| 157 | function extractSolutions(text) { |
| 158 | // Buscar soluciones en el texto |
| 159 | const solutions = text.match(/(?:solución|paso|recomendación)[:]\s*([^\n]+)/gi); |
| 160 | return solutions ? solutions.map(s => s.split(':')[1].trim()) : []; |
| 161 | } |
| 162 | |
| 163 | function extractScore(text, type) { |
| 164 | const match = text.match(new RegExp(`${type}[^0-9]*([0-9]+)`, 'i')); |
| 165 | return match ? parseInt(match[1]) : 85; |
| 166 | } |
| 167 | |
| 168 | function extractFindings(text) { |
| 169 | return text.match(/[•\-\*]\s*([^\n]+)/g) || []; |
| 170 | } |
| 171 | |
| 172 | function extractCompatibilityLevel(text) { |
| 173 | if (text.toLowerCase().includes('full')) return 'FULL'; |
| 174 | if (text.toLowerCase().includes('partial')) return 'PARTIAL'; |
| 175 | return 'UNKNOWN'; |
| 176 | } |
| 177 | |
| 178 | function extractStatus(text) { |
| 179 | if (text.toLowerCase().includes('ready')) return 'READY'; |
| 180 | if (text.toLowerCase().includes('pending')) return 'PENDING'; |
| 181 | return 'REVIEW_NEEDED'; |
| 182 | } |
| 183 | |
| 184 | function extractExplanation(text) { |
| 185 | const explanationMatch = text.match(/explicación[:\n]+(.*?)(?=\n\n|\n[0-9]|$)/is); |
| 186 | return explanationMatch ? explanationMatch[1].trim() : text.split('\n')[0]; |
| 187 | } |
| 188 | |
| 189 | function extractNextSteps(text) { |
| 190 | const steps = text.match(/(?:paso|step)[^:]*:[^\n]+/gi) || []; |
| 191 | return steps.map(step => step.split(':')[1].trim()); |
| 192 | } |
| 193 | |
| 194 | function extractPrevention(text) { |
| 195 | const prevention = text.match(/(?:prevenir|prevención)[^:]*:[^\n]+/gi) || []; |
| 196 | return prevention.map(p => p.split(':')[1].trim()); |
| 197 | } |
| 198 | |
| 199 | function extractResources(text) { |
| 200 | const resources = text.match(/(?:recurso|link|enlace)[^:]*:[^\n]+/gi) || []; |
| 201 | return resources.map(r => r.split(':')[1].trim()); |
| 202 | } |