@sqlrooms/ai-core
Core AI slice, chat UI primitives, and tool-streaming utilities for SQLRooms.
Use @sqlrooms/ai-core when you want lower-level control over AI state/transport/UI. For most apps, use the higher-level @sqlrooms/ai package.
Installation
npm install @sqlrooms/ai-core @sqlrooms/room-store @sqlrooms/ui zod ai@sqlrooms/ui is a peer dependency used for Chat UI rendering/styling. You typically import Chat components from @sqlrooms/ai-core, but @sqlrooms/ui must be installed for the visual components to work.
Store setup (core mode)
createAiSlice requires:
tools– an AI SDKToolSet(created via thetool()helper fromai)getInstructionstoolRenderers(optional) – aToolRendererRegistrymapping tool names to React componentsgetAvailableModels(optional) – returns selectable{provider, value}pairs so new sessions can fall back to the first available model when the configured default is missing
Upgrading from 0.28.x? See the 0.29.0 migration guide for the full list of breaking changes:
parameters→inputSchema,component→toolRenderers,setSessionToolAdditionalDataremoved.
import {
createAiSlice,
type AiSliceState,
type ToolRendererRegistry,
} from '@sqlrooms/ai-core';
import {
BaseRoomStoreState,
createBaseRoomSlice,
createRoomStore,
} from '@sqlrooms/room-store';
import {tool} from 'ai';
import {z} from 'zod';
const EchoResult = ({
output,
}: {
output: {success: boolean; text: string} | undefined;
}) => <div>{output?.text}</div>;
type State = BaseRoomStoreState & AiSliceState;
export const {roomStore, useRoomStore} = createRoomStore<State>(
(set, get, store) => ({
...createBaseRoomSlice()(set, get, store),
...createAiSlice({
getInstructions: () => 'You are a helpful analytics assistant.',
tools: {
echo: tool({
description: 'Echo text back',
inputSchema: z.object({text: z.string()}),
execute: async ({text}) => ({success: true, text: `Echo: ${text}`}),
}),
},
toolRenderers: {
echo: EchoResult,
},
})(set, get, store),
}),
);Chat UI
import {Chat} from '@sqlrooms/ai-core';
export function AiPanel() {
return (
<Chat>
<Chat.Sessions />
<Chat.Messages />
<Chat.PromptSuggestions>
<Chat.PromptSuggestions.Item text="What trends should I investigate first?" />
</Chat.PromptSuggestions>
<Chat.Composer placeholder="Ask a question" />
</Chat>
);
}Local Agent Chat
Use Chat.LocalAgentRoot when a transient surface should be driven by a pre-constructed ToolLoopAgent instead of the session-backed AI slice. The message and composer components stay under the same Chat compound API.
<Chat.LocalAgentRoot
agent={agent}
initialSuggestions={['Get started', 'Show me an example']}
onMessagesChange={(msgs) => console.log(msgs)}
>
<Chat.Messages />
<Chat.PromptSuggestions />
<Chat.Composer placeholder="Ask anything..." />
</Chat.LocalAgentRoot>Chat search
Chat renders a ChatSearchProvider and exposes Chat.Search, an in-conversation find bar that highlights matches in the current session's messages.
For building search UIs outside the chat (e.g. a session list that searches across all sessions), the underlying matching primitives are exported and can be used without the provider:
normalizeChatSearchQuery(query)— trims + lower-cases a query (the casing rule the search uses).findChatSearchMatches(blocks, query)— returns positional matches (ChatSearchMatch[]) for a list ofChatSearchBlocks. Useful for highlighting matched substrings consistently withChat.Search.markdownToPlainText(markdown)— extracts plain text from markdown so message content can be made searchable.
import {findChatSearchMatches, type ChatSearchBlock} from '@sqlrooms/ai-core';
const blocks: ChatSearchBlock[] = [{id: 'title', resultId: 'title', text: title}];
const matches = findChatSearchMatches(blocks, query);Useful exports
- Slice/hooks:
createAiSlice,useStoreWithAi,AiSliceState - Chat UI:
Chat,ModelSelector,QueryControls,PromptSuggestions - Legacy/compat components:
AnalysisResultsContainer,AnalysisResult,ErrorMessage - Types:
ToolRendererProps,ToolRenderer,ToolRendererRegistry,StoredTool,StoredToolSet - Tool/agent utilities:
cleanupPendingAnalysisResultsfixIncompleteToolCallsstreamSubAgent
Related packages
@sqlrooms/ai(recommended high-level integration)@sqlrooms/ai-settings(provider/model settings slice + UI)@sqlrooms/ai-config(config schemas and migrations)
Classes
Interfaces
Type Aliases
- AiSliceConfig
- AiRunContextItem
- AiRunContext
- AiSliceState
- LocalAgentChatRootProps
- ChatSearchBlock
- ChatSearchMatch
- ErrorMessageComponentProps
- ToolStructureBehavior
- ToolDisplayBehavior
- ToolRenderBehavior
- HoistableToolCall
- ContextSelectorItem
- ContextSelectorRootProps
- SessionType
- AgentToolCall
- AgentToolCallAdditionalData
- AgentStreamOutput
- PendingSubAgentApproval
- AgentProgressSnapshot
- ToolTimingEntry
- MessageTokenUsage
- AssistantMessageMetadata
- StoredToolSet
- AddToolOutput
- AddToolApprovalResponse
- AiToolExecutionContext
- ToolRendererProps
- ToolRenderer
- ToolRendererRegistry
- ToolRenderers
Variables
- AiSliceConfig
- AiRunContextItemSchema
- AiRunContextSchema
- ActivityBox
- AiThinkingDots
- AnalysisResult
- AnalysisResultsContainer
- Chat
- ContextUsageIndicator
- ExpandableContent
- ShowToolCallDetailsProvider
- OrchestratorToolLogLine
- FlatAgentRenderer
- HoistedRenderersProvider
- ModelSelector
- PromptSuggestions
- QueryControls
- SessionControls
- ToolCallInfo
- ContextSelector
- CHAT_CONTEXT_SELECTOR_SLOT
- DeleteSessionDialog
- SessionActions
- SessionDropdown
- SessionTitle
Functions
- createDefaultAiConfig
- getAiRunContextItems
- getAiRunContextPrimaryItem
- setAiRunContextPrimaryItem
- createAiSlice
- useStoreWithAi
- updateAgentToolCallData
- formatAbortSnapshot
- streamSubAgent
- markdownToPlainText
- normalizeChatSearchQuery
- findChatSearchMatches
- ErrorMessage
- useHoistedRenderers
- collectHoistableRenderers
- toggleContextSelectorItem
- promoteContextSelectorItem
- reorderContextSelectorItems
- ToolErrorMessage
- useElapsedTime
- useScrollToBottom
- useSessionChat
- extractModelsFromSettings
- cleanupPendingAnalysisResults
- shouldEndAnalysis
- fixIncompleteToolCalls
