@sqlrooms/ai 0.24.15 → 0.24.17

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 CHANGED
@@ -444,17 +444,19 @@ export interface AiSliceOptions {
444
444
  * API key configuration for the AI slice
445
445
  */
446
446
  export type AiSliceApiConfig = {
447
+ defaultModel?: string;
448
+ } & ({
447
449
  baseUrl: string;
448
450
  getApiKey?: never;
449
451
  } | {
450
452
  getApiKey: (modelProvider: string) => string;
451
453
  baseUrl?: never;
452
- };
454
+ });
453
455
  /**
454
456
  * Complete configuration for creating an AI slice
455
457
  */
456
458
  export type CreateAiSliceConfig = AiSliceOptions & AiSliceApiConfig;
457
- export declare function createAiSlice<PC extends BaseRoomConfig & AiSliceConfig>(config: CreateAiSliceConfig): StateCreator<AiSliceState>;
459
+ export declare function createAiSlice<PC extends BaseRoomConfig & AiSliceConfig>(params: CreateAiSliceConfig): StateCreator<AiSliceState>;
458
460
  type RoomConfigWithAi = BaseRoomConfig & AiSliceConfig;
459
461
  type RoomShellSliceStateWithAi = RoomShellSliceState<RoomConfigWithAi> & AiSliceState;
460
462
  export declare function useStoreWithAi<T>(selector: (state: RoomShellSliceStateWithAi) => T): T;
@@ -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;AAEtB,OAAO,EAEL,qBAAqB,EAEtB,MAAM,WAAW,CAAC;AAEnB,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gCAkHT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,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,CAoT5B;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
@@ -29,8 +29,8 @@ export function createDefaultAiConfig(props) {
29
29
  },
30
30
  };
31
31
  }
