@sqlrooms/ai 0.24.20 → 0.24.22
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/AiSlice.d.ts +2 -4
- package/dist/AiSlice.d.ts.map +1 -1
- package/dist/AiSlice.js +3 -6
- package/dist/AiSlice.js.map +1 -1
- package/dist/analysis.d.ts +15 -1
- package/dist/analysis.d.ts.map +1 -1
- package/dist/analysis.js +43 -13
- package/dist/analysis.js.map +1 -1
- package/dist/components/tools/QueryToolResult.d.ts +4 -1
- package/dist/components/tools/QueryToolResult.d.ts.map +1 -1
- package/dist/components/tools/QueryToolResult.js +3 -2
- package/dist/components/tools/QueryToolResult.js.map +1 -1
- package/dist/components/tools/ToolErrorMessage.d.ts +39 -0
- package/dist/components/tools/ToolErrorMessage.d.ts.map +1 -0
- package/dist/components/tools/ToolErrorMessage.js +20 -0
- package/dist/components/tools/ToolErrorMessage.js.map +1 -0
- package/dist/components/tools/ToolResult.d.ts.map +1 -1
- package/dist/components/tools/ToolResult.js +3 -9
- package/dist/components/tools/ToolResult.js.map +1 -1
- package/dist/components/tools/ToolResultErrorBoundary.d.ts.map +1 -1
- package/dist/components/tools/ToolResultErrorBoundary.js +3 -2
- package/dist/components/tools/ToolResultErrorBoundary.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
package/dist/AiSlice.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { ExtendedTool } from '@openassistant/utils';
|
|
|
2
2
|
import { DataTable } from '@sqlrooms/duckdb';
|
|
3
3
|
import { BaseRoomConfig, RoomShellSliceState, type StateCreator } from '@sqlrooms/room-shell';
|
|
4
4
|
import { z } from 'zod';
|
|
5
|
+
import { DefaultToolsOptions } from './analysis';
|
|
5
6
|
import { AnalysisSessionSchema } from './schemas';
|
|
6
7
|
export declare const AiSliceConfig: z.ZodObject<{
|
|
7
8
|
ai: z.ZodObject<{
|
|
@@ -435,10 +436,7 @@ export interface AiSliceOptions {
|
|
|
435
436
|
* @returns The instructions string to use
|
|
436
437
|
*/
|
|
437
438
|
getInstructions?: (tablesSchema: DataTable[]) => string;
|
|
438
|
-
|
|
439
|
-
* Number of rows to share with LLM (default: 0)
|
|
440
|
-
*/
|
|
441
|
-
numberOfRowsToShareWithLLM?: number;
|
|
439
|
+
toolsOptions?: DefaultToolsOptions;
|
|
442
440
|
}
|
|
443
441
|
/**
|
|
444
442
|
* API key configuration for the AI slice
|
package/dist/AiSlice.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiSlice.d.ts","sourceRoot":"","sources":["../src/AiSlice.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,YAAY,EAAC,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAC,SAAS,EAAC,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EACL,cAAc,EAEd,mBAAmB,EAEnB,KAAK,YAAY,EAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"AiSlice.d.ts","sourceRoot":"","sources":["../src/AiSlice.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,YAAY,EAAC,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAC,SAAS,EAAC,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EACL,cAAc,EAEd,mBAAmB,EAEnB,KAAK,YAAY,EAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AACtB,OAAO,EAAC,mBAAmB,EAA+B,MAAM,YAAY,CAAC;AAC7E,OAAO,EAEL,qBAAqB,EAEtB,MAAM,WAAW,CAAC;AAEnB,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gCAiHF,CAAC;kCAAsB,CAAA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;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAC,GAAG,CACrD;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,KAAK,CAAA;CAAC,GACpC;IAAC,SAAS,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAC,CAClE,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,cAAc,GAAG,gBAAgB,CAAC;AAEpE,wBAAgB,aAAa,CAAC,EAAE,SAAS,cAAc,GAAG,aAAa,EACrE,MAAM,EAAE,mBAAmB,GAC1B,YAAY,CAAC,YAAY,CAAC,CAiT5B;AAmGD,KAAK,gBAAgB,GAAG,cAAc,GAAG,aAAa,CAAC;AACvD,KAAK,yBAAyB,GAAG,mBAAmB,CAAC,gBAAgB,CAAC,GACpE,YAAY,CAAC;AAEf,wBAAgB,cAAc,CAAC,CAAC,EAC9B,QAAQ,EAAE,CAAC,KAAK,EAAE,yBAAyB,KAAK,CAAC,GAChD,CAAC,CAMH"}
|
package/dist/AiSlice.js
CHANGED
|
@@ -30,14 +30,14 @@ export function createDefaultAiConfig(props) {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
export function createAiSlice(params) {
|
|
33
|
-
const { getApiKey, baseUrl, initialAnalysisPrompt = '', customTools = {}, getInstructions,
|
|
33
|
+
const { getApiKey, baseUrl, initialAnalysisPrompt = '', customTools = {}, getInstructions, toolsOptions, defaultModel = 'gpt-4o-mini', } = params;
|
|
34
34
|
return createSlice((set, get, store) => {
|
|
35
35
|
return {
|
|
36
36
|
ai: {
|
|
37
37
|
analysisPrompt: initialAnalysisPrompt,
|
|
38
38
|
isRunningAnalysis: false,
|
|
39
39
|
tools: {
|
|
40
|
-
...getDefaultTools(store,
|
|
40
|
+
...getDefaultTools(store, toolsOptions),
|
|
41
41
|
...customTools,
|
|
42
42
|
},
|
|
43
43
|
setAnalysisPrompt: (prompt) => {
|
|
@@ -210,10 +210,7 @@ export function createAiSlice(params) {
|
|
|
210
210
|
baseUrl: currentSession.baseUrl || baseUrl,
|
|
211
211
|
prompt: get().ai.analysisPrompt,
|
|
212
212
|
abortController,
|
|
213
|
-
tools:
|
|
214
|
-
...getDefaultTools(store, numberOfRowsToShareWithLLM),
|
|
215
|
-
...customTools,
|
|
216
|
-
},
|
|
213
|
+
tools: get().ai.tools,
|
|
217
214
|
getInstructions,
|
|
218
215
|
onStreamResult: (isCompleted, streamMessage) => {
|
|
219
216
|
set(makeResultsAppender({
|
package/dist/AiSlice.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiSlice.js","sourceRoot":"","sources":["../src/AiSlice.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AAE9C,OAAO,EAEL,WAAW,EAEX,qBAAqB,GAEtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAC,OAAO,EAAgB,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AACtB,OAAO,EAAC,eAAe,EAAE,WAAW,EAAC,MAAM,YAAY,CAAC;AACxD,OAAO,EAEL,qBAAqB,GAEtB,MAAM,WAAW,CAAC;AAEnB,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC;QACX,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,qBAAqB,CAAC;QACxC,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;KACxC,CAAC;CACH,CAAC,CAAC;AAGH,MAAM,UAAU,qBAAqB,CACnC,KAAmC;IAEnC,MAAM,gBAAgB,GAAG,QAAQ,EAAE,CAAC;IACpC,OAAO;QACL,EAAE,EAAE;YACF,QAAQ,EAA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jB,MAAM,CAAC,YAAY,GAAG,YAAY,CAAC;YACrC,CAAC;YACD,IAAI,WAAW,EAAE,CAAC;gBAChB,MAAM,CAAC,WAAW,GAAG,WAAW,CAAC;YACnC,CAAC;QACH,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC;AAMD,MAAM,UAAU,cAAc,CAC5B,QAAiD;IAEjD,OAAO,qBAAqB,CAI1B,CAAC,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAA6C,CAAC,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import {StreamMessage} from '@openassistant/core';\nimport {ExtendedTool} from '@openassistant/utils';\nimport {createId} from '@paralleldrive/cuid2';\nimport {DataTable} from '@sqlrooms/duckdb';\nimport {\n BaseRoomConfig,\n createSlice,\n RoomShellSliceState,\n useBaseRoomShellStore,\n type StateCreator,\n} from '@sqlrooms/room-shell';\nimport {produce, WritableDraft} from 'immer';\nimport {z} from 'zod';\nimport {getDefaultTools, runAnalysis} from './analysis';\nimport {\n AnalysisResultSchema,\n AnalysisSessionSchema,\n ErrorMessageSchema,\n} from './schemas';\n\nexport const AiSliceConfig = z.object({\n ai: z.object({\n sessions: z.array(AnalysisSessionSchema),\n currentSessionId: z.string().optional(),\n }),\n});\nexport type AiSliceConfig = z.infer<typeof AiSliceConfig>;\n\nexport function createDefaultAiConfig(\n props: Partial<AiSliceConfig['ai']>,\n): AiSliceConfig {\n const defaultSessionId = createId();\n return {\n ai: {\n sessions: [\n {\n id: defaultSessionId,\n name: 'Default Session',\n modelProvider: 'openai',\n model: 'gpt-4o-mini',\n analysisResults: [],\n createdAt: new Date(),\n },\n ],\n currentSessionId: defaultSessionId,\n ...props,\n },\n };\n}\n\n// template for the tool: Argument, LLM Result, Additional Data, Context\nexport type AiSliceTool = ExtendedTool<z.ZodTypeAny, unknown, unknown, unknown>;\n\nexport type AiSliceState = {\n ai: {\n analysisPrompt: string;\n isRunningAnalysis: boolean;\n tools: Record<string, AiSliceTool>;\n analysisAbortController?: AbortController;\n setAnalysisPrompt: (prompt: string) => void;\n startAnalysis: () => Promise<void>;\n cancelAnalysis: () => void;\n setAiModel: (modelProvider: string, model: string) => void;\n setCustomModelName: (customModelName: string) => void;\n setBaseUrl: (baseUrl: string) => void;\n createSession: (\n name?: string,\n modelProvider?: string,\n model?: string,\n ) => void;\n switchSession: (sessionId: string) => void;\n renameSession: (sessionId: string, name: string) => void;\n deleteSession: (sessionId: string) => void;\n getCurrentSession: () => AnalysisSessionSchema | undefined;\n deleteAnalysisResult: (sessionId: string, resultId: string) => void;\n findToolComponent: (toolName: string) => React.ComponentType | undefined;\n };\n};\n\n/**\n * Configuration options for creating an AI slice\n */\nexport interface AiSliceOptions {\n /** Initial prompt to display in the analysis input */\n initialAnalysisPrompt?: string;\n /** Custom tools to add to the AI assistant */\n customTools?: Record<string, AiSliceTool>;\n /**\n * Function to get custom instructions for the AI assistant\n * @param tablesSchema - The schema of the tables in the database\n * @returns The instructions string to use\n */\n getInstructions?: (tablesSchema: DataTable[]) => string;\n /**\n * Number of rows to share with LLM (default: 0)\n */\n numberOfRowsToShareWithLLM?: number;\n}\n\n/**\n * API key configuration for the AI slice\n */\nexport type AiSliceApiConfig = {defaultModel?: string} & (\n | {baseUrl: string; getApiKey?: never}\n | {getApiKey: (modelProvider: string) => string; baseUrl?: never}\n);\n\n/**\n * Complete configuration for creating an AI slice\n */\nexport type CreateAiSliceConfig = AiSliceOptions & AiSliceApiConfig;\n\nexport function createAiSlice<PC extends BaseRoomConfig & AiSliceConfig>(\n params: CreateAiSliceConfig,\n): StateCreator<AiSliceState> {\n const {\n getApiKey,\n baseUrl,\n initialAnalysisPrompt = '',\n customTools = {},\n getInstructions,\n numberOfRowsToShareWithLLM,\n defaultModel = 'gpt-4o-mini',\n } = params;\n\n return createSlice<PC, AiSliceState>((set, get, store) => {\n return {\n ai: {\n analysisPrompt: initialAnalysisPrompt,\n isRunningAnalysis: false,\n\n tools: {\n ...getDefaultTools(store, numberOfRowsToShareWithLLM),\n ...customTools,\n },\n\n setAnalysisPrompt: (prompt: string) => {\n set((state) =>\n produce(state, (draft) => {\n draft.ai.analysisPrompt = prompt;\n }),\n );\n },\n\n /**\n * Set the AI model for the current session\n * @param model - The model to set\n */\n setAiModel: (modelProvider: string, model: string) => {\n set((state) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (currentSession) {\n currentSession.modelProvider = modelProvider;\n currentSession.model = model;\n }\n }),\n );\n },\n\n /**\n * Set the custom model name for the current session\n * @param customModelName - The custom model name to set\n */\n setCustomModelName: (customModelName: string) => {\n set((state) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (currentSession) {\n currentSession.customModelName = customModelName;\n }\n }),\n );\n },\n\n /**\n * Set the base URL for the current session\n * @param baseUrl - The server URL to set\n */\n setBaseUrl: (baseUrl: string) => {\n set((state) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (currentSession) {\n currentSession.baseUrl = baseUrl;\n }\n }),\n );\n },\n\n /**\n * Get the current active session\n */\n getCurrentSession: () => {\n const state = get();\n const {currentSessionId, sessions} = state.config.ai;\n return sessions.find((session) => session.id === currentSessionId);\n },\n\n /**\n * Create a new session with the given name and model settings\n */\n createSession: (\n name?: string,\n modelProvider?: string,\n model?: string,\n ) => {\n const currentSession = get().ai.getCurrentSession();\n const newSessionId = createId();\n\n // Generate a default name if none is provided\n let sessionName = name;\n if (!sessionName) {\n // Generate a human-readable date and time for the session name\n const now = new Date();\n const formattedDate = now.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n });\n const formattedTime = now.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: 'numeric',\n hour12: true,\n });\n sessionName = `Session ${formattedDate} at ${formattedTime}`;\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.config.ai.sessions.unshift({\n id: newSessionId,\n name: sessionName,\n modelProvider:\n modelProvider || currentSession?.modelProvider || 'openai',\n model: model || currentSession?.model || 'gpt-4.1',\n analysisResults: [],\n createdAt: new Date(),\n });\n draft.config.ai.currentSessionId = newSessionId;\n }),\n );\n },\n\n /**\n * Switch to a different session\n */\n switchSession: (sessionId: string) => {\n set((state) =>\n produce(state, (draft) => {\n draft.config.ai.currentSessionId = sessionId;\n }),\n );\n },\n\n /**\n * Rename an existing session\n */\n renameSession: (sessionId: string, name: string) => {\n set((state) =>\n produce(state, (draft) => {\n const session = draft.config.ai.sessions.find(\n (s) => s.id === sessionId,\n );\n if (session) {\n session.name = name;\n }\n }),\n );\n },\n\n /**\n * Delete a session\n */\n deleteSession: (sessionId: string) => {\n set((state) =>\n produce(state, (draft) => {\n const sessionIndex = draft.config.ai.sessions.findIndex(\n (s) => s.id === sessionId,\n );\n if (sessionIndex !== -1) {\n // Don't delete the last session\n if (draft.config.ai.sessions.length > 1) {\n draft.config.ai.sessions.splice(sessionIndex, 1);\n // If we deleted the current session, switch to another one\n if (draft.config.ai.currentSessionId === sessionId) {\n // Make sure there's at least one session before accessing its id\n if (draft.config.ai.sessions.length > 0) {\n const firstSession = draft.config.ai.sessions[0];\n if (firstSession) {\n draft.config.ai.currentSessionId = firstSession.id;\n }\n }\n }\n }\n }\n }),\n );\n },\n\n /**\n * Start the analysis\n * TODO: how to pass the history analysisResults?\n */\n startAnalysis: async () => {\n const resultId = createId();\n const abortController = new AbortController();\n const currentSession = get().ai.getCurrentSession();\n\n if (!currentSession) {\n console.error('No current session found');\n return;\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.ai.analysisAbortController = abortController;\n draft.ai.isRunningAnalysis = true;\n\n const session = draft.config.ai.sessions.find(\n (s) => s.id === draft.config.ai.currentSessionId,\n );\n\n if (session) {\n session.analysisResults.push({\n id: resultId,\n prompt: get().ai.analysisPrompt,\n streamMessage: {\n parts: [\n {\n type: 'text',\n text: '',\n },\n ],\n },\n isCompleted: false,\n });\n }\n }),\n );\n\n try {\n await runAnalysis({\n tableSchemas: get().db.tables,\n modelProvider: currentSession.modelProvider || 'openai',\n model: currentSession.model || defaultModel,\n customModelName: currentSession.customModelName,\n apiKey:\n getApiKey?.(currentSession.modelProvider || 'openai') || '',\n baseUrl: currentSession.baseUrl || baseUrl,\n prompt: get().ai.analysisPrompt,\n abortController,\n tools: {\n ...getDefaultTools(store, numberOfRowsToShareWithLLM),\n ...customTools,\n },\n getInstructions,\n onStreamResult: (isCompleted, streamMessage) => {\n set(\n makeResultsAppender({\n resultId,\n streamMessage,\n isCompleted,\n }),\n );\n },\n });\n } catch (err) {\n set(\n makeResultsAppender({\n resultId,\n isCompleted: true,\n errorMessage: {\n error: err instanceof Error ? err.message : String(err),\n },\n }),\n );\n } finally {\n set((state) =>\n produce(state, (draft) => {\n draft.ai.isRunningAnalysis = false;\n draft.ai.analysisPrompt = '';\n }),\n );\n }\n },\n\n cancelAnalysis: () => {\n set((state) =>\n produce(state, (draft) => {\n draft.ai.isRunningAnalysis = false;\n }),\n );\n get().ai.analysisAbortController?.abort('Analysis cancelled');\n },\n\n /**\n * Delete an analysis result from a session\n */\n deleteAnalysisResult: (sessionId: string, resultId: string) => {\n set((state) =>\n produce(state, (draft) => {\n const session = draft.config.ai.sessions.find(\n (s) => s.id === sessionId,\n );\n if (session) {\n session.analysisResults = session.analysisResults.filter(\n (r) => r.id !== resultId,\n );\n }\n }),\n );\n },\n\n findToolComponent: (toolName: string) => {\n return Object.entries(get().ai.tools).find(\n ([name]) => name === toolName,\n )?.[1]?.component as React.ComponentType;\n },\n },\n };\n });\n}\n\n/**\n * Helper function to get the current session from state\n */\nfunction getCurrentSessionFromState<PC extends BaseRoomConfig & AiSliceConfig>(\n state: RoomShellSliceState<PC> | WritableDraft<RoomShellSliceState<PC>>,\n): AnalysisSessionSchema | undefined {\n const {currentSessionId, sessions} = state.config.ai;\n return sessions.find((session) => session.id === currentSessionId);\n}\n\nfunction findResultById(\n analysisResults: AnalysisResultSchema[],\n id: string,\n): AnalysisResultSchema | undefined {\n return analysisResults.find((result) => result.id === id);\n}\n\n/**\n * Appends the tool results, tool calls, and analysis to the state\n *\n * @param resultId - The id of the result to append to\n * @param message - The message to append to the state. The structure of the message is defined as:\n * - reasoning: string The reasoning of the assistant\n * - toolCallMessages: ToolCallMessage[] The tool call messages\n * - text: string The final text message\n * @param isCompleted - Whether the analysis is completed\n * @returns The new state\n */\nfunction makeResultsAppender<PC extends BaseRoomConfig & AiSliceConfig>({\n resultId,\n streamMessage,\n errorMessage,\n isCompleted,\n}: {\n resultId: string;\n streamMessage?: StreamMessage;\n errorMessage?: ErrorMessageSchema;\n isCompleted?: boolean;\n}) {\n return (state: RoomShellSliceState<PC>) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (!currentSession) {\n console.error('No current session found');\n return;\n }\n\n const result = findResultById(currentSession.analysisResults, resultId);\n if (result) {\n if (streamMessage && streamMessage.parts) {\n // copy all properties from streamMessage\n const newStreamMessage = {\n parts: streamMessage.parts.map((part) => {\n if (part.type === 'text') {\n return {\n type: 'text' as const,\n text: part.text,\n additionalData: part.additionalData,\n isCompleted: part.isCompleted,\n };\n } else if (part.type === 'tool-invocation') {\n return {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n state: part.toolInvocation.state,\n result:\n part.toolInvocation.state === 'result'\n ? part.toolInvocation.result\n : undefined,\n },\n additionalData: part.additionalData,\n isCompleted: part.isCompleted,\n };\n } else {\n // TODO: handle other part types later\n return part;\n }\n }),\n };\n\n result.streamMessage = newStreamMessage as StreamMessage;\n }\n if (errorMessage) {\n result.errorMessage = errorMessage;\n }\n if (isCompleted) {\n result.isCompleted = isCompleted;\n }\n } else {\n console.error('Result not found', resultId);\n }\n });\n}\n\ntype RoomConfigWithAi = BaseRoomConfig & AiSliceConfig;\ntype RoomShellSliceStateWithAi = RoomShellSliceState<RoomConfigWithAi> &\n AiSliceState;\n\nexport function useStoreWithAi<T>(\n selector: (state: RoomShellSliceStateWithAi) => T,\n): T {\n return useBaseRoomShellStore<\n BaseRoomConfig & AiSliceConfig,\n RoomShellSliceState<RoomConfigWithAi>,\n T\n >((state) => selector(state as unknown as RoomShellSliceStateWithAi));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AiSlice.js","sourceRoot":"","sources":["../src/AiSlice.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AAE9C,OAAO,EAEL,WAAW,EAEX,qBAAqB,GAEtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAC,OAAO,EAAgB,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AACtB,OAAO,EAAsB,eAAe,EAAE,WAAW,EAAC,MAAM,YAAY,CAAC;AAC7E,OAAO,EAEL,qBAAqB,GAEtB,MAAM,WAAW,CAAC;AAEnB,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC;QACX,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,qBAAqB,CAAC;QACxC,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;KACxC,CAAC;CACH,CAAC,CAAC;AAGH,MAAM,UAAU,qBAAqB,CACnC,KAAmC;IAEnC,MAAM,gBAAgB,GAAG,QAAQ,EAAE,CAAC;IACpC,OAAO;QACL,EAAE,EAAE;YACF,QAAQ,EAAE;gBACR;oBACE,EAAE,EAAE,gBAAgB;oBACpB,IAAI,EAAE,iBAAiB;oBACvB,aAAa,EAAE,QAAQ;oBACvB,KAAK,EAAE,aAAa;oBACpB,eAAe,EAAE,EAAE;oBACnB,SAAS,EAAE,IAAI,IAAI,EAAE;iBACtB;aACF;YACD,gBAAgB,EA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AC,CAAC;AACP,CAAC;AAMD,MAAM,UAAU,cAAc,CAC5B,QAAiD;IAEjD,OAAO,qBAAqB,CAI1B,CAAC,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAA6C,CAAC,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import {StreamMessage} from '@openassistant/core';\nimport {ExtendedTool} from '@openassistant/utils';\nimport {createId} from '@paralleldrive/cuid2';\nimport {DataTable} from '@sqlrooms/duckdb';\nimport {\n BaseRoomConfig,\n createSlice,\n RoomShellSliceState,\n useBaseRoomShellStore,\n type StateCreator,\n} from '@sqlrooms/room-shell';\nimport {produce, WritableDraft} from 'immer';\nimport {z} from 'zod';\nimport {DefaultToolsOptions, getDefaultTools, runAnalysis} from './analysis';\nimport {\n AnalysisResultSchema,\n AnalysisSessionSchema,\n ErrorMessageSchema,\n} from './schemas';\n\nexport const AiSliceConfig = z.object({\n ai: z.object({\n sessions: z.array(AnalysisSessionSchema),\n currentSessionId: z.string().optional(),\n }),\n});\nexport type AiSliceConfig = z.infer<typeof AiSliceConfig>;\n\nexport function createDefaultAiConfig(\n props: Partial<AiSliceConfig['ai']>,\n): AiSliceConfig {\n const defaultSessionId = createId();\n return {\n ai: {\n sessions: [\n {\n id: defaultSessionId,\n name: 'Default Session',\n modelProvider: 'openai',\n model: 'gpt-4o-mini',\n analysisResults: [],\n createdAt: new Date(),\n },\n ],\n currentSessionId: defaultSessionId,\n ...props,\n },\n };\n}\n\n// template for the tool: Argument, LLM Result, Additional Data, Context\nexport type AiSliceTool = ExtendedTool<z.ZodTypeAny, unknown, unknown, unknown>;\n\nexport type AiSliceState = {\n ai: {\n analysisPrompt: string;\n isRunningAnalysis: boolean;\n tools: Record<string, AiSliceTool>;\n analysisAbortController?: AbortController;\n setAnalysisPrompt: (prompt: string) => void;\n startAnalysis: () => Promise<void>;\n cancelAnalysis: () => void;\n setAiModel: (modelProvider: string, model: string) => void;\n setCustomModelName: (customModelName: string) => void;\n setBaseUrl: (baseUrl: string) => void;\n createSession: (\n name?: string,\n modelProvider?: string,\n model?: string,\n ) => void;\n switchSession: (sessionId: string) => void;\n renameSession: (sessionId: string, name: string) => void;\n deleteSession: (sessionId: string) => void;\n getCurrentSession: () => AnalysisSessionSchema | undefined;\n deleteAnalysisResult: (sessionId: string, resultId: string) => void;\n findToolComponent: (toolName: string) => React.ComponentType | undefined;\n };\n};\n\n/**\n * Configuration options for creating an AI slice\n */\nexport interface AiSliceOptions {\n /** Initial prompt to display in the analysis input */\n initialAnalysisPrompt?: string;\n /** Custom tools to add to the AI assistant */\n customTools?: Record<string, AiSliceTool>;\n /**\n * Function to get custom instructions for the AI assistant\n * @param tablesSchema - The schema of the tables in the database\n * @returns The instructions string to use\n */\n getInstructions?: (tablesSchema: DataTable[]) => string;\n toolsOptions?: DefaultToolsOptions;\n}\n\n/**\n * API key configuration for the AI slice\n */\nexport type AiSliceApiConfig = {defaultModel?: string} & (\n | {baseUrl: string; getApiKey?: never}\n | {getApiKey: (modelProvider: string) => string; baseUrl?: never}\n);\n\n/**\n * Complete configuration for creating an AI slice\n */\nexport type CreateAiSliceConfig = AiSliceOptions & AiSliceApiConfig;\n\nexport function createAiSlice<PC extends BaseRoomConfig & AiSliceConfig>(\n params: CreateAiSliceConfig,\n): StateCreator<AiSliceState> {\n const {\n getApiKey,\n baseUrl,\n initialAnalysisPrompt = '',\n customTools = {},\n getInstructions,\n toolsOptions,\n defaultModel = 'gpt-4o-mini',\n } = params;\n\n return createSlice<PC, AiSliceState>((set, get, store) => {\n return {\n ai: {\n analysisPrompt: initialAnalysisPrompt,\n isRunningAnalysis: false,\n\n tools: {\n ...getDefaultTools(store, toolsOptions),\n ...customTools,\n },\n\n setAnalysisPrompt: (prompt: string) => {\n set((state) =>\n produce(state, (draft) => {\n draft.ai.analysisPrompt = prompt;\n }),\n );\n },\n\n /**\n * Set the AI model for the current session\n * @param model - The model to set\n */\n setAiModel: (modelProvider: string, model: string) => {\n set((state) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (currentSession) {\n currentSession.modelProvider = modelProvider;\n currentSession.model = model;\n }\n }),\n );\n },\n\n /**\n * Set the custom model name for the current session\n * @param customModelName - The custom model name to set\n */\n setCustomModelName: (customModelName: string) => {\n set((state) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (currentSession) {\n currentSession.customModelName = customModelName;\n }\n }),\n );\n },\n\n /**\n * Set the base URL for the current session\n * @param baseUrl - The server URL to set\n */\n setBaseUrl: (baseUrl: string) => {\n set((state) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (currentSession) {\n currentSession.baseUrl = baseUrl;\n }\n }),\n );\n },\n\n /**\n * Get the current active session\n */\n getCurrentSession: () => {\n const state = get();\n const {currentSessionId, sessions} = state.config.ai;\n return sessions.find((session) => session.id === currentSessionId);\n },\n\n /**\n * Create a new session with the given name and model settings\n */\n createSession: (\n name?: string,\n modelProvider?: string,\n model?: string,\n ) => {\n const currentSession = get().ai.getCurrentSession();\n const newSessionId = createId();\n\n // Generate a default name if none is provided\n let sessionName = name;\n if (!sessionName) {\n // Generate a human-readable date and time for the session name\n const now = new Date();\n const formattedDate = now.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n });\n const formattedTime = now.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: 'numeric',\n hour12: true,\n });\n sessionName = `Session ${formattedDate} at ${formattedTime}`;\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.config.ai.sessions.unshift({\n id: newSessionId,\n name: sessionName,\n modelProvider:\n modelProvider || currentSession?.modelProvider || 'openai',\n model: model || currentSession?.model || 'gpt-4.1',\n analysisResults: [],\n createdAt: new Date(),\n });\n draft.config.ai.currentSessionId = newSessionId;\n }),\n );\n },\n\n /**\n * Switch to a different session\n */\n switchSession: (sessionId: string) => {\n set((state) =>\n produce(state, (draft) => {\n draft.config.ai.currentSessionId = sessionId;\n }),\n );\n },\n\n /**\n * Rename an existing session\n */\n renameSession: (sessionId: string, name: string) => {\n set((state) =>\n produce(state, (draft) => {\n const session = draft.config.ai.sessions.find(\n (s) => s.id === sessionId,\n );\n if (session) {\n session.name = name;\n }\n }),\n );\n },\n\n /**\n * Delete a session\n */\n deleteSession: (sessionId: string) => {\n set((state) =>\n produce(state, (draft) => {\n const sessionIndex = draft.config.ai.sessions.findIndex(\n (s) => s.id === sessionId,\n );\n if (sessionIndex !== -1) {\n // Don't delete the last session\n if (draft.config.ai.sessions.length > 1) {\n draft.config.ai.sessions.splice(sessionIndex, 1);\n // If we deleted the current session, switch to another one\n if (draft.config.ai.currentSessionId === sessionId) {\n // Make sure there's at least one session before accessing its id\n if (draft.config.ai.sessions.length > 0) {\n const firstSession = draft.config.ai.sessions[0];\n if (firstSession) {\n draft.config.ai.currentSessionId = firstSession.id;\n }\n }\n }\n }\n }\n }),\n );\n },\n\n /**\n * Start the analysis\n * TODO: how to pass the history analysisResults?\n */\n startAnalysis: async () => {\n const resultId = createId();\n const abortController = new AbortController();\n const currentSession = get().ai.getCurrentSession();\n\n if (!currentSession) {\n console.error('No current session found');\n return;\n }\n\n set((state) =>\n produce(state, (draft) => {\n draft.ai.analysisAbortController = abortController;\n draft.ai.isRunningAnalysis = true;\n\n const session = draft.config.ai.sessions.find(\n (s) => s.id === draft.config.ai.currentSessionId,\n );\n\n if (session) {\n session.analysisResults.push({\n id: resultId,\n prompt: get().ai.analysisPrompt,\n streamMessage: {\n parts: [\n {\n type: 'text',\n text: '',\n },\n ],\n },\n isCompleted: false,\n });\n }\n }),\n );\n\n try {\n await runAnalysis({\n tableSchemas: get().db.tables,\n modelProvider: currentSession.modelProvider || 'openai',\n model: currentSession.model || defaultModel,\n customModelName: currentSession.customModelName,\n apiKey:\n getApiKey?.(currentSession.modelProvider || 'openai') || '',\n baseUrl: currentSession.baseUrl || baseUrl,\n prompt: get().ai.analysisPrompt,\n abortController,\n tools: get().ai.tools,\n getInstructions,\n onStreamResult: (isCompleted, streamMessage) => {\n set(\n makeResultsAppender({\n resultId,\n streamMessage,\n isCompleted,\n }),\n );\n },\n });\n } catch (err) {\n set(\n makeResultsAppender({\n resultId,\n isCompleted: true,\n errorMessage: {\n error: err instanceof Error ? err.message : String(err),\n },\n }),\n );\n } finally {\n set((state) =>\n produce(state, (draft) => {\n draft.ai.isRunningAnalysis = false;\n draft.ai.analysisPrompt = '';\n }),\n );\n }\n },\n\n cancelAnalysis: () => {\n set((state) =>\n produce(state, (draft) => {\n draft.ai.isRunningAnalysis = false;\n }),\n );\n get().ai.analysisAbortController?.abort('Analysis cancelled');\n },\n\n /**\n * Delete an analysis result from a session\n */\n deleteAnalysisResult: (sessionId: string, resultId: string) => {\n set((state) =>\n produce(state, (draft) => {\n const session = draft.config.ai.sessions.find(\n (s) => s.id === sessionId,\n );\n if (session) {\n session.analysisResults = session.analysisResults.filter(\n (r) => r.id !== resultId,\n );\n }\n }),\n );\n },\n\n findToolComponent: (toolName: string) => {\n return Object.entries(get().ai.tools).find(\n ([name]) => name === toolName,\n )?.[1]?.component as React.ComponentType;\n },\n },\n };\n });\n}\n\n/**\n * Helper function to get the current session from state\n */\nfunction getCurrentSessionFromState<PC extends BaseRoomConfig & AiSliceConfig>(\n state: RoomShellSliceState<PC> | WritableDraft<RoomShellSliceState<PC>>,\n): AnalysisSessionSchema | undefined {\n const {currentSessionId, sessions} = state.config.ai;\n return sessions.find((session) => session.id === currentSessionId);\n}\n\nfunction findResultById(\n analysisResults: AnalysisResultSchema[],\n id: string,\n): AnalysisResultSchema | undefined {\n return analysisResults.find((result) => result.id === id);\n}\n\n/**\n * Appends the tool results, tool calls, and analysis to the state\n *\n * @param resultId - The id of the result to append to\n * @param message - The message to append to the state. The structure of the message is defined as:\n * - reasoning: string The reasoning of the assistant\n * - toolCallMessages: ToolCallMessage[] The tool call messages\n * - text: string The final text message\n * @param isCompleted - Whether the analysis is completed\n * @returns The new state\n */\nfunction makeResultsAppender<PC extends BaseRoomConfig & AiSliceConfig>({\n resultId,\n streamMessage,\n errorMessage,\n isCompleted,\n}: {\n resultId: string;\n streamMessage?: StreamMessage;\n errorMessage?: ErrorMessageSchema;\n isCompleted?: boolean;\n}) {\n return (state: RoomShellSliceState<PC>) =>\n produce(state, (draft) => {\n const currentSession = getCurrentSessionFromState(draft);\n if (!currentSession) {\n console.error('No current session found');\n return;\n }\n\n const result = findResultById(currentSession.analysisResults, resultId);\n if (result) {\n if (streamMessage && streamMessage.parts) {\n // copy all properties from streamMessage\n const newStreamMessage = {\n parts: streamMessage.parts.map((part) => {\n if (part.type === 'text') {\n return {\n type: 'text' as const,\n text: part.text,\n additionalData: part.additionalData,\n isCompleted: part.isCompleted,\n };\n } else if (part.type === 'tool-invocation') {\n return {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n state: part.toolInvocation.state,\n result:\n part.toolInvocation.state === 'result'\n ? part.toolInvocation.result\n : undefined,\n },\n additionalData: part.additionalData,\n isCompleted: part.isCompleted,\n };\n } else {\n // TODO: handle other part types later\n return part;\n }\n }),\n };\n\n result.streamMessage = newStreamMessage as StreamMessage;\n }\n if (errorMessage) {\n result.errorMessage = errorMessage;\n }\n if (isCompleted) {\n result.isCompleted = isCompleted;\n }\n } else {\n console.error('Result not found', resultId);\n }\n });\n}\n\ntype RoomConfigWithAi = BaseRoomConfig & AiSliceConfig;\ntype RoomShellSliceStateWithAi = RoomShellSliceState<RoomConfigWithAi> &\n AiSliceState;\n\nexport function useStoreWithAi<T>(\n selector: (state: RoomShellSliceStateWithAi) => T,\n): T {\n return useBaseRoomShellStore<\n BaseRoomConfig & AiSliceConfig,\n RoomShellSliceState<RoomConfigWithAi>,\n T\n >((state) => selector(state as unknown as RoomShellSliceStateWithAi));\n}\n"]}
|
package/dist/analysis.d.ts
CHANGED
|
@@ -57,11 +57,25 @@ export declare function runAnalysis({ name, tableSchemas, modelProvider, model,
|
|
|
57
57
|
streamMessage: StreamMessage;
|
|
58
58
|
messages: import("ai").CoreMessage[];
|
|
59
59
|
}>;
|
|
60
|
+
export type DefaultToolsOptions = {
|
|
61
|
+
/**
|
|
62
|
+
* Whether to enable read only mode (default: true)
|
|
63
|
+
*/
|
|
64
|
+
readOnly?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Number of rows to share with LLM (default: 0)
|
|
67
|
+
*/
|
|
68
|
+
numberOfRowsToShareWithLLM?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Whether to automatically generate a summary of the query result (default: true)
|
|
71
|
+
*/
|
|
72
|
+
autoSummary?: boolean;
|
|
73
|
+
};
|
|
60
74
|
/**
|
|
61
75
|
* Default tools available to the AI assistant for data analysis
|
|
62
76
|
* Includes:
|
|
63
77
|
* - query: Executes SQL queries against DuckDB
|
|
64
78
|
*/
|
|
65
|
-
export declare function getDefaultTools(store: StoreApi<AiSliceState & DuckDbSliceState>,
|
|
79
|
+
export declare function getDefaultTools(store: StoreApi<AiSliceState & DuckDbSliceState>, options?: DefaultToolsOptions): Record<string, AiSliceTool>;
|
|
66
80
|
export {};
|
|
67
81
|
//# sourceMappingURL=analysis.d.ts.map
|
package/dist/analysis.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analysis.d.ts","sourceRoot":"","sources":["../src/analysis.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,aAAa,EACd,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAEL,SAAS,EAET,gBAAgB,
|
|
1
|
+
{"version":3,"file":"analysis.d.ts","sourceRoot":"","sources":["../src/analysis.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,aAAa,EACd,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAEL,SAAS,EAET,gBAAgB,EAEjB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAC,YAAY,EAAE,WAAW,EA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E,kBAAkB;;;GAgDpB;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC;;OAEG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;OAEG;IAEH,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC;;OAEG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,QAAQ,CAAC,YAAY,GAAG,gBAAgB,CAAC,EAChD,OAAO,CAAC,EAAE,mBAAmB,GAC5B,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAiG7B"}
|
package/dist/analysis.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createAssistant, rebuildMessages, } from '@openassistant/core';
|
|
2
2
|
import { extendedTool } from '@openassistant/utils';
|
|
3
|
-
import { arrowTableToJson, } from '@sqlrooms/duckdb';
|
|
3
|
+
import { arrowTableToJson, splitSqlStatements, } from '@sqlrooms/duckdb';
|
|
4
4
|
import { QueryToolResult } from './components/tools/QueryToolResult';
|
|
5
5
|
import { QueryToolParameters } from './schemas';
|
|
6
6
|
import { convertToCoreMessages } from 'ai';
|
|
@@ -77,15 +77,13 @@ async function getQuerySummary(connector, sqlQuery) {
|
|
|
77
77
|
return null;
|
|
78
78
|
}
|
|
79
79
|
try {
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
await connector.query(`DROP VIEW IF EXISTS ${viewName}`);
|
|
85
|
-
return summaryData;
|
|
80
|
+
const summaryResult = await connector.query(`SUMMARIZE (
|
|
81
|
+
${sqlQuery}
|
|
82
|
+
)`);
|
|
83
|
+
return arrowTableToJson(summaryResult);
|
|
86
84
|
}
|
|
87
85
|
catch (error) {
|
|
88
|
-
console.warn('Failed to get summary:', error);
|
|
86
|
+
console.warn('Failed to get summary for query. Error:', error);
|
|
89
87
|
return null;
|
|
90
88
|
}
|
|
91
89
|
}
|
|
@@ -138,7 +136,8 @@ export async function runAnalysis({ name = 'sqlrooms-ai', tableSchemas, modelPro
|
|
|
138
136
|
* Includes:
|
|
139
137
|
* - query: Executes SQL queries against DuckDB
|
|
140
138
|
*/
|
|
141
|
-
export function getDefaultTools(store,
|
|
139
|
+
export function getDefaultTools(store, options) {
|
|
140
|
+
const { readOnly = true, numberOfRowsToShareWithLLM = 0, autoSummary = true, } = options || {};
|
|
142
141
|
return {
|
|
143
142
|
query: extendedTool({
|
|
144
143
|
description: `A tool for running SQL queries on the tables in the database.
|
|
@@ -150,10 +149,41 @@ If a query fails, please don't try to run it again with the same syntax.`,
|
|
|
150
149
|
const connector = await store.getState().db.getConnector();
|
|
151
150
|
// TODO use options.abortSignal: maybe call db.cancelPendingQuery
|
|
152
151
|
const result = await connector.query(sqlQuery);
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
152
|
+
const parsedQuery = await store
|
|
153
|
+
.getState()
|
|
154
|
+
.db.sqlSelectToJson(sqlQuery);
|
|
155
|
+
if (parsedQuery.error &&
|
|
156
|
+
// Only SELECT statements can be serialized to json, so we ignore not implemented errors
|
|
157
|
+
parsedQuery.error_type !== 'not implemented') {
|
|
158
|
+
throw new Error(parsedQuery.error_message);
|
|
159
|
+
}
|
|
160
|
+
if (readOnly) {
|
|
161
|
+
if (parsedQuery.error) {
|
|
162
|
+
throw new Error(`Query is not a valid SELECT statement: ${parsedQuery.error_message}`);
|
|
163
|
+
}
|
|
164
|
+
if (parsedQuery.statements.length !== 1 || // only one statement allowed
|
|
165
|
+
parsedQuery.statements[0]?.node.type !== 'SELECT_NODE' // only SELECT statements allowed
|
|
166
|
+
) {
|
|
167
|
+
throw new Error('Query is not a valid SELECT statement');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const summaryData = await (async () => {
|
|
171
|
+
if (!autoSummary)
|
|
172
|
+
return null;
|
|
173
|
+
if (parsedQuery.error)
|
|
174
|
+
return null;
|
|
175
|
+
const lastNode = parsedQuery.statements[parsedQuery.statements.length - 1]?.node;
|
|
176
|
+
// Only get summary if the last statement isn't already a SUMMARIZE query
|
|
177
|
+
if (lastNode?.type === 'SELECT_NODE' &&
|
|
178
|
+
lastNode?.from_table?.show_type === 'SUMMARY') {
|
|
179
|
+
return arrowTableToJson(result);
|
|
180
|
+
}
|
|
181
|
+
const statements = splitSqlStatements(sqlQuery);
|
|
182
|
+
const lastStatement = statements[statements.length - 1];
|
|
183
|
+
if (!lastStatement)
|
|
184
|
+
return null;
|
|
185
|
+
return await getQuerySummary(connector, lastStatement);
|
|
186
|
+
})();
|
|
157
187
|
// Conditionally get rows of the result as a json object based on numberOfRowsToShareWithLLM
|
|
158
188
|
const firstRows = numberOfRowsToShareWithLLM > 0
|
|
159
189
|
? arrowTableToJson(result.slice(0, numberOfRowsToShareWithLLM))
|
package/dist/analysis.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analysis.js","sourceRoot":"","sources":["../src/analysis.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,GAEhB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAC,YAAY,EAAC,MAAM,sBAAsB,CAAC;AAClD,OAAO,EACL,gBAAgB,GAIjB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAC,eAAe,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAuB,mBAAmB,EAAC,MAAM,WAAW,CAAC;AACpE,OAAO,EAAC,qBAAqB,EAAC,MAAM,IAAI,CAAC;AAEzC;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgD5B,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,sBAAsB,CAAC,YAAyB;IAC9D,OAAO,GAAG,oBAAoB,KAAK,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,EAAE,CAAC;AACpE,CAAC;AAED;;;;;GAKG;A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AAS,EAAE,eAAe;SAC3B,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n createAssistant,\n rebuildMessages,\n StreamMessage,\n} from '@openassistant/core';\nimport {extendedTool} from '@openassistant/utils';\nimport {\n arrowTableToJson,\n DataTable,\n DuckDbConnector,\n DuckDbSliceState,\n} from '@sqlrooms/duckdb';\nimport type {StoreApi} from '@sqlrooms/room-shell';\nimport {AiSliceState, AiSliceTool} from './AiSlice';\nimport {QueryToolResult} from './components/tools/QueryToolResult';\nimport {AnalysisResultSchema, QueryToolParameters} from './schemas';\nimport {convertToCoreMessages} from 'ai';\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\nPlease use the following schema for the tables:\n`;\n\n/**\n * Returns the default system instructions for the AI assistant\n */\nexport function getDefaultInstructions(tablesSchema: DataTable[]): string {\n return `${DEFAULT_INSTRUCTIONS}\\n${JSON.stringify(tablesSchema)}`;\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 */\nasync function getQuerySummary(connector: DuckDbConnector, sqlQuery: string) {\n if (!sqlQuery.toLowerCase().trim().startsWith('select')) {\n return null;\n }\n\n try {\n const viewName = `temp_result_${Date.now()}`; // unique view name to avoid conflicts\n await connector.query(`CREATE TEMPORARY VIEW ${viewName} AS ${sqlQuery}`);\n const summaryResult = await connector.query(`SUMMARIZE ${viewName}`);\n const summaryData = arrowTableToJson(summaryResult);\n await connector.query(`DROP VIEW IF EXISTS ${viewName}`);\n return summaryData;\n } catch (error) {\n console.warn('Failed to get summary:', error);\n return null;\n }\n}\n\n/**\n * Configuration options for running an AI analysis session\n */\ntype AnalysisParameters = {\n tableSchemas: DataTable[];\n\n /** Assistant instance identifier (default: 'sqlrooms-ai') */\n name?: string;\n\n /** AI model provider (e.g., 'openai', 'anthropic') */\n modelProvider: string;\n\n /** Model identifier (e.g., 'gpt-4', 'claude-3') */\n model: string;\n\n /** Custom model name for Ollama (used when model is 'custom') */\n customModelName?: string;\n\n /** Authentication key for the model provider's API */\n apiKey: string;\n\n /** Analysis prompt or question to be processed */\n prompt: string;\n\n /** Optional controller for canceling the analysis operation */\n abortController?: AbortController;\n\n /** Maximum number of analysis steps allowed (default: 100) */\n maxSteps?: number;\n\n /** The history of analysis results (e.g. saved in localStorage) */\n historyAnalysis?: AnalysisResultSchema[];\n\n /** Tools to use in the analysis */\n tools?: Record<string, AiSliceTool>;\n\n /** Base URL for Ollama provider (required when modelProvider is 'ollama') */\n baseUrl?: string;\n\n /**\n * Function to get custom instructions for the AI assistant\n * @param tablesSchema - The schema of the tables in the database\n * @returns The instructions string to use\n */\n getInstructions?: (tablesSchema: DataTable[]) => string;\n\n /**\n * Callback for handling streaming results\n * @param isCompleted - Indicates if this is the final message in the stream\n * @param streamMessage - Current message content being streamed\n */\n onStreamResult: (isCompleted: boolean, streamMessage?: StreamMessage) => void;\n};\n\n/**\n * Executes an AI analysis session on the room data\n *\n * @param config - Analysis configuration options. See {@link AnalysisParameters} for more details.\n * @returns Object containing tool calls executed and the final analysis result\n */\nexport async function runAnalysis({\n name = 'sqlrooms-ai',\n tableSchemas,\n modelProvider,\n model,\n customModelName,\n apiKey,\n prompt,\n abortController,\n historyAnalysis,\n onStreamResult,\n maxSteps = 5,\n tools = {},\n getInstructions,\n baseUrl,\n}: AnalysisParameters) {\n // Use custom model name if model is 'custom' and customModelName is provided\n const actualModel =\n model === 'custom' && customModelName ? customModelName : model;\n\n // get the singleton assistant instance\n const assistant = await createAssistant({\n name,\n modelProvider,\n model: actualModel,\n apiKey,\n version: 'v1',\n instructions: getInstructions\n ? getInstructions(tableSchemas)\n : getDefaultInstructions(tableSchemas),\n tools: tools,\n temperature: 0,\n toolChoice: 'auto', // this will enable streaming\n maxSteps,\n ...(abortController ? {abortController} : {}),\n baseUrl, // ollama base url or LLM proxy server url\n });\n\n // restore ai messages from historyAnalysis?\n if (historyAnalysis) {\n const historyMessages = historyAnalysis.map((analysis) => ({\n prompt: analysis.prompt,\n response: analysis.streamMessage as StreamMessage,\n }));\n const initialMessages = rebuildMessages(historyMessages);\n assistant.setMessages(convertToCoreMessages(initialMessages));\n }\n\n // process the prompt\n const newMessages = await assistant.processTextMessage({\n textMessage: prompt,\n streamMessageCallback: ({\n isCompleted,\n message,\n }: {\n isCompleted?: boolean;\n message?: StreamMessage;\n }) => {\n onStreamResult(isCompleted ?? false, message);\n },\n });\n\n return newMessages;\n}\n\n/**\n * Default tools available to the AI assistant for data analysis\n * Includes:\n * - query: Executes SQL queries against DuckDB\n */\nexport function getDefaultTools(\n store: StoreApi<AiSliceState & DuckDbSliceState>,\n numberOfRowsToShareWithLLM: number = 0,\n): Record<string, AiSliceTool> {\n return {\n query: extendedTool({\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 ({type, sqlQuery}) => {\n try {\n const connector = await store.getState().db.getConnector();\n // TODO use options.abortSignal: maybe call db.cancelPendingQuery\n const result = await connector.query(sqlQuery);\n // Only get summary if the query isn't already a SUMMARIZE query\n const summaryData = sqlQuery.toLowerCase().includes('summarize')\n ? arrowTableToJson(result)\n : await getQuerySummary(connector, sqlQuery);\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"]}
|
|
1
|
+
{"version":3,"file":"analysis.js","sourceRoot":"","sources":["../src/analysis.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,GAEhB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAC,YAAY,EAAC,MAAM,sBAAsB,CAAC;A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AE;4BACd,KAAK,EAAE,cAAc;4BACrB,QAAQ;yBACT;qBACF,CAAC;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO;wBACL,SAAS,EAAE;4BACT,OAAO,EAAE,KAAK;4BACd,OAAO,EAAE,yBAAyB;4BAClC,YAAY,EACV,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe;yBAC3D;qBACF,CAAC;gBACJ,CAAC;YACH,CAAC;YACD,SAAS,EAAE,eAAe;SAC3B,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n createAssistant,\n rebuildMessages,\n StreamMessage,\n} from '@openassistant/core';\nimport {extendedTool} from '@openassistant/utils';\nimport {\n arrowTableToJson,\n DataTable,\n DuckDbConnector,\n DuckDbSliceState,\n splitSqlStatements,\n} from '@sqlrooms/duckdb';\nimport type {StoreApi} from '@sqlrooms/room-shell';\nimport {AiSliceState, AiSliceTool} from './AiSlice';\nimport {QueryToolResult} from './components/tools/QueryToolResult';\nimport {AnalysisResultSchema, QueryToolParameters} from './schemas';\nimport {convertToCoreMessages} from 'ai';\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\nPlease use the following schema for the tables:\n`;\n\n/**\n * Returns the default system instructions for the AI assistant\n */\nexport function getDefaultInstructions(tablesSchema: DataTable[]): string {\n return `${DEFAULT_INSTRUCTIONS}\\n${JSON.stringify(tablesSchema)}`;\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 */\nasync function getQuerySummary(connector: DuckDbConnector, sqlQuery: string) {\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\n/**\n * Configuration options for running an AI analysis session\n */\ntype AnalysisParameters = {\n tableSchemas: DataTable[];\n\n /** Assistant instance identifier (default: 'sqlrooms-ai') */\n name?: string;\n\n /** AI model provider (e.g., 'openai', 'anthropic') */\n modelProvider: string;\n\n /** Model identifier (e.g., 'gpt-4', 'claude-3') */\n model: string;\n\n /** Custom model name for Ollama (used when model is 'custom') */\n customModelName?: string;\n\n /** Authentication key for the model provider's API */\n apiKey: string;\n\n /** Analysis prompt or question to be processed */\n prompt: string;\n\n /** Optional controller for canceling the analysis operation */\n abortController?: AbortController;\n\n /** Maximum number of analysis steps allowed (default: 100) */\n maxSteps?: number;\n\n /** The history of analysis results (e.g. saved in localStorage) */\n historyAnalysis?: AnalysisResultSchema[];\n\n /** Tools to use in the analysis */\n tools?: Record<string, AiSliceTool>;\n\n /** Base URL for Ollama provider (required when modelProvider is 'ollama') */\n baseUrl?: string;\n\n /**\n * Function to get custom instructions for the AI assistant\n * @param tablesSchema - The schema of the tables in the database\n * @returns The instructions string to use\n */\n getInstructions?: (tablesSchema: DataTable[]) => string;\n\n /**\n * Callback for handling streaming results\n * @param isCompleted - Indicates if this is the final message in the stream\n * @param streamMessage - Current message content being streamed\n */\n onStreamResult: (isCompleted: boolean, streamMessage?: StreamMessage) => void;\n};\n\n/**\n * Executes an AI analysis session on the room data\n *\n * @param config - Analysis configuration options. See {@link AnalysisParameters} for more details.\n * @returns Object containing tool calls executed and the final analysis result\n */\nexport async function runAnalysis({\n name = 'sqlrooms-ai',\n tableSchemas,\n modelProvider,\n model,\n customModelName,\n apiKey,\n prompt,\n abortController,\n historyAnalysis,\n onStreamResult,\n maxSteps = 5,\n tools = {},\n getInstructions,\n baseUrl,\n}: AnalysisParameters) {\n // Use custom model name if model is 'custom' and customModelName is provided\n const actualModel =\n model === 'custom' && customModelName ? customModelName : model;\n\n // get the singleton assistant instance\n const assistant = await createAssistant({\n name,\n modelProvider,\n model: actualModel,\n apiKey,\n version: 'v1',\n instructions: getInstructions\n ? getInstructions(tableSchemas)\n : getDefaultInstructions(tableSchemas),\n tools: tools,\n temperature: 0,\n toolChoice: 'auto', // this will enable streaming\n maxSteps,\n ...(abortController ? {abortController} : {}),\n baseUrl, // ollama base url or LLM proxy server url\n });\n\n // restore ai messages from historyAnalysis?\n if (historyAnalysis) {\n const historyMessages = historyAnalysis.map((analysis) => ({\n prompt: analysis.prompt,\n response: analysis.streamMessage as StreamMessage,\n }));\n const initialMessages = rebuildMessages(historyMessages);\n assistant.setMessages(convertToCoreMessages(initialMessages));\n }\n\n // process the prompt\n const newMessages = await assistant.processTextMessage({\n textMessage: prompt,\n streamMessageCallback: ({\n isCompleted,\n message,\n }: {\n isCompleted?: boolean;\n message?: StreamMessage;\n }) => {\n onStreamResult(isCompleted ?? false, message);\n },\n });\n\n return newMessages;\n}\n\nexport type DefaultToolsOptions = {\n /**\n * Whether to enable read only mode (default: true)\n */\n readOnly?: boolean;\n /**\n * Number of rows to share with LLM (default: 0)\n */\n\n numberOfRowsToShareWithLLM?: number;\n /**\n * Whether to automatically generate a summary of the query result (default: true)\n */\n autoSummary?: boolean;\n};\n\n/**\n * Default tools available to the AI assistant for data analysis\n * Includes:\n * - query: Executes SQL queries against DuckDB\n */\nexport function getDefaultTools(\n store: StoreApi<AiSliceState & DuckDbSliceState>,\n options?: DefaultToolsOptions,\n): Record<string, AiSliceTool> {\n const {\n readOnly = true,\n numberOfRowsToShareWithLLM = 0,\n autoSummary = true,\n } = options || {};\n return {\n query: extendedTool({\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 ({type, sqlQuery}) => {\n try {\n const connector = await store.getState().db.getConnector();\n // TODO use options.abortSignal: maybe call db.cancelPendingQuery\n const result = await connector.query(sqlQuery);\n\n const parsedQuery = await store\n .getState()\n .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 const summaryData = await (async () => {\n if (!autoSummary) return null;\n if (parsedQuery.error) return null;\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"]}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import * as arrow from 'apache-arrow';
|
|
1
2
|
type QueryToolResultProps = {
|
|
2
3
|
title: string;
|
|
3
4
|
sqlQuery: string;
|
|
5
|
+
/** Provided in case the query result is already an arrow table */
|
|
6
|
+
arrowTable?: arrow.Table;
|
|
4
7
|
};
|
|
5
|
-
export declare function QueryToolResult(
|
|
8
|
+
export declare function QueryToolResult(props: QueryToolResultProps): import("react/jsx-runtime").JSX.Element;
|
|
6
9
|
export {};
|
|
7
10
|
//# sourceMappingURL=QueryToolResult.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryToolResult.d.ts","sourceRoot":"","sources":["../../../src/components/tools/QueryToolResult.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"QueryToolResult.d.ts","sourceRoot":"","sources":["../../../src/components/tools/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;CAC1B,CAAC;AAEF,wBAAgB,eAAe,CAAC,KAAK,EAAE,oBAAoB,2CA2C1D"}
|
|
@@ -2,8 +2,9 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
|
|
|
2
2
|
import { DataTableModal } from '@sqlrooms/data-table';
|
|
3
3
|
import { Button, CopyButton, useDisclosure } from '@sqlrooms/ui';
|
|
4
4
|
import { TableIcon } from 'lucide-react';
|
|
5
|
-
export function QueryToolResult(
|
|
5
|
+
export function QueryToolResult(props) {
|
|
6
|
+
const { title, sqlQuery } = props;
|
|
6
7
|
const tableModal = useDisclosure();
|
|
7
|
-
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-2", children: _jsxs(Button, { variant: "ghost", size: "
|
|
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-2", 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 }))] }));
|
|
8
9
|
}
|
|
9
10
|
//# sourceMappingURL=QueryToolResult.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryToolResult.js","sourceRoot":"","sources":["../../../src/components/tools/QueryToolResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,cAAc,EAAC,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAC,MAAM,EAAE,UAAU,EAAE,aAAa,EAAC,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"QueryToolResult.js","sourceRoot":"","sources":["../../../src/components/tools/QueryToolResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,cAAc,EAAC,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAC,MAAM,EAAE,UAAU,EAAE,aAAa,EAAC,MAAM,cAAc,CAAC;AAE/D,OAAO,EAAC,SAAS,EAAC,MAAM,cAAc,CAAC;AASvC,MAAM,UAAU,eAAe,CAAC,KAA2B;IACzD,MAAM,EAAC,KAAK,EAAE,QAAQ,EAAC,GAAG,KAAK,CAAC;IAChC,MAAM,UAAU,GAAG,aAAa,EAAE,CAAC;IACnC,OAAO,CACL,8BACE,eAAK,SAAS,EAAC,6GAA6G,aAC1H,cAAK,SAAS,EAAC,sCAAsC,YAAE,QAAQ,GAAO,EACtE,cAAK,SAAS,EAAC,wBAAwB,YACrC,KAAC,UAAU,IACT,IAAI,EAAE,QAAQ,EACd,OAAO,EAAC,OAAO,EACf,IAAI,EAAC,MAAM,EACX,SAAS,EAAC,SAAS,EACnB,SAAS,EAAC,UAAU,GACpB,GACE,IACF,EACN,cAAK,SAAS,EAAC,yBAAyB,YACtC,MAAC,MAAM,IAAC,OAAO,EAAC,OAAO,EAAC,IAAI,EAAC,IAAI,EAAC,OAAO,EAAE,UAAU,CAAC,MAAM,aAC1D,KAAC,SAAS,IAAC,SAAS,EAAC,SAAS,GAAG,EACjC,aAAI,SAAS,EAAC,SAAS,kCAAuB,IACvC,GACL,EAEL,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC,CACvB,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CACjB,KAAC,cAAc,IACb,KAAK,EAAE,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};\n\nexport function QueryToolResult(props: QueryToolResultProps) {\n const {title, sqlQuery} = props;\n const tableModal = useDisclosure();\n return (\n <>\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 <div className=\"flex items-center gap-2\">\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"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Displays a compact, reusable popover with a warning icon and error details.
|
|
3
|
+
* Intended for tool rendering/processing errors to keep UIs consistent.
|
|
4
|
+
*
|
|
5
|
+
* The popover is controllable to optimize performance by only rendering the
|
|
6
|
+
* JsonMonacoEditor when the popover is actually open.
|
|
7
|
+
*/
|
|
8
|
+
export interface ToolErrorMessageProps {
|
|
9
|
+
/**
|
|
10
|
+
* Error object or message to display inside the popover body.
|
|
11
|
+
*/
|
|
12
|
+
error?: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* Optional structured details to render in a Monaco JSON editor.
|
|
15
|
+
*/
|
|
16
|
+
details?: string | object;
|
|
17
|
+
/**
|
|
18
|
+
* Header text shown at the top of the popover.
|
|
19
|
+
* Defaults to "Tool rendering error".
|
|
20
|
+
*/
|
|
21
|
+
title?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Label shown next to the warning icon in the trigger button.
|
|
24
|
+
* Defaults to "Tool rendering failed".
|
|
25
|
+
*/
|
|
26
|
+
triggerLabel?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Alignment of the popover content relative to its trigger.
|
|
29
|
+
* Defaults to "start".
|
|
30
|
+
*/
|
|
31
|
+
align?: 'start' | 'center' | 'end';
|
|
32
|
+
/**
|
|
33
|
+
* Height for the embedded editor when details are provided.
|
|
34
|
+
* Defaults to 300px.
|
|
35
|
+
*/
|
|
36
|
+
editorHeightPx?: number;
|
|
37
|
+
}
|
|
38
|
+
export declare function ToolErrorMessage(props: ToolErrorMessageProps): import("react/jsx-runtime").JSX.Element;
|
|
39
|
+
//# sourceMappingURL=ToolErrorMessage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ToolErrorMessage.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolErrorMessage.tsx"],"names":[],"mappings":"AAUA;;;;;;GAMG;AACH,MAAM,WAAW,qBAAqB;IACpC;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC1B;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,KAAK,CAAC;IACnC;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,qBAAqB,2CAkD5D"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { JsonMonacoEditor } from '@sqlrooms/monaco-editor';
|
|
3
|
+
import { Button, Popover, PopoverContent, PopoverTrigger, useDisclosure, } from '@sqlrooms/ui';
|
|
4
|
+
import { TriangleAlertIcon } from 'lucide-react';
|
|
5
|
+
export function ToolErrorMessage(props) {
|
|
6
|
+
const title = props.title ?? 'Tool rendering error';
|
|
7
|
+
const triggerLabel = props.triggerLabel ?? 'Tool rendering failed';
|
|
8
|
+
const align = props.align ?? 'start';
|
|
9
|
+
const errorText = props.error != null ? String(props.error) : '';
|
|
10
|
+
const editorHeightPx = props.editorHeightPx ?? 300;
|
|
11
|
+
const hasDetails = props.details != null;
|
|
12
|
+
const popoverOpen = useDisclosure();
|
|
13
|
+
return (_jsxs(Popover, { open: popoverOpen.isOpen, onOpenChange: popoverOpen.onToggle, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { className: "w-fit", variant: "ghost", size: "xs", children: _jsxs("p", { className: "flex items-center gap-2 text-xs text-orange-500", children: [_jsx(TriangleAlertIcon, {}), triggerLabel] }) }) }), _jsx(PopoverContent, { align: align, style: { width: '600px', maxWidth: '80%' }, children: _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("div", { className: "border-b text-sm font-medium text-orange-500", children: title }), errorText ? (_jsx("div", { className: "whitespace-pre-wrap font-mono text-xs text-orange-500", children: errorText })) : null, hasDetails && popoverOpen.isOpen ? (_jsx("div", { className: "w-full overflow-hidden rounded-md border", style: { height: editorHeightPx }, children: _jsx(JsonMonacoEditor, { value: props.details, readOnly: true, options: {
|
|
14
|
+
lineNumbers: 'off',
|
|
15
|
+
minimap: { enabled: false },
|
|
16
|
+
scrollBeyondLastLine: false,
|
|
17
|
+
wordWrap: 'on',
|
|
18
|
+
} }) })) : null] }) })] }));
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=ToolErrorMessage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ToolErrorMessage.js","sourceRoot":"","sources":["../../../src/components/tools/ToolErrorMessage.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AACzD,OAAO,EACL,MAAM,EACN,OAAO,EACP,cAAc,EACd,cAAc,EACd,aAAa,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAC,iBAAiB,EAAC,MAAM,cAAc,CAAC;AAwC/C,MA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AAE,EAAC,MAAM,EAAE,cAAc,EAAC,YAE/B,KAAC,gBAAgB,IACf,KAAK,EAAE,KAAK,CAAC,OAAiD,EAC9D,QAAQ,EAAE,IAAI,EACd,OAAO,EAAE;oCACP,WAAW,EAAE,KAAK;oCAClB,OAAO,EAAE,EAAC,OAAO,EAAE,KAAK,EAAC;oCACzB,oBAAoB,EAAE,KAAK;oCAC3B,QAAQ,EAAE,IAAI;iCACf,GACD,GACE,CACP,CAAC,CAAC,CAAC,IAAI,IACJ,GACS,IACT,CACX,CAAC;AACJ,CAAC","sourcesContent":["import {JsonMonacoEditor} from '@sqlrooms/monaco-editor';\nimport {\n Button,\n Popover,\n PopoverContent,\n PopoverTrigger,\n useDisclosure,\n} from '@sqlrooms/ui';\nimport {TriangleAlertIcon} from 'lucide-react';\n\n/**\n * Displays a compact, reusable popover with a warning icon and error details.\n * Intended for tool rendering/processing errors to keep UIs consistent.\n *\n * The popover is controllable to optimize performance by only rendering the\n * JsonMonacoEditor when the popover is actually open.\n */\nexport interface ToolErrorMessageProps {\n /**\n * Error object or message to display inside the popover body.\n */\n error?: unknown;\n /**\n * Optional structured details to render in a Monaco JSON editor.\n */\n details?: string | object;\n /**\n * Header text shown at the top of the popover.\n * Defaults to \"Tool rendering error\".\n */\n title?: string;\n /**\n * Label shown next to the warning icon in the trigger button.\n * Defaults to \"Tool rendering failed\".\n */\n triggerLabel?: string;\n /**\n * Alignment of the popover content relative to its trigger.\n * Defaults to \"start\".\n */\n align?: 'start' | 'center' | 'end';\n /**\n * Height for the embedded editor when details are provided.\n * Defaults to 300px.\n */\n editorHeightPx?: number;\n}\n\nexport function ToolErrorMessage(props: ToolErrorMessageProps) {\n const title = props.title ?? 'Tool rendering error';\n const triggerLabel = props.triggerLabel ?? 'Tool rendering failed';\n const align = props.align ?? 'start';\n const errorText = props.error != null ? String(props.error) : '';\n const editorHeightPx = props.editorHeightPx ?? 300;\n const hasDetails = props.details != null;\n const popoverOpen = useDisclosure();\n\n return (\n <Popover open={popoverOpen.isOpen} onOpenChange={popoverOpen.onToggle}>\n <PopoverTrigger asChild>\n <Button className=\"w-fit\" variant=\"ghost\" size=\"xs\">\n <p className=\"flex items-center gap-2 text-xs text-orange-500\">\n <TriangleAlertIcon />\n {triggerLabel}\n </p>\n </Button>\n </PopoverTrigger>\n <PopoverContent align={align} style={{width: '600px', maxWidth: '80%'}}>\n <div className=\"flex flex-col gap-2\">\n <div className=\"border-b text-sm font-medium text-orange-500\">\n {title}\n </div>\n {errorText ? (\n <div className=\"whitespace-pre-wrap font-mono text-xs text-orange-500\">\n {errorText}\n </div>\n ) : null}\n {hasDetails && popoverOpen.isOpen ? (\n <div\n className=\"w-full overflow-hidden rounded-md border\"\n style={{height: editorHeightPx}}\n >\n <JsonMonacoEditor\n value={props.details as unknown as object | string | undefined}\n readOnly={true}\n options={{\n lineNumbers: 'off',\n minimap: {enabled: false},\n scrollBeyondLastLine: false,\n wordWrap: 'on',\n }}\n />\n </div>\n ) : null}\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolResult.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ToolResult.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAC;AAI1B,OAAO,EAAC,cAAc,EAAC,MAAM,IAAI,CAAC;AAGlC,KAAK,eAAe,GAAG;IACrB,cAAc,EAAE,cAAc,CAAC;IAC/B,cAAc,EAAE,OAAO,CAAC;IACxB,WAAW,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC,EAAE,CAAC,eAAe,CAqEhD,CAAC"}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
3
|
-
import { Button, useDisclosure } from '@sqlrooms/ui';
|
|
4
|
-
import { TriangleAlertIcon } from 'lucide-react';
|
|
2
|
+
import { useDisclosure } from '@sqlrooms/ui';
|
|
5
3
|
import { useStoreWithAi } from '../../AiSlice';
|
|
6
4
|
import { MessageContainer } from '../MessageContainer';
|
|
7
5
|
import { ToolCallErrorBoundary } from './ToolResultErrorBoundary';
|
|
6
|
+
import { ToolErrorMessage } from './ToolErrorMessage';
|
|
8
7
|
export const ToolResult = ({ toolInvocation, additionalData, isCompleted, errorMessage, }) => {
|
|
9
8
|
const { isOpen: showDetails, onToggle: toggleShowDetails } = useDisclosure(false);
|
|
10
9
|
const { toolName, args, state } = toolInvocation;
|
|
@@ -25,11 +24,6 @@ export const ToolResult = ({ toolInvocation, additionalData, isCompleted, errorM
|
|
|
25
24
|
llmResult,
|
|
26
25
|
additionalData,
|
|
27
26
|
isCompleted,
|
|
28
|
-
}, children: [_jsx("div", { className: "text-sm text-gray-500", children: reason && _jsx("span", { children: reason }) }), ToolComponent && isSuccess && isCompleted && (_jsx(ToolCallErrorBoundary, { children: typeof ToolComponent === 'function' ? (_jsx(ToolComponent, { ...llmResult, ...additionalData })) : (ToolComponent) })), isCompleted && (errorMessage || !isSuccess) && (
|
|
29
|
-
lineNumbers: 'off',
|
|
30
|
-
minimap: { enabled: false },
|
|
31
|
-
scrollBeyondLastLine: false,
|
|
32
|
-
wordWrap: 'on',
|
|
33
|
-
} }) }))] }))] }));
|
|
27
|
+
}, children: [_jsx("div", { className: "text-sm text-gray-500", children: reason && _jsx("span", { children: reason }) }), ToolComponent && isSuccess && isCompleted && (_jsx(ToolCallErrorBoundary, { children: typeof ToolComponent === 'function' ? (_jsx(ToolComponent, { ...llmResult, ...additionalData })) : (ToolComponent) })), isCompleted && (errorMessage || !isSuccess) && (_jsx(ToolErrorMessage, { error: errorMessage ?? 'Tool call failed', details: toolInvocation, title: "Tool call error", triggerLabel: "Tool call failed", editorHeightPx: 300 }))] }));
|
|
34
28
|
};
|
|
35
29
|
//# sourceMappingURL=ToolResult.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolResult.js","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":";AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"ToolResult.js","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAS,aAAa,EAAC,MAAM,cAAc,CAAC;AAEnD,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAC,gBAAgB,EAAC,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAC,qBAAqB,EAAC,MAAM,2BAA2B,CAAC;AAEhE,OAAO,EAAC,gBAAgB,EAAC,MAAM,oBAAoB,CAAC;AASpD,MAAM,CAAC,MAAM,UAAU,GAA8B,CAAC,EACpD,cAAc,EACd,cAAc,EACd,WAAW,EACX,YAAY,GACb,EAAE,EAAE;IACH,MAAM,EAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,iBAAiB,EAAC,GACtD,aAAa,CAAC,KAAK,CAAC,CAAC;IAEvB,MAAM,EAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAC,GAAG,cAAc,CAAC;IAC/C,MAAM,SAAS,GAAG,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IAEpE,6CAA6C;IAC7C,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC;IAElC,MAAM,aAAa,GAAG,cAAc,CAAC,CAAC,KAAK,EAAE,EAAE,CAC7C,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CACrC,CAAC;IAEF,+CAA+C;IAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,SAAmB,CAAC;IAExC,6DAA6D;IAC7D,MAAM,SAAS,GACb,OAAO,SAAS,KAAK,QAAQ;QAC7B,SAAS,KAAK,IAAI;QAClB,SAAS,IAAI,SAAS;QACtB,SAAS,CAAC,OAAO,KAAK,IAAI,CAAC;IAE7B,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CACpB,cAAK,SAAS,EAAC,uBAAuB,YAAE,IAAI,GAAO,CACpD,CAAC,CAAC,CAAC,CACF,MAAC,gBAAgB,IACf,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,QAAQ,EACd,OAAO,EAAE;YACP,QAAQ;YACR,IAAI;YACJ,SAAS;YACT,cAAc;YACd,WAAW;SACZ,aAED,cAAK,SAAS,EAAC,uBAAuB,YACnC,MAAM,IAAI,yBAAO,MAAM,GAAQ,GAC5B,EACL,aAAa,IAAI,SAAS,IAAI,WAAW,IAAI,CAC5C,KAAC,qBAAqB,cACnB,OAAO,aAAa,KAAK,UAAU,CAAC,CAAC,CAAC,CACrC,KAAC,aAAa,OACP,SAAqC,KACrC,cAA0C,GAC/C,CACH,CAAC,CAAC,CAAC,CACF,aAAa,CACd,GACqB,CACzB,EACA,WAAW,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,CAAC,IAAI,CAC9C,KAAC,gBAAgB,IACf,KAAK,EAAE,YAAY,IAAI,kBAAkB,EACzC,OAAO,EAAE,cAAc,EACvB,KAAK,EAAC,iBAAiB,EACvB,YAAY,EAAC,kBAAkB,EAC/B,cAAc,EAAE,GAAG,GACnB,CACH,IACgB,CACpB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {Button, useDisclosure} from '@sqlrooms/ui';\nimport React from 'react';\nimport {useStoreWithAi} from '../../AiSlice';\nimport {MessageContainer} from '../MessageContainer';\nimport {ToolCallErrorBoundary} from './ToolResultErrorBoundary';\nimport {ToolInvocation} from 'ai';\nimport {ToolErrorMessage} from './ToolErrorMessage';\n\ntype ToolResultProps = {\n toolInvocation: ToolInvocation;\n additionalData: unknown;\n isCompleted: boolean;\n errorMessage?: string;\n};\n\nexport const ToolResult: React.FC<ToolResultProps> = ({\n toolInvocation,\n additionalData,\n isCompleted,\n errorMessage,\n}) => {\n const {isOpen: showDetails, onToggle: toggleShowDetails} =\n useDisclosure(false);\n\n const {toolName, args, state} = toolInvocation;\n const llmResult = state === 'result' ? toolInvocation.result : null;\n\n // show reason text before tool call complete\n const text = args.reasoning || '';\n\n const ToolComponent = useStoreWithAi((state) =>\n state.ai.findToolComponent(toolName),\n );\n\n // check if args has a property called 'reason'\n const reason = args.reasoning as string;\n\n // check if llmResult is an object and has a success property\n const isSuccess =\n typeof llmResult === 'object' &&\n llmResult !== null &&\n 'success' in llmResult &&\n llmResult.success === true;\n\n return !isCompleted ? (\n <div className=\"text-sm text-gray-500\">{text}</div>\n ) : (\n <MessageContainer\n isSuccess={isSuccess}\n type={toolName}\n content={{\n toolName,\n args,\n llmResult,\n additionalData,\n isCompleted,\n }}\n >\n <div className=\"text-sm text-gray-500\">\n {reason && <span>{reason}</span>}\n </div>\n {ToolComponent && isSuccess && isCompleted && (\n <ToolCallErrorBoundary>\n {typeof ToolComponent === 'function' ? (\n <ToolComponent\n {...(llmResult as Record<string, unknown>)}\n {...(additionalData as Record<string, unknown>)}\n />\n ) : (\n ToolComponent\n )}\n </ToolCallErrorBoundary>\n )}\n {isCompleted && (errorMessage || !isSuccess) && (\n <ToolErrorMessage\n error={errorMessage ?? 'Tool call failed'}\n details={toolInvocation}\n title=\"Tool call error\"\n triggerLabel=\"Tool call failed\"\n editorHeightPx={300}\n />\n )}\n </MessageContainer>\n );\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolResultErrorBoundary.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolResultErrorBoundary.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ToolResultErrorBoundary.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolResultErrorBoundary.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAC,SAAS,EAAC,MAAM,OAAO,CAAC;AAEvC,qBAAa,qBAAsB,SAAQ,KAAK,CAAC,SAAS,CACxD;IAAC,QAAQ,EAAE,SAAS,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAA;CAAC,EAC3C;IAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,KAAK,CAAA;CAAC,CACnC;gBACa,KAAK,EAAE;QAAC,QAAQ,EAAE,SAAS,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAA;KAAC;IAK9D,MAAM,CAAC,wBAAwB;;;IAI/B,iBAAiB,CAAC,KAAK,EAAE,KAAK;IAM9B,MAAM;CAOP"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { jsx as _jsx
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { ToolErrorMessage } from './ToolErrorMessage';
|
|
2
3
|
import React from 'react';
|
|
3
4
|
export class ToolCallErrorBoundary extends React.Component {
|
|
4
5
|
constructor(props) {
|
|
@@ -15,7 +16,7 @@ export class ToolCallErrorBoundary extends React.Component {
|
|
|
15
16
|
}
|
|
16
17
|
render() {
|
|
17
18
|
if (this.state.hasError) {
|
|
18
|
-
return
|
|
19
|
+
return _jsx(ToolErrorMessage, { error: this.state.error });
|
|
19
20
|
}
|
|
20
21
|
return this.props.children;
|
|
21
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolResultErrorBoundary.js","sourceRoot":"","sources":["../../../src/components/tools/ToolResultErrorBoundary.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAkB,MAAM,OAAO,CAAC;AAEvC,MAAM,OAAO,qBAAsB,SAAQ,KAAK,CAAC,SAGhD;IACC,YAAY,KAAkD;QAC5D,KAAK,CAAC,KAAK,CAAC,CAAC;QACb,IAAI,CAAC,KAAK,GAAG,EAAC,QAAQ,EAAE,KAAK,EAAC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,GAAI,CAAC;QACvD,CAAC;QAED,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import {ToolErrorMessage} from './ToolErrorMessage';\nimport React, {ReactNode} from 'react';\n\nexport class ToolCallErrorBoundary extends React.Component<\n {children: ReactNode; onError?: () => void},\n {hasError: boolean; error?: Error}\n> {\n constructor(props: {children: ReactNode; onError?: () => void}) {\n super(props);\n this.state = {hasError: false};\n }\n\n static getDerivedStateFromError() {\n return {hasError: true};\n }\n\n componentDidCatch(error: Error) {\n console.error('Tool call component error:', error);\n this.setState({error});\n this.props.onError?.();\n }\n\n render() {\n if (this.state.hasError) {\n return <ToolErrorMessage error={this.state.error} />;\n }\n\n return this.props.children;\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -19,4 +19,5 @@ export * from './components/session/SessionActions';
|
|
|
19
19
|
export * from './components/session/SessionDropdown';
|
|
20
20
|
export * from './components/session/SessionTitle';
|
|
21
21
|
export * from './components/session/SessionType';
|
|
22
|
+
export * from './components/tools/ToolErrorMessage';
|
|
22
23
|
//# sourceMappingURL=index.d.ts.map
|
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,EACL,aAAa,EACb,aAAa,EACb,cAAc,EACd,qBAAqB,GACtB,MAAM,WAAW,CAAC;AAEnB,YAAY,EAAC,YAAY,EAAC,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EAAC,cAAc,EAAC,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAC,iBAAiB,EAAC,MAAM,2BAA2B,CAAC;AAC5D,YAAY,EAAC,WAAW,EAAC,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAC,eAAe,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAC,sBAAsB,EAAC,MAAM,YAAY,CAAC;AAElD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0CAA0C,CAAC;AACzD,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,aAAa,EACb,aAAa,EACb,cAAc,EACd,qBAAqB,GACtB,MAAM,WAAW,CAAC;AAEnB,YAAY,EAAC,YAAY,EAAC,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EAAC,cAAc,EAAC,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAC,iBAAiB,EAAC,MAAM,2BAA2B,CAAC;AAC5D,YAAY,EAAC,WAAW,EAAC,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAC,eAAe,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAC,sBAAsB,EAAC,MAAM,YAAY,CAAC;AAElD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0CAA0C,CAAC;AACzD,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC;AACjD,cAAc,qCAAqC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -17,4 +17,5 @@ export * from './components/session/SessionActions';
|
|
|
17
17
|
export * from './components/session/SessionDropdown';
|
|
18
18
|
export * from './components/session/SessionTitle';
|
|
19
19
|
export * from './components/session/SessionType';
|
|
20
|
+
export * from './components/tools/ToolErrorMessage';
|
|
20
21
|
//# sourceMappingURL=index.js.map
|
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,EACL,aAAa,EACb,aAAa,EACb,cAAc,EACd,qBAAqB,GACtB,MAAM,WAAW,CAAC;AAGnB,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EAAC,cAAc,EAAC,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAC,iBAAiB,EAAC,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAC,eAAe,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAC,sBAAsB,EAAC,MAAM,YAAY,CAAC;AAElD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0CAA0C,CAAC;AACzD,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC","sourcesContent":["/**\n * {@include ../README.md}\n * @packageDocumentation\n */\n\nexport {\n AiSliceConfig,\n createAiSlice,\n useStoreWithAi,\n createDefaultAiConfig,\n} from './AiSlice';\n\nexport type {AiSliceState} from './AiSlice';\nexport {QueryControls} from './components/QueryControls';\nexport {AnalysisResultsContainer} from './components/AnalysisResultsContainer';\nexport {AnalysisResult} from './components/AnalysisResult';\nexport {useScrollToBottom} from './hooks/useScrollToBottom';\nexport type {AiSliceTool} from './AiSlice';\nexport {QueryToolResult} from './components/tools/QueryToolResult';\nexport {getDefaultInstructions} from './analysis';\n\nexport * from './components/ModelSelector';\nexport * from './components/SessionControls';\nexport * from './components/QueryControls';\nexport * from './components/session/DeleteSessionDialog';\nexport * from './components/session/SessionActions';\nexport * from './components/session/SessionDropdown';\nexport * from './components/session/SessionTitle';\nexport * from './components/session/SessionType';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,aAAa,EACb,aAAa,EACb,cAAc,EACd,qBAAqB,GACtB,MAAM,WAAW,CAAC;AAGnB,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EAAC,cAAc,EAAC,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAC,iBAAiB,EAAC,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAC,eAAe,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAC,sBAAsB,EAAC,MAAM,YAAY,CAAC;AAElD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0CAA0C,CAAC;AACzD,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,mCAAmC,CAAC;AAClD,cAAc,kCAAkC,CAAC;AACjD,cAAc,qCAAqC,CAAC","sourcesContent":["/**\n * {@include ../README.md}\n * @packageDocumentation\n */\n\nexport {\n AiSliceConfig,\n createAiSlice,\n useStoreWithAi,\n createDefaultAiConfig,\n} from './AiSlice';\n\nexport type {AiSliceState} from './AiSlice';\nexport {QueryControls} from './components/QueryControls';\nexport {AnalysisResultsContainer} from './components/AnalysisResultsContainer';\nexport {AnalysisResult} from './components/AnalysisResult';\nexport {useScrollToBottom} from './hooks/useScrollToBottom';\nexport type {AiSliceTool} from './AiSlice';\nexport {QueryToolResult} from './components/tools/QueryToolResult';\nexport {getDefaultInstructions} from './analysis';\n\nexport * from './components/ModelSelector';\nexport * from './components/SessionControls';\nexport * from './components/QueryControls';\nexport * from './components/session/DeleteSessionDialog';\nexport * from './components/session/SessionActions';\nexport * from './components/session/SessionDropdown';\nexport * from './components/session/SessionTitle';\nexport * from './components/session/SessionType';\nexport * from './components/tools/ToolErrorMessage';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sqlrooms/ai",
|
|
3
|
-
"version": "0.24.
|
|
3
|
+
"version": "0.24.22",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -22,13 +22,13 @@
|
|
|
22
22
|
"@openassistant/core": "0.5.17",
|
|
23
23
|
"@openassistant/utils": "0.5.17",
|
|
24
24
|
"@paralleldrive/cuid2": "^2.2.2",
|
|
25
|
-
"@sqlrooms/data-table": "0.24.
|
|
26
|
-
"@sqlrooms/duckdb": "0.24.
|
|
27
|
-
"@sqlrooms/monaco-editor": "0.24.
|
|
28
|
-
"@sqlrooms/room-config": "0.24.
|
|
29
|
-
"@sqlrooms/room-shell": "0.24.
|
|
30
|
-
"@sqlrooms/ui": "0.24.
|
|
31
|
-
"@sqlrooms/utils": "0.24.
|
|
25
|
+
"@sqlrooms/data-table": "0.24.22",
|
|
26
|
+
"@sqlrooms/duckdb": "0.24.22",
|
|
27
|
+
"@sqlrooms/monaco-editor": "0.24.22",
|
|
28
|
+
"@sqlrooms/room-config": "0.24.22",
|
|
29
|
+
"@sqlrooms/room-shell": "0.24.22",
|
|
30
|
+
"@sqlrooms/ui": "0.24.22",
|
|
31
|
+
"@sqlrooms/utils": "0.24.22",
|
|
32
32
|
"ai": "^4.3.19",
|
|
33
33
|
"immer": "^10.1.1",
|
|
34
34
|
"lucide-react": "^0.475.0",
|
|
@@ -48,5 +48,5 @@
|
|
|
48
48
|
"typecheck": "tsc --noEmit",
|
|
49
49
|
"typedoc": "typedoc"
|
|
50
50
|
},
|
|
51
|
-
"gitHead": "
|
|
51
|
+
"gitHead": "bc633cde7574270b679cb6c3d9ce9b496a634133"
|
|
52
52
|
}
|