@sqlrooms/ai 0.19.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/AiSlice.js CHANGED
@@ -164,9 +164,12 @@ export function createAiSlice({ getApiKey, initialAnalysisPrompt = '', customToo
164
164
  id: resultId,
165
165
  prompt: get().ai.analysisPrompt,
166
166
  streamMessage: {
167
- toolCallMessages: [],
168
- reasoning: '',
169
- text: '',
167
+ parts: [
168
+ {
169
+ type: 'text',
170
+ text: '',
171
+ },
172
+ ],
170
173
  },
171
174
  isCompleted: false,
172
175
  });
@@ -239,7 +242,7 @@ function getCurrentSessionFromState(state) {
239
242
  return sessions.find((session) => session.id === currentSessionId);
240
243
  }
241
244
  function findResultById(analysisResults, id) {
242
- return analysisResults.find((r) => r.id === id);
245
+ return analysisResults.find((result) => result.id === id);
243
246
  }
244
247
  /**
245
248
  * Appends the tool results, tool calls, and analysis to the state
@@ -261,36 +264,41 @@ function makeResultsAppender({ resultId, streamMessage, errorMessage, isComplete
261
264
  }
262
265
  const result = findResultById(currentSession.analysisResults, resultId);
263
266
  if (result) {
264
- if (streamMessage) {
265
- result.streamMessage = {
266
- toolCallMessages: (streamMessage.toolCallMessages || []).map((toolCall) => ({
267
- args: { ...toolCall.args },
268
- isCompleted: toolCall.isCompleted,
269
- llmResult: toolCall.llmResult,
270
- additionalData: toolCall.additionalData,
271
- text: toolCall.text,
272
- toolCallId: toolCall.toolCallId,
273
- toolName: toolCall.toolName,
274
- })),
275
- reasoning: streamMessage.reasoning,
276
- text: streamMessage.text,
277
- analysis: streamMessage.analysis,
278
- parts: streamMessage.parts?.map((part) => ({
279
- ...part,
280
- ...(part.type === 'text' && { text: part.text }),
281
- ...(part.type === 'tool' && {
282
- toolCallMessages: part.toolCallMessages?.map((toolCall) => ({
283
- args: { ...toolCall.args },
284
- isCompleted: toolCall.isCompleted,
285
- llmResult: toolCall.llmResult,
286
- additionalData: toolCall.additionalData,
287
- text: toolCall.text,
288
- toolCallId: toolCall.toolCallId,
289
- toolName: toolCall.toolName,
290
- })),
291
- }),
292
- })),
267
+ if (streamMessage && streamMessage.parts) {
268
+ // copy all properties from streamMessage
269
+ const newStreamMessage = {
270
+ parts: streamMessage.parts.map((part) => {
271
+ if (part.type === 'text') {
272
+ return {
273
+ type: 'text',
274
+ text: part.text,
275
+ additionalData: part.additionalData,
276
+ isCompleted: part.isCompleted,
277
+ };
278
+ }
279
+ else if (part.type === 'tool-invocation') {
280
+ return {
281
+ type: 'tool-invocation',
282
+ toolInvocation: {
283
+ toolCallId: part.toolInvocation.toolCallId,
284
+ toolName: part.toolInvocation.toolName,
285
+ args: part.toolInvocation.args,
286
+ state: part.toolInvocation.state,
287
+ result: part.toolInvocation.state === 'result'
288
+ ? part.toolInvocation.result
289
+ : undefined,
290
+ },
291
+ additionalData: part.additionalData,
292
+ isCompleted: part.isCompleted,
293
+ };
294
+ }
295
+ else {
296
+ // TODO: handle other part types later
297
+ return part;
298
+ }
299
+ }),
293
300
  };
301
+ result.streamMessage = newStreamMessage;
294
302
  }
295
303
  if (errorMessage) {
296
304
  result.errorMessage = errorMessage;
@@ -1 +1 @@
1
- {"version":3,"file":"AiSlice.js","sourceRoot":"","sources":["../src/AiSlice.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AAE9C,OAAO,EACL,WAAW,EAEX,qBAAqB,GAGtB,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;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@openassistant/core';\nimport {createId} from '@paralleldrive/cuid2';\nimport {DataTable} from '@sqlrooms/duckdb';\nimport {\n createSlice,\n RoomShellSliceState,\n useBaseRoomShellStore,\n type StateCreator,\n BaseRoomConfig,\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\nexport type AiSliceTool = ExtendedTool<any>;\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 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\nexport function createAiSlice<PC extends BaseRoomConfig & AiSliceConfig>({\n getApiKey,\n initialAnalysisPrompt = '',\n customTools = {},\n getInstructions,\n}: {\n getApiKey: (modelProvider: string) => string;\n initialAnalysisPrompt?: string;\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}): StateCreator<AiSliceState> {\n return createSlice<PC, AiSliceState>((set, get, store) => {\n return {\n ai: {\n analysisPrompt: initialAnalysisPrompt,\n isRunningAnalysis: false,\n\n tools: {\n ...getDefaultTools(store),\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 * 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-4o-mini',\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 toolCallMessages: [],\n reasoning: '',\n text: '',\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 || 'gpt-4o-mini',\n apiKey: getApiKey(currentSession.modelProvider || 'openai'),\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(\n (session: AnalysisSessionSchema) => session.id === currentSessionId,\n );\n}\n\nfunction findResultById(analysisResults: AnalysisResultSchema[], id: string) {\n return analysisResults.find((r: AnalysisResultSchema) => r.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) {\n result.streamMessage = {\n toolCallMessages: (streamMessage.toolCallMessages || []).map(\n (toolCall) => ({\n args: {...toolCall.args},\n isCompleted: toolCall.isCompleted,\n llmResult: toolCall.llmResult,\n additionalData: toolCall.additionalData,\n text: toolCall.text,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n }),\n ),\n reasoning: streamMessage.reasoning,\n text: streamMessage.text,\n analysis: streamMessage.analysis,\n parts: streamMessage.parts?.map((part) => ({\n ...part,\n ...(part.type === 'text' && {text: part.text}),\n ...(part.type === 'tool' && {\n toolCallMessages: part.toolCallMessages?.map((toolCall) => ({\n args: {...toolCall.args},\n isCompleted: toolCall.isCompleted,\n llmResult: toolCall.llmResult,\n additionalData: toolCall.additionalData,\n text: toolCall.text,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n })),\n }),\n })),\n };\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,EACL,WAAW,EAEX,qBAAqB,GAGtB,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,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,EAAE,gBAAgB;YAClC,GAAG,KAAK;SACT;KACF,CAAC;AACJ,CAAC;AA6BD,MAAM,UAAU,aAAa,CAA4C,EACvE,SAAS,EACT,qBAAqB,GAAG,EAAE,EAC1B,WAAW,GAAG,EAAE,EAChB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AAE,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 createSlice,\n RoomShellSliceState,\n useBaseRoomShellStore,\n type StateCreator,\n BaseRoomConfig,\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 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\nexport function createAiSlice<PC extends BaseRoomConfig & AiSliceConfig>({\n getApiKey,\n initialAnalysisPrompt = '',\n customTools = {},\n getInstructions,\n}: {\n getApiKey: (modelProvider: string) => string;\n initialAnalysisPrompt?: string;\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}): StateCreator<AiSliceState> {\n return createSlice<PC, AiSliceState>((set, get, store) => {\n return {\n ai: {\n analysisPrompt: initialAnalysisPrompt,\n isRunningAnalysis: false,\n\n tools: {\n ...getDefaultTools(store),\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 * 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-4o-mini',\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 || 'gpt-4o-mini',\n apiKey: getApiKey(currentSession.modelProvider || 'openai'),\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"]}
@@ -50,7 +50,8 @@ type AnalysisParameters = {
50
50
  * @returns Object containing tool calls executed and the final analysis result
51
51
  */
