import { readFileSync, statSync } from "node:fs"; import { defineTool, FilePath, Type } from "@toolpal/tool"; const MAX_BYTES = 25 * 1024 * 1024; const MISSING = new Set(["", "na", "n/a", "null", "none", "nan", "-"]); const BOOLEAN = /^(true|false|yes|no)$/i; const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/; function isValidIsoDate(s: string): boolean { const m = s.match(ISO_DATE); if (!m) return false; const year = Number(m[1]); const month = Number(m[2]); const day = Number(m[3]); if (month < 1 || month > 12 || day < 1 || day > 31) return false; const d = new Date(Date.UTC(year, month - 1, day)); if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day) { return false; } return !Number.isNaN(Date.parse(s)); } function detectDelimiter(text: string): string { const firstLine = text.slice(0, text.search(/\r?\n|$/)); let best = ","; let bestCount = 0; for (const d of [",", ";", "\t", "|"]) { const count = firstLine.replace(/"[^"]*"/g, "").split(d).length - 1; if (count > bestCount) [best, bestCount] = [d, count]; } return best; } // RFC 4180: quoted fields may contain delimiters, newlines and doubled quotes. function parseCsv(text: string, delimiter: string): string[][] { const rows: string[][] = []; let row: string[] = []; let field = ""; let quoted = false; const endRow = () => { row.push(field); rows.push(row); row = []; field = ""; }; for (let i = 0; i < text.length; i++) { const c = text[i]; if (quoted) { if (c !== '"') { field += c; } else if (text[i + 1] === '"') { field += '"'; i++; } else { quoted = false; } } else if (c === '"' && field === "") { quoted = true; } else if (c === delimiter) { row.push(field); field = ""; } else if (c === "\n" || c === "\r") { if (c === "\r" && text[i + 1] === "\n") i++; endRow(); } else { field += c; } } if (field !== "" || row.length > 0) endRow(); // Drop trailing blank lines while keeping empty single-column cells inside data. while (rows.length > 0) { const last = rows[rows.length - 1]; if (last.length === 1 && last[0].trim() === "") rows.pop(); else break; } return rows; } // Handles currency prefixes, percentages, accounting negatives like ($1,250.50), // negative-before-currency like -$50, and European decimal commas (1.250,50) on `;` files. function toNumber(value: string, decimalComma: boolean): number | undefined { let v = value.trim(); let negative = false; if (v.startsWith("(") && v.endsWith(")")) { negative = true; v = v.slice(1, -1).trim(); } if (v.startsWith("-")) { negative = !negative; v = v.slice(1).trim(); } else if (v.startsWith("+")) { v = v.slice(1).trim(); } v = v.replace(/^[$€£₹¥]\s*/, "").replace(/\s*%$/, ""); if (v.startsWith("-")) { negative = !negative; v = v.slice(1).trim(); } if (decimalComma && /^(\d{1,3}(\.\d{3})*|\d+),\d+$|^\d{1,3}(\.\d{3})+$/.test(v)) { v = v.replace(/\./g, "").replace(",", "."); } else if (/^\d{1,3}(,\d{3})+(\.\d+)?$/.test(v)) { v = v.replace(/,/g, ""); } if (!/^(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(v)) return undefined; const n = Number(v); if (!Number.isFinite(n)) return undefined; return negative ? (n === 0 ? 0 : -n) : n; } const round = (n: number) => Math.round(n * 10000) / 10000; function topValues(values: string[], limit: number) { const counts = new Map(); for (const v of values) counts.set(v, (counts.get(v) ?? 0) + 1); return [...counts.entries()] .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) .slice(0, limit) .map(([value, count]) => ({ value, count })); } function describeColumn(name: string, raw: string[], limit: number, decimalComma: boolean) { const values = raw.map((v) => v.trim()).filter((v) => !MISSING.has(v.toLowerCase())); const base = { name, filled: values.length, missing: raw.length - values.length, unique: new Set(values).size, }; if (values.length === 0) return { ...base, type: "empty" as const }; const numbers = values.map((v) => toNumber(v, decimalComma)); if (numbers.every((n) => n !== undefined)) { const sorted = (numbers as number[]).slice().sort((a, b) => a - b); const sum = sorted.reduce((a, b) => a + b, 0); const mean = sum / sorted.length; const mid = Math.floor(sorted.length / 2); const median = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; const variance = sorted.reduce((acc, n) => acc + (n - mean) ** 2, 0) / sorted.length; return { ...base, type: "number" as const, stats: { min: sorted[0], max: sorted[sorted.length - 1], mean: round(mean), median: round(median), sum: round(sum), stdDev: round(Math.sqrt(variance)), }, }; } if (values.every((v) => BOOLEAN.test(v))) { return { ...base, type: "boolean" as const, topValues: topValues( values.map((v) => v.toLowerCase()), limit, ), }; } if (values.every(isValidIsoDate)) { const sorted = values.slice().sort((a, b) => Date.parse(a) - Date.parse(b)); return { ...base, type: "date" as const, range: { earliest: sorted[0], latest: sorted[sorted.length - 1] }, }; } return { ...base, type: "text" as const, topValues: topValues(values, limit) }; } const ColumnSummary = Type.Object({ name: Type.String(), type: Type.Union([ Type.Literal("number"), Type.Literal("date"), Type.Literal("boolean"), Type.Literal("text"), Type.Literal("empty"), ]), filled: Type.Integer(), missing: Type.Integer({ description: "Empty cells and NA, N/A, null, none, NaN or -" }), unique: Type.Integer(), stats: Type.Optional( Type.Object({ min: Type.Number(), max: Type.Number(), mean: Type.Number(), median: Type.Number(), sum: Type.Number(), stdDev: Type.Number(), }), ), range: Type.Optional(Type.Object({ earliest: Type.String(), latest: Type.String() })), topValues: Type.Optional( Type.Array(Type.Object({ value: Type.String(), count: Type.Integer() })), ), }); export default defineTool({ description: "Profiles a CSV file locally and exactly instead of eyeballing it: row count, each column's inferred type (number, date, boolean, text), missing and unique values, min/max/mean/median/sum/standard deviation for numeric columns, date ranges, and the most frequent values of text columns. Handles quoted fields and comma, semicolon, tab or pipe delimiters. Offline, no API key needed.", input: Type.Object({ file: FilePath({ description: "CSV, TSV or pipe/semicolon-delimited text file" }), delimiter: Type.Optional( Type.Union([Type.Literal(","), Type.Literal(";"), Type.Literal("tab"), Type.Literal("|")], { description: "Field separator; detected from the header row when left out", }), ), topValues: Type.Optional( Type.Integer({ minimum: 1, maximum: 20, description: "Frequent values to list per text column, 5 by default", }), ), }), output: Type.Object({ rows: Type.Integer({ description: "Data rows, not counting the header" }), columnCount: Type.Integer(), delimiter: Type.String(), raggedRows: Type.Integer({ description: "Rows whose field count differs from the header" }), columns: Type.Array(ColumnSummary), }), examples: [ { title: "Profile a sales CSV", prompt: "Profile sample.csv and summarize every column's types, stats, and missing values", input: { file: "examples/sample.csv", topValues: 3, }, }, ], handler: async ({ file, delimiter, topValues: limit = 5 }, ctx) => { const { size } = statSync(file); if (size > MAX_BYTES) { throw new Error(`The file is ${(size / 1048576).toFixed(1)} MB; the limit is 25 MB.`); } const text = readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const sep = delimiter === "tab" ? "\t" : (delimiter ?? detectDelimiter(text)); const [header = [], ...rawBody] = parseCsv(text, sep); const body = header.length > 1 ? rawBody.filter((r) => r.length > 1 || r[0].trim() !== "") : rawBody; if (header.length === 0) throw new Error("The file is empty."); const seen = new Set(); const names = header.map((h, i) => { let name = h.trim() || `column_${i + 1}`; while (seen.has(name)) name += `_${i + 1}`; seen.add(name); return name; }); const columns = names.map((name, i) => describeColumn( name, body.map((r) => r[i] ?? ""), limit, sep === ";", ), ); ctx.log("info", `Profiled ${body.length} rows and ${names.length} columns`); return { rows: body.length, columnCount: names.length, delimiter: sep === "\t" ? "tab" : sep, raggedRows: body.filter((r) => r.length !== header.length).length, columns, }; }, });