32
- export function createAiSlice(config) {
33
- const { getApiKey, baseUrl, initialAnalysisPrompt = '', customTools = {}, getInstructions, numberOfRowsToShareWithLLM, } = config;
32
+ export function createAiSlice(params) {
33
+ const { getApiKey, baseUrl, initialAnalysisPrompt = '', customTools = {}, getInstructions, numberOfRowsToShareWithLLM, defaultModel = 'gpt-4o-mini', } = params;
34
34
  return createSlice((set, get, store) => {
35
35
  return {
36
36
  ai: {
@@ -204,7 +204,7 @@ export function createAiSlice(config) {
204
204
  await runAnalysis({
205
205
  tableSchemas: get().db.tables,
206
206
  modelProvider: currentSession.modelProvider || 'openai',
207
- model: currentSession.model || 'gpt-4o-mini',
207
+ model: currentSession.model || defaultModel,
208
208
  customModelName: currentSession.customModelName,
209
209
  apiKey: getApiKey?.(currentSession.modelProvider || 'openai') || '',
210
210
  baseUrl: currentSession.baseUrl || baseUrl,
@@ -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,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;AA+DD,MAAM,UAAU,aAAa,CAC3B,MAA2B;IAE3B,MAAM,EACJ,SAAS,EACT,OAAO,EACP,qBAAqB,GAAG,EAAE,EAC1B,WAAW,GAAG,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xE,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 =\n | {baseUrl: string; getApiKey?: never}\n | {getApiKey: (modelProvider: string) => string; baseUrl?: never};\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 config: CreateAiSliceConfig,\n): StateCreator<AiSliceState> {\n const {\n getApiKey,\n baseUrl,\n initialAnalysisPrompt = '',\n customTools = {},\n getInstructions,\n numberOfRowsToShareWithLLM,\n } = config;\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 || 'gpt-4o-mini',\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,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AAQ,EAAE,IAAI,CAAC,cAAc,CAAC,QAAQ;oCACtC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,IAAI;oCAC9B,KAAK,EAAE,IAAI,CAAC,cAAc,CAAC,KAAK;oCAChC,MAAM,EACJ,IAAI,CAAC,cAAc,CAAC,KAAK,KAAK,QAAQ;wCACpC,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM;wCAC5B,CAAC,CAAC,SAAS;iCAChB;gCACD,cAAc,EAAE,IAAI,CAAC,cAAc;gCACnC,WAAW,EAAE,IAAI,CAAC,WAAW;6BAC9B,CAAC;wBACJ,CAAC;6BAAM,CAAC;4BACN,sCAAsC;4BACtC,OAAO,IAAI,CAAC;wBACd,CAAC;oBACH,CAAC,CAAC;iBACH,CAAC;gBAEF,MAAM,CAAC,aAAa,GAAG,gBAAiC,CAAC;YAC3D,CAAC;YACD,IAAI,YAAY,EAAE,CAAC;gBACjB,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"]}
@@ -2,6 +2,8 @@ import { PropsWithChildren } from 'react';
2
2
  type QueryControlsProps = PropsWithChildren<{
3
3
  className?: string;
4
4
  placeholder?: string;
5
+ onRun?: () => void;
6
+ onCancel?: () => void;
5
7
  }>;
6
8
  export declare const QueryControls: React.FC<QueryControlsProps>;
7
9
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"QueryControls.d.ts","sourceRoot":"","sources":["../../src/components/QueryControls.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAC,iBAAiB,EAAiC,MAAM,OAAO,CAAC;AAGxE,KAAK,kBAAkB,GAAG,iBAAiB,CAAC;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC,CAAC;AAEH,eAAO,MAAM,aAAa,EAAE,KAAK,CAAC,EAAE,CAAC,kBAAkB,CA6FtD,CAAC"}
1
+ {"version":3,"file":"QueryControls.d.ts","sourceRoot":"","sources":["../../src/components/QueryControls.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAC,iBAAiB,EAAiC,MAAM,OAAO,CAAC;AAGxE,KAAK,kBAAkB,GAAG,iBAAiB,CAAC;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB,CAAC,CAAC;AAEH,eAAO,MAAM,aAAa,EAAE,KAAK,CAAC,EAAE,CAAC,kBAAkB,CA0GtD,CAAC"}
@@ -3,7 +3,7 @@ import { Button, cn, Textarea } from '@sqlrooms/ui';
3
3
  import { ArrowUpIcon, OctagonXIcon } from 'lucide-react';
4
4
  import { useCallback, useRef, useEffect } from 'react';
5
5
  import { useStoreWithAi } from '../AiSlice';
6
- export const QueryControls = ({ className, placeholder = 'What would you like to learn about the data?', children, }) => {
6
+ export const QueryControls = ({ className, placeholder = 'What would you like to learn about the data?', children, onRun, onCancel, }) => {
7
7
  const textareaRef = useRef(null);
8
8
  const isRunningAnalysis = useStoreWithAi((s) => s.ai.isRunningAnalysis);
9
9
  const runAnalysis = useStoreWithAi((s) => s.ai.startAnalysis);
@@ -40,6 +40,16 @@ export const QueryControls = ({ className, placeholder = 'What would you like to
40
40
  }
41
41
  }, [isRunningAnalysis, model, analysisPrompt, runAnalysis]);
42
42
  const canStart = Boolean(model && analysisPrompt.trim().length);
43
- return (_jsx("div", { className: cn('flex w-full flex-col items-center justify-center gap-4', className), children: _jsx("div", { className: "bg-muted/50 flex h-full w-full flex-row items-center gap-2 rounded-md border", children: _jsxs("div", { className: "flex w-full flex-col gap-1 overflow-hidden", children: [_jsx(Textarea, { ref: textareaRef, disabled: isRunningAnalysis, className: "min-h-[30px] resize-none border-none p-2 text-sm outline-none focus-visible:ring-0", autoResize: true, value: analysisPrompt, onChange: (e) => setAnalysisPrompt(e.target.value), onKeyDown: handleKeyDown, placeholder: placeholder, autoFocus: true }), _jsx("div", { className: "align-stretch flex w-full items-center gap-2 overflow-hidden", children: _jsxs("div", { className: "flex h-full w-full min-w-0 items-center gap-2 overflow-hidden", children: [_jsx("div", { className: "min-w-0 flex-1 overflow-hidden pl-2", children: _jsx("div", { className: "flex flex-nowrap items-center gap-2 overflow-x-auto py-1", children: children }) }), _jsx("div", { className: "ml-auto shrink-0 pr-2", children: _jsx(Button, { className: "h-8 w-8 rounded-full", variant: "default", size: "icon", onClick: isRunningAnalysis ? cancelAnalysis : runAnalysis, disabled: !canStart, children: isRunningAnalysis ? _jsx(OctagonXIcon, {}) : _jsx(ArrowUpIcon, {}) }) })] }) })] }) }) }));
43
+ const handleClickRunOrCancel = useCallback(() => {
44
+ if (isRunningAnalysis) {
45
+ cancelAnalysis();
46
+ onCancel?.();
47
+ }
48
+ else {
49
+ runAnalysis();
50
+ onRun?.();
51
+ }
52
+ }, [isRunningAnalysis, cancelAnalysis, runAnalysis]);
53
+ return (_jsx("div", { className: cn('flex w-full flex-col items-center justify-center gap-4', className), children: _jsx("div", { className: "bg-muted/50 flex h-full w-full flex-row items-center gap-2 rounded-md border", children: _jsxs("div", { className: "flex w-full flex-col gap-1 overflow-hidden", children: [_jsx(Textarea, { ref: textareaRef, disabled: isRunningAnalysis, className: "min-h-[30px] resize-none border-none p-2 text-sm outline-none focus-visible:ring-0", autoResize: true, value: analysisPrompt, onChange: (e) => setAnalysisPrompt(e.target.value), onKeyDown: handleKeyDown, placeholder: placeholder, autoFocus: true }), _jsx("div", { className: "align-stretch flex w-full items-center gap-2 overflow-hidden", children: _jsxs("div", { className: "flex h-full w-full min-w-0 items-center gap-2 overflow-hidden", children: [_jsx("div", { className: "min-w-0 flex-1 overflow-hidden pl-2", children: _jsx("div", { className: "flex flex-nowrap items-center gap-2 overflow-x-auto py-1", children: children }) }), _jsx("div", { className: "ml-auto shrink-0 pr-2", children: _jsx(Button, { className: "h-8 w-8 rounded-full", variant: "default", size: "icon", onClick: handleClickRunOrCancel, disabled: !canStart, children: isRunningAnalysis ? _jsx(OctagonXIcon, {}) : _jsx(ArrowUpIcon, {}) }) })] }) })] }) }) }));
44
54
  };
45
55
  //# sourceMappingURL=QueryControls.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"QueryControls.js","sourceRoot":"","sources":["../../src/components/QueryControls.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,MAAM,EAAE,EAAE,EAAW,QAAQ,EAAC,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAC,WAAW,EAAE,YAAY,EAAC,MAAM,cAAc,CAAC;AACvD,OAAO,EAAoB,WAAW,EAAE,MAAM,EAAE,SAAS,EAAC,MAAM,OAAO,CAAC;AACxE,OAAO,EAAC,cAAc,EAAC,MAAM,YAAY,CAAC;AAO1C,MAAM,CAAC,MAAM,aAAa,GAAiC,CAAC,EAC1D,SAAS,EACT,WAAW,GAAG,8CAA8C,EAC5D,QAAQ,GACT,EAAE,EAAE;IACH,MAAM,WAAW,GAAG,MAAM,CAAsB,IAAI,CAAC,CAAC;IACtD,MAAM,iBAAiB,GAAG,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC;IACxE,MAAM,WAAW,GAAG,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;IAC9D,MAAM,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC;IAClE,MAAM,cAAc,GAAG,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CA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con, OctagonXIcon} from 'lucide-react';\nimport {PropsWithChildren, useCallback, useRef, useEffect} from 'react';\nimport {useStoreWithAi} from '../AiSlice';\n\ntype QueryControlsProps = PropsWithChildren<{\n className?: string;\n placeholder?: string;\n}>;\n\nexport const QueryControls: React.FC<QueryControlsProps> = ({\n className,\n placeholder = 'What would you like to learn about the data?',\n children,\n}) => {\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const isRunningAnalysis = useStoreWithAi((s) => s.ai.isRunningAnalysis);\n const runAnalysis = useStoreWithAi((s) => s.ai.startAnalysis);\n const cancelAnalysis = useStoreWithAi((s) => s.ai.cancelAnalysis);\n const analysisPrompt = useStoreWithAi((s) => s.ai.analysisPrompt);\n const isDataAvailable = useStoreWithAi((s) => s.room.isDataAvailable);\n const setAnalysisPrompt = useStoreWithAi((s) => s.ai.setAnalysisPrompt);\n const currentSession = useStoreWithAi((s) => s.ai.getCurrentSession());\n const model = currentSession?.model;\n\n useEffect(() => {\n if (!isDataAvailable) return;\n // Focus the textarea when the component mounts\n // Using a small timeout ensures the data is loaded and\n // add timeout to prevent aria hidden warning caused by the\n // loading progress dialog being still open\n const timer = setTimeout(() => {\n if (textareaRef.current) {\n textareaRef.current.focus();\n }\n }, 500);\n\n return () => clearTimeout(timer);\n }, [isDataAvailable]);\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (\n e.key === 'Enter' &&\n !e.shiftKey &&\n !e.ctrlKey &&\n !e.altKey &&\n !e.metaKey\n ) {\n e.preventDefault();\n if (!isRunningAnalysis && model && analysisPrompt.trim().length) {\n runAnalysis();\n }\n }\n },\n [isRunningAnalysis, model, analysisPrompt, runAnalysis],\n );\n\n const canStart = Boolean(model && analysisPrompt.trim().length);\n return (\n <div\n className={cn(\n 'flex w-full flex-col items-center justify-center gap-4',\n className,\n )}\n >\n <div className=\"bg-muted/50 flex h-full w-full flex-row items-center gap-2 rounded-md border\">\n <div className=\"flex w-full flex-col gap-1 overflow-hidden\">\n <Textarea\n ref={textareaRef}\n disabled={isRunningAnalysis}\n className=\"min-h-[30px] resize-none border-none p-2 text-sm outline-none focus-visible:ring-0\"\n autoResize\n value={analysisPrompt}\n onChange={(e) => setAnalysisPrompt(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n autoFocus\n />\n <div className=\"align-stretch flex w-full items-center gap-2 overflow-hidden\">\n <div className=\"flex h-full w-full min-w-0 items-center gap-2 overflow-hidden\">\n <div className=\"min-w-0 flex-1 overflow-hidden pl-2\">\n <div className=\"flex flex-nowrap items-center gap-2 overflow-x-auto py-1\">\n {children}\n </div>\n </div>\n <div className=\"ml-auto shrink-0 pr-2\">\n <Button\n className=\"h-8 w-8 rounded-full\"\n variant=\"default\"\n size=\"icon\"\n onClick={isRunningAnalysis ? cancelAnalysis : runAnalysis}\n disabled={!canStart}\n >\n {isRunningAnalysis ? <OctagonXIcon /> : <ArrowUpIcon />}\n </Button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n};\n"]}
1
+ {"version":3,"file":"QueryControls.js","sourceRoot":"","sources":["../../src/components/QueryControls.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAC,MAAM,EAAE,EAAE,EAAW,QAAQ,EAAC,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAC,WAAW,EAAE,YAAY,EAAC,MAAM,cAAc,CAAC;AACvD,OAAO,EAAoB,WAAW,EAAE,MAAM,EAAE,SAAS,EAAC,MAAM,OAAO,CAAC;AACxE,OAAO,EAAC,cAAc,EAAC,MAAM,YAAY,CAAC;AAS1C,MAAM,CAAC,MAAM,aAAa,GAAiC,CAAC,EAC1D,SAAS,EACT,WAAW,GAAG,8CAA8C,EAC5D,QAAQ,EACR,KAAK,EACL,QAAQ,GACT,EAAE,EAAE;IACH,MAAM,WAAW,GAAG,MAAM,CAAsB,IAAI,CAAC,CAAC;IACtD,MAAM,iBAAiB,GAAG,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAA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AAa,EACxB,WAAW,EAAE,WAAW,EACxB,SAAS,SACT,EACF,cAAK,SAAS,EAAC,8DAA8D,YAC3E,eAAK,SAAS,EAAC,+DAA+D,aAC5E,cAAK,SAAS,EAAC,qCAAqC,YAClD,cAAK,SAAS,EAAC,0DAA0D,YACtE,QAAQ,GACL,GACF,EACN,cAAK,SAAS,EAAC,uBAAuB,YACpC,KAAC,MAAM,IACL,SAAS,EAAC,sBAAsB,EAChC,OAAO,EAAC,SAAS,EACjB,IAAI,EAAC,MAAM,EACX,OAAO,EAAE,sBAAsB,EAC/B,QAAQ,EAAE,CAAC,QAAQ,YAElB,iBAAiB,CAAC,CAAC,CAAC,KAAC,YAAY,KAAG,CAAC,CAAC,CAAC,KAAC,WAAW,KAAG,GAChD,GACL,IACF,GACF,IACF,GACF,GACF,CACP,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {Button, cn, Spinner, Textarea} from '@sqlrooms/ui';\nimport {ArrowUpIcon, OctagonXIcon} from 'lucide-react';\nimport {PropsWithChildren, useCallback, useRef, useEffect} from 'react';\nimport {useStoreWithAi} from '../AiSlice';\n\ntype QueryControlsProps = PropsWithChildren<{\n className?: string;\n placeholder?: string;\n onRun?: () => void;\n onCancel?: () => void;\n}>;\n\nexport const QueryControls: React.FC<QueryControlsProps> = ({\n className,\n placeholder = 'What would you like to learn about the data?',\n children,\n onRun,\n onCancel,\n}) => {\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const isRunningAnalysis = useStoreWithAi((s) => s.ai.isRunningAnalysis);\n const runAnalysis = useStoreWithAi((s) => s.ai.startAnalysis);\n const cancelAnalysis = useStoreWithAi((s) => s.ai.cancelAnalysis);\n const analysisPrompt = useStoreWithAi((s) => s.ai.analysisPrompt);\n const isDataAvailable = useStoreWithAi((s) => s.room.isDataAvailable);\n const setAnalysisPrompt = useStoreWithAi((s) => s.ai.setAnalysisPrompt);\n const currentSession = useStoreWithAi((s) => s.ai.getCurrentSession());\n const model = currentSession?.model;\n\n useEffect(() => {\n if (!isDataAvailable) return;\n // Focus the textarea when the component mounts\n // Using a small timeout ensures the data is loaded and\n // add timeout to prevent aria hidden warning caused by the\n // loading progress dialog being still open\n const timer = setTimeout(() => {\n if (textareaRef.current) {\n textareaRef.current.focus();\n }\n }, 500);\n\n return () => clearTimeout(timer);\n }, [isDataAvailable]);\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (\n e.key === 'Enter' &&\n !e.shiftKey &&\n !e.ctrlKey &&\n !e.altKey &&\n !e.metaKey\n ) {\n e.preventDefault();\n if (!isRunningAnalysis && model && analysisPrompt.trim().length) {\n runAnalysis();\n }\n }\n },\n [isRunningAnalysis, model, analysisPrompt, runAnalysis],\n );\n\n const canStart = Boolean(model && analysisPrompt.trim().length);\n\n const handleClickRunOrCancel = useCallback(() => {\n if (isRunningAnalysis) {\n cancelAnalysis();\n onCancel?.();\n } else {\n runAnalysis();\n onRun?.();\n }\n }, [isRunningAnalysis, cancelAnalysis, runAnalysis]);\n\n return (\n <div\n className={cn(\n 'flex w-full flex-col items-center justify-center gap-4',\n className,\n )}\n >\n <div className=\"bg-muted/50 flex h-full w-full flex-row items-center gap-2 rounded-md border\">\n <div className=\"flex w-full flex-col gap-1 overflow-hidden\">\n <Textarea\n ref={textareaRef}\n disabled={isRunningAnalysis}\n className=\"min-h-[30px] resize-none border-none p-2 text-sm outline-none focus-visible:ring-0\"\n autoResize\n value={analysisPrompt}\n onChange={(e) => setAnalysisPrompt(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n autoFocus\n />\n <div className=\"align-stretch flex w-full items-center gap-2 overflow-hidden\">\n <div className=\"flex h-full w-full min-w-0 items-center gap-2 overflow-hidden\">\n <div className=\"min-w-0 flex-1 overflow-hidden pl-2\">\n <div className=\"flex flex-nowrap items-center gap-2 overflow-x-auto py-1\">\n {children}\n </div>\n </div>\n <div className=\"ml-auto shrink-0 pr-2\">\n <Button\n className=\"h-8 w-8 rounded-full\"\n variant=\"default\"\n size=\"icon\"\n onClick={handleClickRunOrCancel}\n disabled={!canStart}\n >\n {isRunningAnalysis ? <OctagonXIcon /> : <ArrowUpIcon />}\n </Button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n};\n"]}
@@ -26,7 +26,7 @@ export const ToolResult = ({ toolInvocation, additionalData, isCompleted, errorM
26
26
  additionalData,
27
27
  isCompleted,
28
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: {
29
- lineNumbers: false,
29
+ lineNumbers: 'off',
30
30
  minimap: { enabled: false },
31
31
  scrollBeyondLastLine: false,
32
32
  wordWrap: 'on',
@@ -1 +1 @@
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,2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,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,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"]}
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,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,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,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: 'off',\n minimap: {enabled: false},\n scrollBeyondLastLine: false,\n wordWrap: 'on',\n }}\n />\n </div>\n )}\n </div>\n )}\n </MessageContainer>\n );\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sqlrooms/ai",
3
- "version": "0.24.15",
3
+ "version": "0.24.17",
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.15",
26
- "@sqlrooms/duckdb": "0.24.15",
27
- "@sqlrooms/monaco-editor": "0.24.15",
28
- "@sqlrooms/room-config": "0.24.15",
29
- "@sqlrooms/room-shell": "0.24.15",
30
- "@sqlrooms/ui": "0.24.15",
31
- "@sqlrooms/utils": "0.24.15",
25
+ "@sqlrooms/data-table": "0.24.17",
26
+ "@sqlrooms/duckdb": "0.24.17",
27
+ "@sqlrooms/monaco-editor": "0.24.17",
28
+ "@sqlrooms/room-config": "0.24.17",
29
+ "@sqlrooms/room-shell": "0.24.17",
30
+ "@sqlrooms/ui": "0.24.17",
31
+ "@sqlrooms/utils": "0.24.17",
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": "9388ad51033a365069bad9a14df24a0688b6a592"
51
+ "gitHead": "31b706c4687780cefa92bc9e715f2839dbe4ee49"
52
52
  }