52
52
  export declare function runAnalysis({ name, tableSchemas, modelProvider, model, apiKey, prompt, abortController, historyAnalysis, onStreamResult, maxSteps, tools, getInstructions, }: AnalysisParameters): Promise<{
53
- messages: import("@openassistant/core").AIMessage[];
53
+ streamMessage: StreamMessage;
54
+ messages: import("ai").CoreMessage[];
54
55
  }>;
55
56
  /**
56
57
  * Default tools available to the AI assistant for data analysis
@@ -1 +1 @@
1
- {"version":3,"file":"analysis.d.ts","sourceRoot":"","sources":["../src/analysis.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,aAAa,EAEd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,SAAS,EAET,gBAAgB,EACjB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAC,YAAY,EAAE,WAAW,EAAC,MAAM,WAAW,CAAC;AAEpD,OAAO,EAAC,oBAAoB,EAAsB,MAAM,WAAW,CAAC;AAuDpE;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,YAAY,EAAE,SAAS,EAAE,GAAG,MAAM,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,EACd,QAAY,EACZ,KAAU,EACV,eAAe,GAChB,EAAE,kBAAkB;;;GA2CpB;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,QAAQ,CAAC,YAAY,GAAG,gBAAgB,CAAC,GAC/C,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAkD7B"}
package/dist/analysis.js CHANGED
@@ -1,7 +1,9 @@
1
- import { createAssistant, rebuildMessages, tool, } from '@openassistant/core';
1
+ import { createAssistant, rebuildMessages, } from '@openassistant/core';
2
+ import { extendedTool } from '@openassistant/utils';
2
3
  import { arrowTableToJson, } from '@sqlrooms/duckdb';
3
4
  import { QueryToolResult } from './components/tools/QueryToolResult';
4
5
  import { QueryToolParameters } from './schemas';
6
+ import { convertToCoreMessages } from 'ai';
5
7
  /**
6
8
  * System prompt template for the AI assistant that provides instructions for:
7
9
  * - Using DuckDB-specific SQL syntax and functions
@@ -13,6 +15,7 @@ const DEFAULT_INSTRUCTIONS = `
13
15
  You are analyzing tables in DuckDB database in the context of a room.
14
16
 
15
17
  Instructions for analysis:
18
+ - When calling query tool, please use type: 'query'
16
19
  - Use DuckDB-specific SQL syntax and functions (not Oracle, PostgreSQL, or other SQL dialects)
17
20
  - Some key DuckDB-specific functions to use:
18
21
  * regexp_matches() for regex (not regexp_like)
@@ -100,7 +103,7 @@ export async function runAnalysis({ name = 'sqlrooms-ai', tableSchemas, modelPro
100
103
  instructions: getInstructions
101
104
  ? getInstructions(tableSchemas)
102
105
  : getDefaultInstructions(tableSchemas),
103
- functions: tools,
106
+ tools: tools,
104
107
  temperature: 0,
105
108
  toolChoice: 'auto', // this will enable streaming
106
109
  maxSteps,
@@ -113,12 +116,12 @@ export async function runAnalysis({ name = 'sqlrooms-ai', tableSchemas, modelPro
113
116
  response: analysis.streamMessage,
114
117
  }));
115
118
  const initialMessages = rebuildMessages(historyMessages);
116
- assistant.setMessages(initialMessages);
119
+ assistant.setMessages(convertToCoreMessages(initialMessages));
117
120
  }
118
121
  // process the prompt
119
122
  const newMessages = await assistant.processTextMessage({
120
123
  textMessage: prompt,
121
- streamMessageCallback: ({ isCompleted, message }) => {
124
+ streamMessageCallback: ({ isCompleted, message, }) => {
122
125
  onStreamResult(isCompleted ?? false, message);
123
126
  },
124
127
  });
@@ -131,7 +134,7 @@ export async function runAnalysis({ name = 'sqlrooms-ai', tableSchemas, modelPro
131
134
  */
