@sqlrooms/ai 0.26.0-rc.5 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/tools/defaultInstructions.d.ts +7 -1
- package/dist/tools/defaultInstructions.d.ts.map +1 -1
- package/dist/tools/defaultInstructions.js +39 -2
- package/dist/tools/defaultInstructions.js.map +1 -1
- package/dist/tools/query/QueryToolResult.d.ts +2 -0
- package/dist/tools/query/QueryToolResult.d.ts.map +1 -1
- package/dist/tools/query/QueryToolResult.js +2 -2
- package/dist/tools/query/QueryToolResult.js.map +1 -1
- package/dist/tools/query/queryTool.d.ts +45 -3
- package/dist/tools/query/queryTool.d.ts.map +1 -1
- package/dist/tools/query/queryTool.js +19 -4
- package/dist/tools/query/queryTool.js.map +1 -1
- package/package.json +10 -10
package/dist/index.d.ts
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
* @packageDocumentation
|
|
4
4
|
*/
|
|
5
5
|
export { QueryToolResult } from './tools/query/QueryToolResult';
|
|
6
|
-
export
|
|
6
|
+
export * from './tools/query/queryTool';
|
|
7
7
|
export { createDefaultAiTools } from './tools/defaultTools';
|
|
8
8
|
export type { DefaultToolsOptions } from './tools/defaultTools';
|
|
9
|
-
export { createDefaultAiInstructions } from './tools/defaultInstructions';
|
|
9
|
+
export { createDefaultAiInstructions, formatTablesForLLM } from './tools/defaultInstructions';
|
|
10
10
|
export * from '@sqlrooms/ai-core';
|
|
11
11
|
export * from '@sqlrooms/ai-config';
|
|
12
12
|
export * from '@sqlrooms/ai-settings';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAC,eAAe,EAAC,MAAM,+BAA+B,CAAC;AAC9D,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAC,eAAe,EAAC,MAAM,+BAA+B,CAAC;AAC9D,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAC,oBAAoB,EAAC,MAAM,sBAAsB,CAAC;AAC1D,YAAY,EAAC,mBAAmB,EAAC,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAC,2BAA2B,EAAE,kBAAkB,EAAC,MAAM,6BAA6B,CAAC;AAE5F,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
* @packageDocumentation
|
|
4
4
|
*/
|
|
5
5
|
export { QueryToolResult } from './tools/query/QueryToolResult';
|
|
6
|
-
export
|
|
6
|
+
export * from './tools/query/queryTool';
|
|
7
7
|
export { createDefaultAiTools } from './tools/defaultTools';
|
|
8
|
-
export { createDefaultAiInstructions } from './tools/defaultInstructions';
|
|
8
|
+
export { createDefaultAiInstructions, formatTablesForLLM } from './tools/defaultInstructions';
|
|
9
9
|
export * from '@sqlrooms/ai-core';
|
|
10
10
|
export * from '@sqlrooms/ai-config';
|
|
11
11
|
export * from '@sqlrooms/ai-settings';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAC,eAAe,EAAC,MAAM,+BAA+B,CAAC;AAC9D,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAC,eAAe,EAAC,MAAM,+BAA+B,CAAC;AAC9D,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAC,oBAAoB,EAAC,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAC,2BAA2B,EAAE,kBAAkB,EAAC,MAAM,6BAA6B,CAAC;AAE5F,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC","sourcesContent":["/**\n * {@include ../README.md}\n * @packageDocumentation\n */\n\nexport {QueryToolResult} from './tools/query/QueryToolResult';\nexport * from './tools/query/queryTool';\nexport {createDefaultAiTools} from './tools/defaultTools';\nexport type {DefaultToolsOptions} from './tools/defaultTools';\nexport {createDefaultAiInstructions, formatTablesForLLM} from './tools/defaultInstructions';\n\nexport * from '@sqlrooms/ai-core';\nexport * from '@sqlrooms/ai-config';\nexport * from '@sqlrooms/ai-settings';\n"]}
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { AiSliceState } from '@sqlrooms/ai-core';
|
|
2
|
-
import { DuckDbSliceState } from '@sqlrooms/duckdb';
|
|
2
|
+
import { DuckDbSliceState, DataTable } from '@sqlrooms/duckdb';
|
|
3
3
|
import { StoreApi } from '@sqlrooms/room-shell';
|
|
4
|
+
/**
|
|
5
|
+
* Formats table schema information in a clean, LLM-friendly format
|
|
6
|
+
* @param tables Array of DataTable objects from the DuckDB state
|
|
7
|
+
* @returns Formatted string representation of table schemas
|
|
8
|
+
*/
|
|
9
|
+
export declare function formatTablesForLLM(tables: DataTable[]): string;
|
|
4
10
|
/**
|
|
5
11
|
* Returns the default system instructions for the AI assistant
|
|
6
12
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaultInstructions.d.ts","sourceRoot":"","sources":["../../src/tools/defaultInstructions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAC,gBAAgB,EAAC,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"defaultInstructions.d.ts","sourceRoot":"","sources":["../../src/tools/defaultInstructions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAC,gBAAgB,EAAE,SAAS,EAAC,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AAE9C;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,CAmC9D;AA4DD;;GAEG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,QAAQ,CAAC,YAAY,GAAG,gBAAgB,CAAC,GAC/C,MAAM,CAGR"}
|
|
@@ -1,3 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formats table schema information in a clean, LLM-friendly format
|
|
3
|
+
* @param tables Array of DataTable objects from the DuckDB state
|
|
4
|
+
* @returns Formatted string representation of table schemas
|
|
5
|
+
*/
|
|
6
|
+
export function formatTablesForLLM(tables) {
|
|
7
|
+
if (!tables || tables.length === 0) {
|
|
8
|
+
return 'No tables available in the database.';
|
|
9
|
+
}
|
|
10
|
+
return tables
|
|
11
|
+
.filter((table) => {
|
|
12
|
+
const schemaName = table.table?.schema || table.schema;
|
|
13
|
+
return !schemaName || schemaName === 'main';
|
|
14
|
+
})
|
|
15
|
+
.map((table) => {
|
|
16
|
+
const tableName = table.table?.table || table.tableName;
|
|
17
|
+
const schemaName = table.table?.schema || table.schema;
|
|
18
|
+
const fullTableName = schemaName && schemaName !== 'main'
|
|
19
|
+
? `${schemaName}.${tableName}`
|
|
20
|
+
: tableName;
|
|
21
|
+
// Build table header with metadata
|
|
22
|
+
const header = [fullTableName];
|
|
23
|
+
if (table.isView)
|
|
24
|
+
header.push('(view)');
|
|
25
|
+
if (table.rowCount !== undefined)
|
|
26
|
+
header.push(`[${table.rowCount.toLocaleString()} rows]`);
|
|
27
|
+
// Format columns with proper indentation
|
|
28
|
+
const columns = table.columns
|
|
29
|
+
.map((col) => ` ${col.name}: ${col.type}`)
|
|
30
|
+
.join('\n');
|
|
31
|
+
// Add comment if available
|
|
32
|
+
const comment = table.comment ? ` # ${table.comment}` : '';
|
|
33
|
+
return `${header.join(' ')}\n${columns}${comment ? '\n' + comment : ''}`;
|
|
34
|
+
})
|
|
35
|
+
.join('\n\n');
|
|
36
|
+
}
|
|
1
37
|
/**
|
|
2
38
|
* System prompt template for the AI assistant that provides instructions for:
|
|
3
39
|
* - Using DuckDB-specific SQL syntax and functions
|
|
@@ -52,13 +88,14 @@ For your final answer:
|
|
|
52
88
|
* If no sample rows provided: Never fabricate data. Direct users to the table component for actual results.
|
|
53
89
|
* If sample rows provided: Use them to enhance your analysis, but always direct users to the table component for complete results.
|
|
54
90
|
|
|
55
|
-
|
|
91
|
+
Available tables in the database (format: tableName [rowCount] followed by indented columns):
|
|
92
|
+
|
|
56
93
|
`;
|
|
57
94
|
/**
|
|
58
95
|
* Returns the default system instructions for the AI assistant
|
|
59
96
|
*/
|
|
60
97
|
export function createDefaultAiInstructions(store) {
|
|
61
98
|
const tables = store.getState().db.tables;
|
|
62
|
-
return `${DEFAULT_INSTRUCTIONS}\n${
|
|
99
|
+
return `${DEFAULT_INSTRUCTIONS}\n${formatTablesForLLM(tables)}`;
|
|
63
100
|
}
|
|
64
101
|
//# sourceMappingURL=defaultInstructions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaultInstructions.js","sourceRoot":"","sources":["../../src/tools/defaultInstructions.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG
|
|
1
|
+
{"version":3,"file":"defaultInstructions.js","sourceRoot":"","sources":["../../src/tools/defaultInstructions.ts"],"names":[],"mappings":"AAIA;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAAmB;IACpD,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnC,OAAO,sCAAsC,CAAC;IAChD,CAAC;IAED,OAAO,MAAM;S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G,OAAO,CAAC,CAAC,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAC3E,CAAC,CAAC;SACD,IAAI,CAAC,MAAM,CAAC,CAAC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiD5B,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAgD;IAEhD,MAAM,MAAM,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC;IAC1C,OAAO,GAAG,oBAAoB,KAAK,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC;AAClE,CAAC","sourcesContent":["import {AiSliceState} from '@sqlrooms/ai-core';\nimport {DuckDbSliceState, DataTable} from '@sqlrooms/duckdb';\nimport {StoreApi} from '@sqlrooms/room-shell';\n\n/**\n * Formats table schema information in a clean, LLM-friendly format\n * @param tables Array of DataTable objects from the DuckDB state\n * @returns Formatted string representation of table schemas\n */\nexport function formatTablesForLLM(tables: DataTable[]): string {\n if (!tables || tables.length === 0) {\n return 'No tables available in the database.';\n }\n\n return tables\n .filter((table) => {\n const schemaName = table.table?.schema || table.schema;\n return !schemaName || schemaName === 'main';\n })\n .map((table) => {\n const tableName = table.table?.table || table.tableName;\n const schemaName = table.table?.schema || table.schema;\n const fullTableName =\n schemaName && schemaName !== 'main'\n ? `${schemaName}.${tableName}`\n : tableName;\n\n // Build table header with metadata\n const header = [fullTableName];\n if (table.isView) header.push('(view)');\n if (table.rowCount !== undefined)\n header.push(`[${table.rowCount.toLocaleString()} rows]`);\n\n // Format columns with proper indentation\n const columns = table.columns\n .map((col) => ` ${col.name}: ${col.type}`)\n .join('\\n');\n\n // Add comment if available\n const comment = table.comment ? ` # ${table.comment}` : '';\n\n return `${header.join(' ')}\\n${columns}${comment ? '\\n' + comment : ''}`;\n })\n .join('\\n\\n');\n}\n\n/**\n * System prompt template for the AI assistant that provides instructions for:\n * - Using DuckDB-specific SQL syntax and functions\n * - Handling query results and error cases\n * - Creating visualizations with VegaLite\n * - Formatting final answers\n */\nconst DEFAULT_INSTRUCTIONS = `\nYou are analyzing tables in DuckDB database in the context of a room.\n\nInstructions for analysis:\n- When using 'query' tool, please assign parameter 'type' with value 'query'\n- Use DuckDB-specific SQL syntax and functions (not Oracle, PostgreSQL, or other SQL dialects)\n- Some key DuckDB-specific functions to use:\n * regexp_matches() for regex (not regexp_like)\n * strftime() for date formatting (not to_char)\n * list_aggregate() for array operations\n * unnest() for array expansion\n * regr_sxy()\n * corr()\n * skewness()\n- Please always try to use SQL queries to answer users questions\n- Please run tool calls sequentially, don't run multiple tool calls in parallel\n- IMPORTANT: Do not list out raw query results in your response. Instead:\n * Describe the results in natural language\n * Provide summary statistics\n * Use comparisons and relative terms\n * Include only the most relevant values if necessary\n- Break down complex problems into smaller steps\n- Use \"SUMMARIZE table_name\"for quick overview of the table\n- Please don't modify data\n- IMPORTANT: When you receive an error response from a tool call (where success: false):\n * Stop making any further tool calls immediately\n * Return a final answer that includes the error message\n * Explain what went wrong and suggest possible fixes if applicable\n\nWhen creating visualizations:\n- Follow VegaLite syntax\n- Choose appropriate chart types based on the data and analysis goals\n- Use clear titles and axis labels\n- Consider color schemes for better readability\n- Add meaningful tooltips when relevant\n- Format numbers and dates appropriately\n- Use aggregations when dealing with large datasets\n\nFor your final answer:\n- Provide an explanation for how you got it\n- Explain your reasoning step by step\n- Include relevant statistics or metrics\n- For each prompt, please always provide the final answer.\n- IMPORTANT: Query tool results may include sample rows (firstRows) or may be empty:\n * If no sample rows provided: Never fabricate data. Direct users to the table component for actual results.\n * If sample rows provided: Use them to enhance your analysis, but always direct users to the table component for complete results.\n\nAvailable tables in the database (format: tableName [rowCount] followed by indented columns):\n\n`;\n\n/**\n * Returns the default system instructions for the AI assistant\n */\nexport function createDefaultAiInstructions(\n store: StoreApi<AiSliceState & DuckDbSliceState>,\n): string {\n const tables = store.getState().db.tables;\n return `${DEFAULT_INSTRUCTIONS}\\n${formatTablesForLLM(tables)}`;\n}\n"]}
|
|
@@ -4,6 +4,8 @@ type QueryToolResultProps = {
|
|
|
4
4
|
sqlQuery: string;
|
|
5
5
|
/** Provided in case the query result is already an arrow table */
|
|
6
6
|
arrowTable?: arrow.Table;
|
|
7
|
+
/** Whether to show the SQL text in the result */
|
|
8
|
+
showSql?: boolean;
|
|
7
9
|
};
|
|
8
10
|
export declare function QueryToolResult(props: QueryToolResultProps): import("react/jsx-runtime").JSX.Element;
|
|
9
11
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryToolResult.d.ts","sourceRoot":"","sources":["../../../src/tools/query/QueryToolResult.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAGtC,KAAK,oBAAoB,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,kEAAkE;IAClE,UAAU,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"QueryToolResult.d.ts","sourceRoot":"","sources":["../../../src/tools/query/QueryToolResult.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAGtC,KAAK,oBAAoB,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,kEAAkE;IAClE,UAAU,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC;IACzB,iDAAiD;IACjD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,wBAAgB,eAAe,CAAC,KAAK,EAAE,oBAAoB,2CA6C1D"}
|
|
@@ -3,8 +3,8 @@ import { DataTableModal } from '@sqlrooms/data-table';
|
|
|
3
3
|
import { Button, CopyButton, useDisclosure } from '@sqlrooms/ui';
|
|
4
4
|
import { TableIcon } from 'lucide-react';
|
|
5
5
|
export function QueryToolResult(props) {
|
|
6
|
-
const { title, sqlQuery } = props;
|
|
6
|
+
const { title, sqlQuery, showSql = true } = props;
|
|
7
7
|
const tableModal = useDisclosure();
|
|
8
|
-
return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "text-muted-foreground bg-muted relative max-h-[150px] w-full overflow-auto rounded-md p-2 font-mono text-xs", children: [_jsx("pre", { className: "whitespace-pre-wrap break-words pr-8", children: sqlQuery }), _jsx("div", { className: "absolute right-1 top-1", children: _jsx(CopyButton, { text: sqlQuery, variant: "ghost", size: "icon", className: "h-6 w-6", ariaLabel: "Copy SQL" }) })] }), _jsx("div", { className: "flex items-center gap-
|
|
8
|
+
return (_jsxs(_Fragment, { children: [showSql && (_jsxs("div", { className: "text-muted-foreground bg-muted relative max-h-[150px] w-full overflow-auto rounded-md p-2 font-mono text-xs", children: [_jsx("pre", { className: "whitespace-pre-wrap break-words pr-8", children: sqlQuery }), _jsx("div", { className: "absolute right-1 top-1", children: _jsx(CopyButton, { text: sqlQuery, variant: "ghost", size: "icon", className: "h-6 w-6", ariaLabel: "Copy SQL" }) })] })), _jsx("div", { className: "flex items-center gap-1 text-gray-500 dark:text-gray-400", children: _jsxs(Button, { variant: "ghost", size: "xs", onClick: tableModal.onOpen, children: [_jsx(TableIcon, { className: "h-4 w-4" }), _jsx("h3", { className: "text-xs", children: "Show Query Result" })] }) }), 'arrowTable' in props ? (props.arrowTable ? (_jsx(DataTableModal, { title: title, arrowTable: props.arrowTable, tableModal: tableModal })) : (_jsx("div", { className: "p-4 text-xs", children: "No data" }))) : (_jsx(DataTableModal, { title: title, query: sqlQuery, tableModal: tableModal }))] }));
|
|
9
9
|
}
|
|
10
10
|
//# sourceMappingURL=QueryToolResult.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryToolResult.js","sourceRoot":"","sources":["../../../src/tools/query/QueryToolResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,cAAc,E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AAE,KAAK,EACZ,UAAU,EAAE,KAAK,CAAC,UAAU,EAC5B,UAAU,EAAE,UAAU,GACtB,CACH,CAAC,CAAC,CAAC,CACF,cAAK,SAAS,EAAC,aAAa,wBAAc,CAC3C,CACF,CAAC,CAAC,CAAC,CACF,KAAC,cAAc,IACb,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,QAAQ,EACf,UAAU,EAAE,UAAU,GACtB,CACH,IACA,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import {DataTableModal} from '@sqlrooms/data-table';\nimport {Button, CopyButton, useDisclosure} from '@sqlrooms/ui';\nimport * as arrow from 'apache-arrow';\nimport {TableIcon} from 'lucide-react';\n\ntype QueryToolResultProps = {\n title: string;\n sqlQuery: string;\n /** Provided in case the query result is already an arrow table */\n arrowTable?: arrow.Table;\n /** Whether to show the SQL text in the result */\n showSql?: boolean;\n};\n\nexport function QueryToolResult(props: QueryToolResultProps) {\n const {title, sqlQuery, showSql = true} = props;\n const tableModal = useDisclosure();\n return (\n <>\n {showSql && (\n <div className=\"text-muted-foreground bg-muted relative max-h-[150px] w-full overflow-auto rounded-md p-2 font-mono text-xs\">\n <pre className=\"whitespace-pre-wrap break-words pr-8\">{sqlQuery}</pre>\n <div className=\"absolute right-1 top-1\">\n <CopyButton\n text={sqlQuery}\n variant=\"ghost\"\n size=\"icon\"\n className=\"h-6 w-6\"\n ariaLabel=\"Copy SQL\"\n />\n </div>\n </div>\n )}\n <div className=\"flex items-center gap-1 text-gray-500 dark:text-gray-400\">\n <Button variant=\"ghost\" size=\"xs\" onClick={tableModal.onOpen}>\n <TableIcon className=\"h-4 w-4\" />\n <h3 className=\"text-xs\">Show Query Result</h3>\n </Button>\n </div>\n\n {'arrowTable' in props ? (\n props.arrowTable ? (\n <DataTableModal\n title={title}\n arrowTable={props.arrowTable}\n tableModal={tableModal}\n />\n ) : (\n <div className=\"p-4 text-xs\">No data</div>\n )\n ) : (\n <DataTableModal\n title={title}\n query={sqlQuery}\n tableModal={tableModal}\n />\n )}\n </>\n );\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { AiSliceState } from '@sqlrooms/ai-core';
|
|
2
|
-
import {
|
|
3
|
-
import { DuckDbSliceState } from '@sqlrooms/duckdb';
|
|
2
|
+
import { DuckDbConnector, DuckDbSliceState } from '@sqlrooms/duckdb';
|
|
4
3
|
import type { StoreApi } from '@sqlrooms/room-shell';
|
|
5
4
|
import { z } from 'zod';
|
|
5
|
+
import { QueryToolResult } from './QueryToolResult';
|
|
6
6
|
export declare const QueryToolParameters: z.ZodObject<{
|
|
7
7
|
type: z.ZodLiteral<"query">;
|
|
8
8
|
sqlQuery: z.ZodString;
|
|
@@ -28,5 +28,47 @@ export type QueryToolOptions = {
|
|
|
28
28
|
autoSummary?: boolean;
|
|
29
29
|
numberOfRowsToShareWithLLM?: number;
|
|
30
30
|
};
|
|
31
|
-
export declare function createQueryTool(store: StoreApi<AiSliceState & DuckDbSliceState>, options?: QueryToolOptions):
|
|
31
|
+
export declare function createQueryTool(store: StoreApi<AiSliceState & DuckDbSliceState>, options?: QueryToolOptions): {
|
|
32
|
+
name: string;
|
|
33
|
+
description: string;
|
|
34
|
+
parameters: z.ZodObject<{
|
|
35
|
+
type: z.ZodLiteral<"query">;
|
|
36
|
+
sqlQuery: z.ZodString;
|
|
37
|
+
reasoning: z.ZodString;
|
|
38
|
+
}, z.core.$strip>;
|
|
39
|
+
execute: (params: QueryToolParameters, options?: {
|
|
40
|
+
abortSignal?: AbortSignal;
|
|
41
|
+
}) => Promise<{
|
|
42
|
+
llmResult: {
|
|
43
|
+
success: boolean;
|
|
44
|
+
data: {
|
|
45
|
+
firstRows?: Record<string, unknown>[] | undefined;
|
|
46
|
+
type: "query";
|
|
47
|
+
summary: Record<string, unknown>[] | null;
|
|
48
|
+
};
|
|
49
|
+
details?: undefined;
|
|
50
|
+
errorMessage?: undefined;
|
|
51
|
+
};
|
|
52
|
+
additionalData: {
|
|
53
|
+
title: string;
|
|
54
|
+
sqlQuery: string;
|
|
55
|
+
};
|
|
56
|
+
} | {
|
|
57
|
+
llmResult: {
|
|
58
|
+
success: boolean;
|
|
59
|
+
details: string;
|
|
60
|
+
errorMessage: string;
|
|
61
|
+
data?: undefined;
|
|
62
|
+
};
|
|
63
|
+
additionalData?: undefined;
|
|
64
|
+
}>;
|
|
65
|
+
component: typeof QueryToolResult;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Generates summary statistics for a SQL query result
|
|
69
|
+
* @param connector - DuckDB connection instance
|
|
70
|
+
* @param sqlQuery - SQL SELECT query to analyze
|
|
71
|
+
* @returns Summary statistics as JSON object, or null if the query is not a SELECT statement or if summary generation fails
|
|
72
|
+
*/
|
|
73
|
+
export declare function getQuerySummary(connector: DuckDbConnector, sqlQuery: string): Promise<Record<string, unknown>[] | null>;
|
|
32
74
|
//# sourceMappingURL=queryTool.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryTool.d.ts","sourceRoot":"","sources":["../../../src/tools/query/queryTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAC/C,OAAO,
|
|
1
|
+
{"version":3,"file":"queryTool.d.ts","sourceRoot":"","sources":["../../../src/tools/query/queryTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,gBAAgB,EAEjB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AACtB,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAC;AAElD,eAAO,MAAM,mBAAmB;;;;iBAI9B,CAAC;AAEH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,CAAC,EAAE;QACL,IAAI,EAAE,OAAO,CAAC;QACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC;QAC1C,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;KACvC,CAAC;IACF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,0BAA0B,CAAC,EAAE,MAAM,CAAC;CACrC,CAAC;AAEF,wBAAgB,eAAe,CAC7B,KAAK,EAAE,QAAQ,CAAC,YAAY,GAAG,gBAAgB,CAAC,EAChD,OAAO,CAAC,EAAE,gBAAgB;;;;;;;;sBAcd,mBAAmB,YACjB;QAAC,WAAW,CAAC,EAAE,WAAW,CAAA;KAAC;;;;;;;;;;;;;;;;;;;;;;;;;EAwG1C;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,SAAS,EAAE,eAAe,EAC1B,QAAQ,EAAE,MAAM,6CAejB"}
|
|
@@ -14,12 +14,15 @@ export function createQueryTool(store, options) {
|
|
|
14
14
|
Please only run one query at a time.
|
|
15
15
|
If a query fails, please don't try to run it again with the same syntax.`,
|
|
16
16
|
parameters: QueryToolParameters,
|
|
17
|
-
execute: async (params) => {
|
|
17
|
+
execute: async (params, options) => {
|
|
18
18
|
const { type, sqlQuery } = params;
|
|
19
|
+
const abortSignal = options?.abortSignal;
|
|
19
20
|
try {
|
|
21
|
+
// Check if aborted before starting
|
|
22
|
+
if (abortSignal?.aborted) {
|
|
23
|
+
throw new Error('Query execution was aborted');
|
|
24
|
+
}
|
|
20
25
|
const connector = await store.getState().db.getConnector();
|
|
21
|
-
// TODO use options.abortSignal: maybe call db.cancelPendingQuery
|
|
22
|
-
const result = await connector.query(sqlQuery);
|
|
23
26
|
const parsedQuery = await store.getState().db.sqlSelectToJson(sqlQuery);
|
|
24
27
|
if (parsedQuery.error &&
|
|
25
28
|
// Only SELECT statements can be serialized to json, so we ignore not implemented errors
|
|
@@ -36,11 +39,23 @@ If a query fails, please don't try to run it again with the same syntax.`,
|
|
|
36
39
|
throw new Error('Query is not a valid SELECT statement');
|
|
37
40
|
}
|
|
38
41
|
}
|
|
42
|
+
// Check if aborted before running query
|
|
43
|
+
if (abortSignal?.aborted) {
|
|
44
|
+
throw new Error('Query execution was aborted');
|
|
45
|
+
}
|
|
46
|
+
const result = await connector.query(sqlQuery);
|
|
47
|
+
// Check if aborted after query execution
|
|
48
|
+
if (abortSignal?.aborted) {
|
|
49
|
+
throw new Error('Query execution was aborted');
|
|
50
|
+
}
|
|
39
51
|
const summaryData = await (async () => {
|
|
40
52
|
if (!autoSummary)
|
|
41
53
|
return null;
|
|
42
54
|
if (parsedQuery.error)
|
|
43
55
|
return null;
|
|
56
|
+
// Check if aborted before generating summary
|
|
57
|
+
if (abortSignal?.aborted)
|
|
58
|
+
return null;
|
|
44
59
|
const lastNode = parsedQuery.statements[parsedQuery.statements.length - 1]?.node;
|
|
45
60
|
// Only get summary if the last statement isn't already a SUMMARIZE query
|
|
46
61
|
if (lastNode?.type === 'SELECT_NODE' &&
|
|
@@ -91,7 +106,7 @@ If a query fails, please don't try to run it again with the same syntax.`,
|
|
|
91
106
|
* @param sqlQuery - SQL SELECT query to analyze
|
|
92
107
|
* @returns Summary statistics as JSON object, or null if the query is not a SELECT statement or if summary generation fails
|
|
93
108
|
*/
|
|
94
|
-
async function getQuerySummary(connector, sqlQuery) {
|
|
109
|
+
export async function getQuerySummary(connector, sqlQuery) {
|
|
95
110
|
if (!sqlQuery.toLowerCase().trim().startsWith('select')) {
|
|
96
111
|
return null;
|
|
97
112
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryTool.js","sourceRoot":"","sources":["../../../src/tools/query/queryTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"queryTool.js","sourceRoot":"","sources":["../../../src/tools/query/queryTool.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAGhB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AACtB,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAC;AAElD,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC1C,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;IACxB,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;IACpB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;CACtB,CAAC,CAAC;AA0BH,MAAM,UAAU,eAAe,CAC7B,KAAgD,EAChD,OAA0B;IAE1B,MAAM,EACJ,QAAQ,GAAG,IAAI,EACf,WAAW,GAAG,KAAK,EACnB,0BAA0B,GAAG,CAAC,GAC/B,GAAG,OAAO,IAAI,EAAE,CAAC;IAClB,OAAO;QACL,IAAI,EAAE,OAAO;QACb,WAAW,EAAE;;yEAEwD;QACrE,UAAU,EAAE,mBAAmB;QAC/B,OAAO,EAAE,KAAK,EACZ,MAA2B,EAC3B,OAAqC,EACrC,EAAE;YACF,MAAM,EAAC,IAAI,EAAE,QAAQ,EAAC,GAAG,MAAM,CAAC;YAChC,MAAM,WAAW,GAAG,OAAO,EAAE,WAAW,CAAC;YAEzC,IAAI,CAAC;gBACH,mCAAmC;gBACnC,IAAI,WAAW,EAAE,OAAO,EAAE,CAAC;oBACzB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC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AE,CAAC;gBACf,OAAO;oBACL,SAAS,EAAE;wBACT,OAAO,EAAE,KAAK;wBACd,OAAO,EAAE,yBAAyB;wBAClC,YAAY,EACV,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe;qBAC3D;iBACF,CAAC;YACJ,CAAC;QACH,CAAC;QACD,SAAS,EAAE,eAAe;KAC3B,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,SAA0B,EAC1B,QAAgB;IAEhB,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACH,MAAM,aAAa,GAAG,MAAM,SAAS,CAAC,KAAK,CAAC;QACxC,QAAQ;MACV,CAAC,CAAC;QACJ,OAAO,gBAAgB,CAAC,aAAa,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;QAC/D,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {AiSliceState} from '@sqlrooms/ai-core';\nimport {\n arrowTableToJson,\n DuckDbConnector,\n DuckDbSliceState,\n splitSqlStatements,\n} from '@sqlrooms/duckdb';\nimport type {StoreApi} from '@sqlrooms/room-shell';\nimport {z} from 'zod';\nimport {QueryToolResult} from './QueryToolResult';\n\nexport const QueryToolParameters = z.object({\n type: z.literal('query'),\n sqlQuery: z.string(),\n reasoning: z.string(),\n});\n\nexport type QueryToolParameters = z.infer<typeof QueryToolParameters>;\n\nexport type QueryToolLlmResult = {\n success: boolean;\n data?: {\n type: 'query';\n summary: Record<string, unknown>[] | null;\n firstRows?: Record<string, unknown>[];\n };\n details?: string;\n errorMessage?: string;\n};\n\nexport type QueryToolAdditionalData = {\n title: string;\n sqlQuery: string;\n};\n\nexport type QueryToolOptions = {\n readOnly?: boolean;\n autoSummary?: boolean;\n numberOfRowsToShareWithLLM?: number;\n};\n\nexport function createQueryTool(\n store: StoreApi<AiSliceState & DuckDbSliceState>,\n options?: QueryToolOptions,\n) {\n const {\n readOnly = true,\n autoSummary = false,\n numberOfRowsToShareWithLLM = 0,\n } = options || {};\n return {\n name: 'query',\n description: `A tool for running SQL queries on the tables in the database.\nPlease only run one query at a time.\nIf a query fails, please don't try to run it again with the same syntax.`,\n parameters: QueryToolParameters,\n execute: async (\n params: QueryToolParameters,\n options?: {abortSignal?: AbortSignal},\n ) => {\n const {type, sqlQuery} = params;\n const abortSignal = options?.abortSignal;\n\n try {\n // Check if aborted before starting\n if (abortSignal?.aborted) {\n throw new Error('Query execution was aborted');\n }\n\n const connector = await store.getState().db.getConnector();\n const parsedQuery = await store.getState().db.sqlSelectToJson(sqlQuery);\n\n if (\n parsedQuery.error &&\n // Only SELECT statements can be serialized to json, so we ignore not implemented errors\n parsedQuery.error_type !== 'not implemented'\n ) {\n throw new Error(parsedQuery.error_message);\n }\n\n if (readOnly) {\n if (parsedQuery.error) {\n throw new Error(\n `Query is not a valid SELECT statement: ${parsedQuery.error_message}`,\n );\n }\n if (\n parsedQuery.statements.length !== 1 || // only one statement allowed\n parsedQuery.statements[0]?.node.type !== 'SELECT_NODE' // only SELECT statements allowed\n ) {\n throw new Error('Query is not a valid SELECT statement');\n }\n }\n\n // Check if aborted before running query\n if (abortSignal?.aborted) {\n throw new Error('Query execution was aborted');\n }\n\n const result = await connector.query(sqlQuery);\n\n // Check if aborted after query execution\n if (abortSignal?.aborted) {\n throw new Error('Query execution was aborted');\n }\n\n const summaryData = await (async () => {\n if (!autoSummary) return null;\n if (parsedQuery.error) return null;\n\n // Check if aborted before generating summary\n if (abortSignal?.aborted) return null;\n\n const lastNode =\n parsedQuery.statements[parsedQuery.statements.length - 1]?.node;\n\n // Only get summary if the last statement isn't already a SUMMARIZE query\n if (\n lastNode?.type === 'SELECT_NODE' &&\n lastNode?.from_table?.show_type === 'SUMMARY'\n ) {\n return arrowTableToJson(result);\n }\n const statements = splitSqlStatements(sqlQuery);\n const lastStatement = statements[statements.length - 1];\n if (!lastStatement) return null;\n return await getQuerySummary(connector, lastStatement);\n })();\n\n // Conditionally get rows of the result as a json object based on numberOfRowsToShareWithLLM\n const firstRows =\n numberOfRowsToShareWithLLM > 0\n ? arrowTableToJson(result.slice(0, numberOfRowsToShareWithLLM))\n : [];\n\n return {\n llmResult: {\n success: true,\n data: {\n type,\n summary: summaryData,\n ...(numberOfRowsToShareWithLLM > 0 ? {firstRows} : {}),\n },\n },\n additionalData: {\n title: 'Query Result',\n sqlQuery,\n },\n };\n } catch (error) {\n return {\n llmResult: {\n success: false,\n details: 'Query execution failed.',\n errorMessage:\n error instanceof Error ? error.message : 'Unknown error',\n },\n };\n }\n },\n component: QueryToolResult,\n };\n}\n\n/**\n * Generates summary statistics for a SQL query result\n * @param connector - DuckDB connection instance\n * @param sqlQuery - SQL SELECT query to analyze\n * @returns Summary statistics as JSON object, or null if the query is not a SELECT statement or if summary generation fails\n */\nexport async function getQuerySummary(\n connector: DuckDbConnector,\n sqlQuery: string,\n) {\n if (!sqlQuery.toLowerCase().trim().startsWith('select')) {\n return null;\n }\n\n try {\n const summaryResult = await connector.query(`SUMMARIZE (\n ${sqlQuery}\n )`);\n return arrowTableToJson(summaryResult);\n } catch (error) {\n console.warn('Failed to get summary for query. Error:', error);\n return null;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sqlrooms/ai",
|
|
3
|
-
"version": "0.26.0
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"@openassistant/utils": "1.0.0-alpha.0",
|
|
22
|
-
"@sqlrooms/ai-config": "0.26.0
|
|
23
|
-
"@sqlrooms/ai-core": "0.26.0
|
|
24
|
-
"@sqlrooms/ai-settings": "0.26.0
|
|
25
|
-
"@sqlrooms/data-table": "0.26.0
|
|
26
|
-
"@sqlrooms/duckdb": "0.26.0
|
|
27
|
-
"@sqlrooms/room-shell": "0.26.0
|
|
28
|
-
"@sqlrooms/ui": "0.26.0
|
|
29
|
-
"@sqlrooms/utils": "0.26.0
|
|
22
|
+
"@sqlrooms/ai-config": "0.26.0",
|
|
23
|
+
"@sqlrooms/ai-core": "0.26.0",
|
|
24
|
+
"@sqlrooms/ai-settings": "0.26.0",
|
|
25
|
+
"@sqlrooms/data-table": "0.26.0",
|
|
26
|
+
"@sqlrooms/duckdb": "0.26.0",
|
|
27
|
+
"@sqlrooms/room-shell": "0.26.0",
|
|
28
|
+
"@sqlrooms/ui": "0.26.0",
|
|
29
|
+
"@sqlrooms/utils": "0.26.0",
|
|
30
30
|
"ai": "^5.0.44",
|
|
31
31
|
"immer": "^10.1.3",
|
|
32
32
|
"lucide-react": "^0.544.0",
|
|
@@ -48,5 +48,5 @@
|
|
|
48
48
|
"typecheck": "tsc --noEmit",
|
|
49
49
|
"typedoc": "typedoc"
|
|
50
50
|
},
|
|
51
|
-
"gitHead": "
|
|
51
|
+
"gitHead": "3376e76ddfa3c54097b79a20b88a1c37814dca61"
|
|
52
52
|
}
|