forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.ts
More file actions
68 lines (63 loc) · 1.68 KB
/
Copy pathquery.ts
File metadata and controls
68 lines (63 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import { tool } from "@langchain/core/tools";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function parseCsv(raw: string): Record<string, string>[] {
const lines = raw.trim().split(/\r?\n/);
if (lines.length === 0) return [];
const headers = lines[0].split(",");
const rows: Record<string, string>[] = [];
for (let i = 1; i < lines.length; i++) {
const cells = splitCsvLine(lines[i]);
const row: Record<string, string> = {};
headers.forEach((h, idx) => {
row[h] = cells[idx] ?? "";
});
rows.push(row);
}
return rows;
}
function splitCsvLine(line: string): string[] {
const out: string[] = [];
let cur = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (inQuotes) {
if (ch === '"' && line[i + 1] === '"') {
cur += '"';
i++;
} else if (ch === '"') {
inQuotes = false;
} else {
cur += ch;
}
} else if (ch === '"') {
inQuotes = true;
} else if (ch === ",") {
out.push(cur);
cur = "";
} else {
cur += ch;
}
}
out.push(cur);
return out;
}
const _cached_data = parseCsv(
readFileSync(path.join(__dirname, "db.csv"), "utf8"),
);
export const query_data = tool(
(_input: { query: string }) => {
return JSON.stringify(_cached_data);
},
{
name: "query_data",
description:
"Query the database, takes natural language. Always call before showing a chart or graph.",
schema: z.object({ query: z.string() }),
},
);