132
135
  export function getDefaultTools(store) {
133
136
  return {
134
- query: tool({
137
+ query: extendedTool({
135
138
  description: `A tool for running SQL queries on the tables in the database.
136
139
  Please only run one query at a time.
137
140
  If a query fails, please don't try to run it again with the same syntax.`,
@@ -1 +1 @@
1
- {"version":3,"file":"analysis.js","sourceRoot":"","sources":["../src/analysis.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EAEf,IAAI,GACL,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,gBAAgB,GAIjB,MAAM,kBAAkB,CAAC;AAI1B,OAAO,EAAC,eAAe,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,EAAuB,mBAAmB,EAAC,MAAM,WAAW,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4C5B,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;AACH,KAAK,UAAU,eAAe,CAAC,SAA0B,EAAE,QAAgB;IACzE,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,eAAe,IAAI,CAAC,GAAG,EAAE,E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AE/C,kDAAkD;oBAClD,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;oBACrC,MAAM,YAAY,GAAG,gBAAgB,CAAC,SAAS,CAAC,CAAC;oBAEjD,OAAO;wBACL,SAAS,EAAE;4BACT,OAAO,EAAE,IAAI;4BACb,IAAI,EAAE;gCACJ,IAAI;gCACJ,OAAO,EAAE,WAAW;gCACpB,YAAY;6BACb;yBACF;wBACD,cAAc,EAAE;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 tool,\n} from '@openassistant/core';\nimport {\n arrowTableToJson,\n DataTable,\n DuckDbConnector,\n DuckDbSliceState,\n} from '@sqlrooms/duckdb';\n\nimport type {StoreApi} from '@sqlrooms/room-shell';\nimport {AiSliceState, AiSliceTool} from './AiSlice';\nimport {QueryToolResult} from './components/tools/QueryToolResult';\nimport {AnalysisResultSchema, QueryToolParameters} from './schemas';\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- 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\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 /** 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 /**\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 apiKey,\n prompt,\n abortController,\n historyAnalysis,\n onStreamResult,\n maxSteps = 5,\n tools = {},\n getInstructions,\n}: AnalysisParameters) {\n // get the singleton assistant instance\n const assistant = await createAssistant({\n name,\n modelProvider,\n model,\n apiKey,\n version: 'v1',\n instructions: getInstructions\n ? getInstructions(tableSchemas)\n : getDefaultInstructions(tableSchemas),\n functions: tools,\n temperature: 0,\n toolChoice: 'auto', // this will enable streaming\n maxSteps,\n ...(abortController ? {abortController} : {}),\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,\n }));\n const initialMessages = rebuildMessages(historyMessages);\n assistant.setMessages(initialMessages);\n }\n\n // process the prompt\n const newMessages = await assistant.processTextMessage({\n textMessage: prompt,\n streamMessageCallback: ({isCompleted, message}) => {\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): Record<string, AiSliceTool> {\n return {\n query: tool({\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 // TODO: specify the return type e.g. Promise<Partial<ToolCallMessage>>\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 // Get first 2 rows of the result as a json object\n const subResult = result.slice(0, 2);\n const firstTwoRows = arrowTableToJson(subResult);\n\n return {\n llmResult: {\n success: true,\n data: {\n type,\n summary: summaryData,\n firstTwoRows,\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,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AAC;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} 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 calling query tool, please use type: '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\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 /** 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 /**\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 apiKey,\n prompt,\n abortController,\n historyAnalysis,\n onStreamResult,\n maxSteps = 5,\n tools = {},\n getInstructions,\n}: AnalysisParameters) {\n // get the singleton assistant instance\n const assistant = await createAssistant({\n name,\n modelProvider,\n model,\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 });\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): 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 // TODO: specify the return type e.g. Promise<Partial<ToolCallMessage>>\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 // Get first 2 rows of the result as a json object\n const subResult = result.slice(0, 2);\n const firstTwoRows = arrowTableToJson(subResult);\n\n return {\n llmResult: {\n success: true,\n data: {\n type,\n summary: summaryData,\n firstTwoRows,\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 +1 @@
1
- {"version":3,"file":"AnalysisResult.d.ts","sourceRoot":"","sources":["../../src/components/AnalysisResult.tsx"],"names":[],"mappings":"AAeA,OAAO,EAAC,oBAAoB,EAAC,MAAM,YAAY,CAAC;AAKhD;;;GAGG;AACH,KAAK,mBAAmB,GAAG;IACzB,MAAM,EAAE,oBAAoB,CAAC;IAC7B,sBAAsB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C,CAAC;AAaF;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,EAAE,CAAC,mBAAmB,CAgHxD,CAAC"}
1
+ {"version":3,"file":"AnalysisResult.d.ts","sourceRoot":"","sources":["../../src/components/AnalysisResult.tsx"],"names":[],"mappings":"AAgBA,OAAO,EAAC,oBAAoB,EAAC,MAAM,YAAY,CAAC;AAKhD;;;GAGG;AACH,KAAK,mBAAmB,GAAG;IACzB,MAAM,EAAE,oBAAoB,CAAC;IAC7B,sBAAsB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C,CAAC;AAaF;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,EAAE,CAAC,mBAAmB,CAiHxD,CAAC"}
@@ -30,6 +30,7 @@ export const AnalysisResult = ({ result, onDeleteAnalysisResult, }) => {
30
30
  // the toolResults are reasoning steps that the LLM took to achieve the final result
31
31
  // by calling function tools to answer the prompt
32
32
  const { id, prompt, errorMessage, streamMessage } = result;
33
+ const parts = streamMessage.parts;
33
34
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);
34
35
  return (_jsxs("div", { className: "group flex w-full flex-col gap-2 text-sm", children: [_jsx("div", { className: "mb-2 flex items-center gap-2 rounded-md text-gray-700 dark:text-gray-100", children: _jsxs("div", { className: "flex w-full items-center gap-2 rounded-md border p-4 text-sm", children: [_jsx(SquareTerminalIcon, { className: "h-4 w-4" }), _jsx("div", { className: "flex-1", children: prompt }), _jsxs("div", { className: "flex gap-2 opacity-0 transition-opacity group-hover:opacity-100", children: [_jsxs(Popover, { children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "icon", className: "h-6 w-6", children: _jsx(CodeIcon, { className: "h-4 w-4" }) }) }), _jsx(PopoverContent, { className: "max-h-[400px] w-[400px] overflow-auto", align: "end", side: "right", children: _jsx(JsonMonacoEditor, { value: stringifyResult(result), readOnly: true, className: "h-[300px]", options: {
35
36
  minimap: { enabled: false },
@@ -41,6 +42,6 @@ export const AnalysisResult = ({ result, onDeleteAnalysisResult, }) => {
41
42
  } }) })] }), _jsx(Button, { variant: "ghost", size: "icon", className: "h-6 w-6", onClick: () => setShowDeleteConfirmation(true), children: _jsx(TrashIcon, { className: "h-4 w-4" }) }), _jsx(Dialog, { open: showDeleteConfirmation, onOpenChange: setShowDeleteConfirmation, children: _jsxs(DialogContent, { className: "sm:max-w-[425px]", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Confirm Deletion" }), _jsx(DialogDescription, { children: "Are you sure you want to delete this analysis result? This action cannot be undone." })] }), _jsxs(DialogFooter, { children: [_jsx(Button, { variant: "outline", onClick: () => setShowDeleteConfirmation(false), children: "Cancel" }), _jsx(Button, { variant: "destructive", onClick: () => {
42
43
  onDeleteAnalysisResult(id);
43
44
  setShowDeleteConfirmation(false);
44
- }, children: "Delete" })] })] }) })] })] }) }), streamMessage.parts?.map((part, index) => (_jsxs("div", { children: [part.type === 'text' && (_jsx(AnalysisAnswer, { content: part.text, isAnswer: index === (streamMessage.parts?.length || 0) - 1 })), part.type === 'tool' && (_jsx("div", { children: part.toolCallMessages.map((toolCallMessage) => (_jsx(ToolResult, { toolCallMessage: toolCallMessage }, toolCallMessage.toolCallId))) }))] }, index))), errorMessage && _jsx(ErrorMessage, { errorMessage: errorMessage.error })] }));
45
+ }, children: "Delete" })] })] }) })] })] }) }), parts?.map((part, index) => (_jsxs("div", { children: [part.type === 'text' && (_jsx(AnalysisAnswer, { content: part.text, isAnswer: index === (streamMessage.parts?.length || 0) - 1 })), part.type === 'tool-invocation' && (_jsx("div", { children: _jsx(ToolResult, { toolInvocation: part.toolInvocation, additionalData: part.additionalData, isCompleted: result.isCompleted }, part.toolInvocation.toolCallId) }))] }, index))), errorMessage && _jsx(ErrorMessage, { errorMessage: errorMessage.error })] }));
45
46
  };
