scai
Version:
> **AI-powered CLI for local code analysis, commit message suggestions, and natural-language queries.** 100% local, private, GDPR-friendly, made in Denmark/EU with â¤ď¸.
71 lines (63 loc) ⢠2.73 kB
JavaScript
import { Config } from '../../config.js';
import { generate } from '../../lib/generate.js';
import path from 'path';
import chalk from 'chalk';
import { cleanupModule } from './cleanupModule.js';
import { normalizeData } from '../../utils/normalizeData.js';
export const kgModule = {
name: 'knowledge-graph',
description: 'Generates a knowledge graph of entities, tags, and relationships from file content.',
run: async (input, content) => {
const model = Config.getModel();
const ext = input.filepath ? path.extname(input.filepath).toLowerCase() : '';
const filename = input.filepath ? path.basename(input.filepath) : '';
// Build prompt for LLM
const prompt = `
You are an assistant specialized in building knowledge graphs from code or text.
Your task is to extract structured information from the file content below.
File: ${filename}
Extension: ${ext}
đ Instructions:
- Identify all entities (functions, classes, modules, or main concepts)
- For each entity, generate tags describing its characteristics, purpose, or category
- Identify relationships between entities (e.g., "uses", "extends", "calls")
- Return output in **valid JSON** format with this structure:
{
"entities": [
{ "name": "EntityName", "type": "class|function|module|concept", "tags": ["tag1", "tag2"] }
],
"edges": [
{ "from": "EntityName1", "to": "EntityName2", "type": "relationship_type" }
]
}
â ď¸ Make sure all strings are safely JSON-encoded: escape quotes, backslashes, and newlines.
Do NOT include raw content from the file. Only provide structured JSON output.
--- FILE CONTENT START ---
${content}
--- FILE CONTENT END ---
`.trim();
try {
// === INTERACTION #1: generate.ts (via ModuleIO) ===
const genInput = {
query: 'Extract entities and relationships for knowledge graph',
content: prompt,
};
const genOutput = await generate(genInput);
// === INTERACTION #2: cleanupModule (via ModuleIO) ===
const cleaned = await cleanupModule.run({
query: 'Clean up JSON for knowledge graph',
content: genOutput.data,
});
// === Normalize and parse JSON result ===
const parsed = normalizeData(cleaned.data);
// Ensure structure validity
parsed.entities ?? (parsed.entities = []);
parsed.edges ?? (parsed.edges = []);
return parsed;
}
catch (err) {
console.log(chalk.yellow(`â ď¸ [KG] Garbage or invalid JSON output for ${input.filepath}`));
return { entities: [], edges: [] };
}
},
};