46
47
  //# sourceMappingURL=AnalysisResult.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AnalysisResult.js","sourceRoot":"","sources":["../../src/components/AnalysisResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,gBAA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wDACnC,CAAC,uBAGM,IACI,IACD,GACT,IACL,IACF,GACF,EAEL,aAAa,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CACzC,0BACG,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,CACvB,KAAC,cAAc,IACb,OAAO,EAAE,IAAI,CAAC,IAAI,EAClB,QAAQ,EAAE,KAAK,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,IAAI,CAAC,CAAC,GAAG,CAAC,GAC1D,CACH,EACA,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,CACvB,wBACG,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,eAAe,EAAE,EAAE,CAAC,CAC9C,KAAC,UAAU,IAET,eAAe,EAAE,eAAe,IAD3B,eAAe,CAAC,UAAU,CAE/B,CACH,CAAC,GACE,CACP,KAhBO,KAAK,CAiBT,CACP,CAAC,EAED,YAAY,IAAI,KAAC,YAAY,IAAC,YAAY,EAAE,YAAY,CAAC,KAAK,GAAI,IAC/D,CACP,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {JsonMonacoEditor} from '@sqlrooms/monaco-editor';\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from '@sqlrooms/ui';\nimport {CodeIcon, SquareTerminalIcon, TrashIcon} from 'lucide-react';\nimport {useState} from 'react';\nimport {AnalysisResultSchema} from '../schemas';\nimport {AnalysisAnswer} from './AnalysisAnswer';\nimport {ErrorMessage} from './ErrorMessage';\nimport {ToolResult} from './tools/ToolResult';\n\n/**\n * Props for the AnalysisResult component\n * @property {AnalysisResultSchema} result - The result of the analysis containing prompt, tool calls, and analysis data\n */\ntype AnalysisResultProps = {\n result: AnalysisResultSchema;\n onDeleteAnalysisResult: (id: string) => void;\n};\n\n/**\n * Stringify the result of the analysis, excluding toolCallMessages.\n * Used to display raw result data in a code view.\n *\n * @param result - The complete analysis result\n * @returns A JSON string representation of the result without toolCallMessages\n */\nconst stringifyResult = (result: AnalysisResultSchema) => {\n return JSON.stringify(result, null, 2);\n};\n\n/**\n * Component that displays the results of an AI analysis.\n * Shows the original prompt, intermediate tool calls, final analysis text,\n * and any tool results.\n *\n * @component\n * @param props - Component props\n * @param props.result - The analysis result data to display\n * @returns A React component displaying the analysis results\n */\nexport const AnalysisResult: React.FC<AnalysisResultProps> = ({\n result,\n onDeleteAnalysisResult,\n}) => {\n // the toolResults are reasoning steps that the LLM took to achieve the final result\n // by calling function tools to answer the prompt\n const {id, prompt, errorMessage, streamMessage} = result;\n const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);\n\n return (\n <div className=\"group flex w-full flex-col gap-2 text-sm\">\n <div className=\"mb-2 flex items-center gap-2 rounded-md text-gray-700 dark:text-gray-100\">\n <div className=\"flex w-full items-center gap-2 rounded-md border p-4 text-sm\">\n <SquareTerminalIcon className=\"h-4 w-4\" />\n {/** render prompt */}\n <div className=\"flex-1\">{prompt}</div>\n <div className=\"flex gap-2 opacity-0 transition-opacity group-hover:opacity-100\">\n <Popover>\n <PopoverTrigger asChild>\n <Button variant=\"ghost\" size=\"icon\" className=\"h-6 w-6\">\n <CodeIcon className=\"h-4 w-4\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent\n className=\"max-h-[400px] w-[400px] overflow-auto\"\n align=\"end\"\n side=\"right\"\n >\n <JsonMonacoEditor\n value={stringifyResult(result)}\n readOnly={true}\n className=\"h-[300px]\"\n options={{\n minimap: {enabled: false},\n scrollBeyondLastLine: false,\n automaticLayout: true,\n folding: true,\n lineNumbers: false,\n wordWrap: 'on',\n }}\n />\n </PopoverContent>\n </Popover>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n className=\"h-6 w-6\"\n onClick={() => setShowDeleteConfirmation(true)}\n >\n <TrashIcon className=\"h-4 w-4\" />\n </Button>\n\n {/* Delete Confirmation Dialog */}\n <Dialog\n open={showDeleteConfirmation}\n onOpenChange={setShowDeleteConfirmation}\n >\n <DialogContent className=\"sm:max-w-[425px]\">\n <DialogHeader>\n <DialogTitle>Confirm Deletion</DialogTitle>\n <DialogDescription>\n Are you sure you want to delete this analysis result? This\n action cannot be undone.\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button\n variant=\"outline\"\n onClick={() => setShowDeleteConfirmation(false)}\n >\n Cancel\n </Button>\n <Button\n variant=\"destructive\"\n onClick={() => {\n onDeleteAnalysisResult(id);\n setShowDeleteConfirmation(false);\n }}\n >\n Delete\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </div>\n </div>\n </div>\n {/** render parts */}\n {streamMessage.parts?.map((part, index) => (\n <div key={index}>\n {part.type === 'text' && (\n <AnalysisAnswer\n content={part.text}\n isAnswer={index === (streamMessage.parts?.length || 0) - 1}\n />\n )}\n {part.type === 'tool' && (\n <div>\n {part.toolCallMessages.map((toolCallMessage) => (\n <ToolResult\n key={toolCallMessage.toolCallId}\n toolCallMessage={toolCallMessage}\n />\n ))}\n </div>\n )}\n </div>\n ))}\n {/** render error message */}\n {errorMessage && <ErrorMessage errorMessage={errorMessage.error} />}\n </div>\n );\n};\n"]}
1
+ {"version":3,"file":"AnalysisResult.js","sourceRoot":"","sources":["../../src/components/AnalysisResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AACzD,OAAO,EACL,MAAM,EACN,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,OAAO,EACP,cAAc,EACd,cAAc,GACf,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAC,QAAQ,EAAE,kBAAkB,EAAE,SAAS,EAAC,MAAM,cAAc,CAAC;AACrE,OAAO,EAAC,QAAQ,EAAC,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAC,cAAc,EAAC,MAAM,kBAAkB,CAAC;AAChD,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G,CAAC,GAC1D,CACH,EACA,IAAI,CAAC,IAAI,KAAK,iBAAiB,IAAI,CAClC,wBACE,KAAC,UAAU,IAET,cAAc,EAAE,IAAI,CAAC,cAAc,EACnC,cAAc,EAAE,IAAI,CAAC,cAAc,EACnC,WAAW,EAAE,MAAM,CAAC,WAAW,IAH1B,IAAI,CAAC,cAAc,CAAC,UAAU,CAInC,GACE,CACP,KAhBO,KAAK,CAiBT,CACP,CAAC,EAED,YAAY,IAAI,KAAC,YAAY,IAAC,YAAY,EAAE,YAAY,CAAC,KAAK,GAAI,IAC/D,CACP,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {JsonMonacoEditor} from '@sqlrooms/monaco-editor';\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Popover,\n PopoverContent,\n PopoverTrigger,\n} from '@sqlrooms/ui';\nimport {StreamMessagePart} from '@openassistant/core';\nimport {CodeIcon, SquareTerminalIcon, TrashIcon} from 'lucide-react';\nimport {useState} from 'react';\nimport {AnalysisResultSchema} from '../schemas';\nimport {AnalysisAnswer} from './AnalysisAnswer';\nimport {ErrorMessage} from './ErrorMessage';\nimport {ToolResult} from './tools/ToolResult';\n\n/**\n * Props for the AnalysisResult component\n * @property {AnalysisResultSchema} result - The result of the analysis containing prompt, tool calls, and analysis data\n */\ntype AnalysisResultProps = {\n result: AnalysisResultSchema;\n onDeleteAnalysisResult: (id: string) => void;\n};\n\n/**\n * Stringify the result of the analysis, excluding toolCallMessages.\n * Used to display raw result data in a code view.\n *\n * @param result - The complete analysis result\n * @returns A JSON string representation of the result without toolCallMessages\n */\nconst stringifyResult = (result: AnalysisResultSchema) => {\n return JSON.stringify(result, null, 2);\n};\n\n/**\n * Component that displays the results of an AI analysis.\n * Shows the original prompt, intermediate tool calls, final analysis text,\n * and any tool results.\n *\n * @component\n * @param props - Component props\n * @param props.result - The analysis result data to display\n * @returns A React component displaying the analysis results\n */\nexport const AnalysisResult: React.FC<AnalysisResultProps> = ({\n result,\n onDeleteAnalysisResult,\n}) => {\n // the toolResults are reasoning steps that the LLM took to achieve the final result\n // by calling function tools to answer the prompt\n const {id, prompt, errorMessage, streamMessage} = result;\n const parts = streamMessage.parts as StreamMessagePart[];\n const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);\n\n return (\n <div className=\"group flex w-full flex-col gap-2 text-sm\">\n <div className=\"mb-2 flex items-center gap-2 rounded-md text-gray-700 dark:text-gray-100\">\n <div className=\"flex w-full items-center gap-2 rounded-md border p-4 text-sm\">\n <SquareTerminalIcon className=\"h-4 w-4\" />\n {/** render prompt */}\n <div className=\"flex-1\">{prompt}</div>\n <div className=\"flex gap-2 opacity-0 transition-opacity group-hover:opacity-100\">\n <Popover>\n <PopoverTrigger asChild>\n <Button variant=\"ghost\" size=\"icon\" className=\"h-6 w-6\">\n <CodeIcon className=\"h-4 w-4\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent\n className=\"max-h-[400px] w-[400px] overflow-auto\"\n align=\"end\"\n side=\"right\"\n >\n <JsonMonacoEditor\n value={stringifyResult(result)}\n readOnly={true}\n className=\"h-[300px]\"\n options={{\n minimap: {enabled: false},\n scrollBeyondLastLine: false,\n automaticLayout: true,\n folding: true,\n lineNumbers: false,\n wordWrap: 'on',\n }}\n />\n </PopoverContent>\n </Popover>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n className=\"h-6 w-6\"\n onClick={() => setShowDeleteConfirmation(true)}\n >\n <TrashIcon className=\"h-4 w-4\" />\n </Button>\n\n {/* Delete Confirmation Dialog */}\n <Dialog\n open={showDeleteConfirmation}\n onOpenChange={setShowDeleteConfirmation}\n >\n <DialogContent className=\"sm:max-w-[425px]\">\n <DialogHeader>\n <DialogTitle>Confirm Deletion</DialogTitle>\n <DialogDescription>\n Are you sure you want to delete this analysis result? This\n action cannot be undone.\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button\n variant=\"outline\"\n onClick={() => setShowDeleteConfirmation(false)}\n >\n Cancel\n </Button>\n <Button\n variant=\"destructive\"\n onClick={() => {\n onDeleteAnalysisResult(id);\n setShowDeleteConfirmation(false);\n }}\n >\n Delete\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </div>\n </div>\n </div>\n {/** render parts */}\n {parts?.map((part, index) => (\n <div key={index}>\n {part.type === 'text' && (\n <AnalysisAnswer\n content={part.text}\n isAnswer={index === (streamMessage.parts?.length || 0) - 1}\n />\n )}\n {part.type === 'tool-invocation' && (\n <div>\n <ToolResult\n key={part.toolInvocation.toolCallId}\n toolInvocation={part.toolInvocation}\n additionalData={part.additionalData}\n isCompleted={result.isCompleted}\n />\n </div>\n )}\n </div>\n ))}\n {/** render error message */}\n {errorMessage && <ErrorMessage errorMessage={errorMessage.error} />}\n </div>\n );\n};\n"]}
@@ -1,7 +1,9 @@
1
- import { ToolCallMessage } from '@openassistant/core';
2
1
  import React from 'react';
2
+ import { ToolInvocation } from 'ai';
3
3
  type ToolResultProps = {
4
- toolCallMessage: ToolCallMessage;
4
+ toolInvocation: ToolInvocation;
5
+ additionalData: unknown;
6
+ isCompleted: boolean;
5
7
  errorMessage?: string;
6
8
  };
7
9
  export declare const ToolResult: React.FC<ToolResultProps>;
@@ -1 +1 @@
1
- {"version":3,"file":"ToolResult.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,qBAAqB,CAAC;AAIpD,OAAO,KAAK,MAAM,OAAO,CAAC;AAK1B,KAAK,eAAe,GAAG;IACrB,eAAe,EAAE,eAAe,CAAC;IACjC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC,EAAE,CAAC,eAAe,CAmFhD,CAAC"}
1
+ {"version":3,"file":"ToolResult.d.ts","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,MAAM,OAAO,CAAC;AAI1B,OAAO,EAAC,cAAc,EAAC,MAAM,IAAI,CAAC;AAElC,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,CAyFhD,CAAC"}
@@ -5,9 +5,12 @@ import { TriangleAlertIcon } from 'lucide-react';
5
5
  import { useStoreWithAi } from '../../AiSlice';
6
6
  import { MessageContainer } from '../MessageContainer';
7
7
  import { ToolCallErrorBoundary } from './ToolResultErrorBoundary';
8
- export const ToolResult = ({ toolCallMessage, errorMessage, }) => {
8
+ export const ToolResult = ({ toolInvocation, additionalData, isCompleted, errorMessage, }) => {
9
9
  const { isOpen: showDetails, onToggle: toggleShowDetails } = useDisclosure(false);
10
- const { toolName, args, llmResult, additionalData, text, isCompleted } = toolCallMessage;
10
+ const { toolName, args, state } = toolInvocation;
11
+ const llmResult = state === 'result' ? toolInvocation.result : null;
12
+ // show reason text before tool call complete
13
+ const text = args.reasoning || '';
11
14
  const ToolComponent = useStoreWithAi((state) => state.ai.findToolComponent(toolName));
12
15
  // check if args has a property called 'reason'
13
16
  const reason = args.reasoning;
@@ -22,7 +25,7 @@ export const ToolResult = ({ toolCallMessage, errorMessage, }) => {
22
25
  llmResult,
23
26
  additionalData,
24
27
  isCompleted,
25
- }, 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) && (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Button, { className: "w-fit", variant: "ghost", size: "xs", onClick: () => toggleShowDetails(), children: _jsxs("p", { className: "flex items-center gap-2 text-xs text-orange-500", children: [_jsx(TriangleAlertIcon, {}), "Tool call failed"] }) }), showDetails && (_jsx("div", { className: "h-[300px] w-full overflow-hidden rounded-md border", children: _jsx(JsonMonacoEditor, { value: toolCallMessage, readOnly: true, options: {
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) && (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Button, { className: "w-fit", variant: "ghost", size: "xs", onClick: () => toggleShowDetails(), children: _jsxs("p", { className: "flex items-center gap-2 text-xs text-orange-500", children: [_jsx(TriangleAlertIcon, {}), "Tool call failed"] }) }), showDetails && (_jsx("div", { className: "h-[300px] w-full overflow-hidden rounded-md border", children: _jsx(JsonMonacoEditor, { value: toolInvocation, readOnly: true, options: {
26
29
  lineNumbers: false,
27
30
  minimap: { enabled: false },
28
31
  scrollBeyondLastLine: false,
@@ -1 +1 @@
1
- {"version":3,"file":"ToolResult.js","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":";AACA,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAC,MAAM,EAAE,aAAa,EAAC,MAAM,cAAc,CAAC;AACnD,OAAO,EAAC,iBAAiB,EAAC,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAC,gBAAgB,EAAC,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAC,qBAAqB,EAAC,MAAM,2BAA2B,CAAC;AAOhE,MAAM,CAAC,MAAM,UAAU,GAA8B,CAAC,EACpD,eAAe,EACf,YAAY,GACb,EAAE,EAAE;IACH,MAAM,E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C,OAAO,EACjB,OAAO,EAAC,OAAO,EACf,IAAI,EAAC,IAAI,EACT,OAAO,EAAE,GAAG,EAAE,CAAC,iBAAiB,EAAE,YAElC,aAAG,SAAS,EAAC,iDAAiD,aAC5D,KAAC,iBAAiB,KAAG,wBAEnB,GACG,EACR,WAAW,IAAI,CACd,cAAK,SAAS,EAAC,oDAAoD,YACjE,KAAC,gBAAgB,IACf,KAAK,EAAE,eAAe,EACtB,QAAQ,EAAE,IAAI,EACd,OAAO,EAAE;gCACP,WAAW,EAAE,KAAK;gCAClB,OAAO,EAAE,EAAC,OAAO,EAAE,KAAK,EAAC;gCACzB,oBAAoB,EAAE,KAAK;gCAC3B,QAAQ,EAAE,IAAI;6BACf,GACD,GACE,CACP,IACG,CACP,IACgB,CACpB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {ToolCallMessage} from '@openassistant/core';\nimport {JsonMonacoEditor} from '@sqlrooms/monaco-editor';\nimport {Button, useDisclosure} from '@sqlrooms/ui';\nimport {TriangleAlertIcon} from 'lucide-react';\nimport React from 'react';\nimport {useStoreWithAi} from '../../AiSlice';\nimport {MessageContainer} from '../MessageContainer';\nimport {ToolCallErrorBoundary} from './ToolResultErrorBoundary';\n\ntype ToolResultProps = {\n toolCallMessage: ToolCallMessage;\n errorMessage?: string;\n};\n\nexport const ToolResult: React.FC<ToolResultProps> = ({\n toolCallMessage,\n errorMessage,\n}) => {\n const {isOpen: showDetails, onToggle: toggleShowDetails} =\n useDisclosure(false);\n const {toolName, args, llmResult, additionalData, text, isCompleted} =\n toolCallMessage;\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 <div className=\"flex flex-col gap-2\">\n <Button\n className=\"w-fit\"\n variant=\"ghost\"\n size=\"xs\"\n onClick={() => toggleShowDetails()}\n >\n <p className=\"flex items-center gap-2 text-xs text-orange-500\">\n <TriangleAlertIcon />\n Tool call failed\n </p>\n </Button>\n {showDetails && (\n <div className=\"h-[300px] w-full overflow-hidden rounded-md border\">\n <JsonMonacoEditor\n value={toolCallMessage}\n readOnly={true}\n options={{\n lineNumbers: false,\n minimap: {enabled: false},\n scrollBeyondLastLine: false,\n wordWrap: 'on',\n }}\n />\n </div>\n )}\n </div>\n )}\n </MessageContainer>\n );\n};\n"]}
1
+ {"version":3,"file":"ToolResult.js","sourceRoot":"","sources":["../../../src/components/tools/ToolResult.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAC,MAAM,EAAE,aAAa,EAAC,MAAM,cAAc,CAAC;AACnD,OAAO,EAAC,iBAAiB,EAAC,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAC,cAAc,EAAC,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAC,gBAAgB,EAAC,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAC,qBAAqB,EAAC,MAAM,2BAA2B,CAAC;AAUhE,MAAM,CAAC,MAAM,UAAU,GAA8B,CAAC,EACpD,cAAc,EACd,cAAc,EACd,WAAW,EACX,YAAY,GACb,EAAE,EAAE;IACH,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,CAAC,CACF,aAAa,CACd,GACqB,CACzB,EACA,WAAW,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,CAAC,IAAI,CAC9C,eAAK,SAAS,EAAC,qBAAqB,aAClC,KAAC,MAAM,IACL,SAAS,EAAC,OAAO,EACjB,OAAO,EAAC,OAAO,EACf,IAAI,EAAC,IAAI,EACT,OAAO,EAAE,GAAG,EAAE,CAAC,iBAAiB,EAAE,YAElC,aAAG,SAAS,EAAC,iDAAiD,aAC5D,KAAC,iBAAiB,KAAG,wBAEnB,GACG,EACR,WAAW,IAAI,CACd,cAAK,SAAS,EAAC,oDAAoD,YACjE,KAAC,gBAAgB,IACf,KAAK,EAAE,cAAc,EACrB,QAAQ,EAAE,IAAI,EACd,OAAO,EAAE;gCACP,WAAW,EAAE,KAAK;gCAClB,OAAO,EAAE,EAAC,OAAO,EAAE,KAAK,EAAC;gCACzB,oBAAoB,EAAE,KAAK;gCAC3B,QAAQ,EAAE,IAAI;6BACf,GACD,GACE,CACP,IACG,CACP,IACgB,CACpB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {JsonMonacoEditor} from '@sqlrooms/monaco-editor';\nimport {Button, useDisclosure} from '@sqlrooms/ui';\nimport {TriangleAlertIcon} from 'lucide-react';\nimport React from 'react';\nimport {useStoreWithAi} from '../../AiSlice';\nimport {MessageContainer} from '../MessageContainer';\nimport {ToolCallErrorBoundary} from './ToolResultErrorBoundary';\nimport {ToolInvocation} from 'ai';\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 <div className=\"flex flex-col gap-2\">\n <Button\n className=\"w-fit\"\n variant=\"ghost\"\n size=\"xs\"\n onClick={() => toggleShowDetails()}\n >\n <p className=\"flex items-center gap-2 text-xs text-orange-500\">\n <TriangleAlertIcon />\n Tool call failed\n </p>\n </Button>\n {showDetails && (\n <div className=\"h-[300px] w-full overflow-hidden rounded-md border\">\n <JsonMonacoEditor\n value={toolInvocation}\n readOnly={true}\n options={{\n lineNumbers: false,\n minimap: {enabled: false},\n scrollBeyondLastLine: false,\n wordWrap: 'on',\n }}\n />\n </div>\n )}\n </div>\n )}\n </MessageContainer>\n );\n};\n"]}