Skip to Content
Anuma SDKReactHooksuseChatStorage

useChatStorage

useChatStorage(options: object): UseChatStorageResult

Defined in: src/react/useChatStorage.ts:1091 

A React hook that wraps useChat and persists messages and conversations to WatermelonDB as they are sent and received.

Parameters

ParameterTypeDescription

options

object

Configuration options

options.activeToolSets?

string[]

Tool set names that should expand unconditionally for this request, bypassing the anchor-similarity check. Use when conversation state implies a set should be present regardless of how the prompt is phrased — e.g., pass ["slides"] when the conversation already contains a slide deck artifact, so short follow-up prompts (“add a thank you slide”, “make it bigger”) still get the full slide toolkit.

Read via a ref so updates are visible to in-flight sendMessage calls without rebuilding the callback.

Names must match a set’s name from BUILT_IN_TOOL_SETS or extraToolSets. Unknown names are ignored.

options.apiType?

ApiType

Which API endpoint to use. Default: “responses”

  • “responses”: OpenAI Responses API (supports thinking, reasoning, conversations)
  • “completions”: OpenAI Chat Completions API (wider model compatibility)

options.autoCreateConversation?

boolean

Automatically create a new conversation if none is set (default: true)

options.autoEmbedMessages?

boolean

Automatically generate embeddings for messages after saving. Enables semantic search over past conversations via searchMessages().

Default

true

options.autoFlushOnKeyAvailable?

boolean

Automatically flush queued operations when the encryption key becomes available. Requires enableQueue to be true.

Default

true

options.background?

boolean

Keep a resumable generation running when the request fails or the hook unmounts. Portal stores the answer of a turn that finishes with no client attached.

options.baseUrl?

string

Base URL for the chat API endpoint

options.chatBackend?

ChatBackendFactory

Builds the chat storage backend (default: this database); keep it stable across renders, since a new factory rebuilds the backend and every callback.

options.conversationId?

string

ID of an existing conversation to load and continue

options.database

Database

WatermelonDB database instance for storing conversations and messages

options.defaultConversationTitle?

string

Title for auto-created conversations (default: “New conversation”)

options.detachedTools?

ToolConfig[]

Device tools that can finish a turn the portal completed while the device was away: their executors run when that answer is stored. Pass the display tools and the memory save tool.

options.embeddedWalletSigner?

EmbeddedWalletSignerFn

Function for silent signing with Privy embedded wallets. When provided, enables automatic encryption key derivation without user confirmation modals.

options.embeddingModel?

string

Embedding model to use when autoEmbedMessages is enabled.

Default

DEFAULT_API_EMBEDDING_MODEL

options.enableQueue?

boolean

Enable the in-memory write queue for operations when encryption key isn’t yet available. When enabled, operations are held in memory and flushed to encrypted storage once the key becomes available.

Default

true

options.extraToolSets?

ToolSet[]

Additional tool sets to apply on top of the built-in ones (app-generation, slides, github). When any anchor tool in a custom set is selected by semantic matching, all members of that set are included automatically.

Treated as static config — set once at hook setup. Changing it across renders does not affect in-flight sendMessage calls; use activeToolSets for dynamic, conversation-state-driven overrides.

options.fileProcessingOptions?

{ keepOriginalFiles?: boolean; maxFileSizeBytes?: number; onError?: (fileName: string, error: Error) => void; onProgress?: (current: number, total: number, fileName: string) => void; }

Options for file preprocessing behavior

options.fileProcessingOptions.keepOriginalFiles?

boolean

Whether to keep original file attachments (default: true)

options.fileProcessingOptions.maxFileSizeBytes?

number

Max file size to process in bytes (default: 10MB)

options.fileProcessingOptions.onError?

(fileName: string, error: Error) => void

Callback for errors (non-fatal)

options.fileProcessingOptions.onProgress?

(current: number, total: number, fileName: string) => void

Callback for progress updates

options.fileProcessors?

FileProcessor[] | null

File preprocessors to use for automatic text extraction.

  • undefined (default): Use all built-in processors (PDF, Excel, Word)
  • null or []: Disable preprocessing
  • FileProcessor[]: Use specific processors

options.foldToolResultsInHistory?

boolean

Fold persisted [Tool Execution Results] rows onto the assistant turn that produced them when replaying stored history, instead of dropping them.

Defaults to false, and that default is deliberate. Folding is the better behaviour — it is what lets a follow-up about a tool’s output work after a reload — but it moves the payload from a role: "user" row onto an assistant row. Any consumer that scrubs these rows by checking role === "user" plus the content prefix (which is how both apps did it before this option existed) stops catching them the moment folding turns on, and starts replaying whatever the row held. Opting in is therefore a statement that the caller has checked its own filters and set toolResultsHistoryExclude for any payload that must not reach the model.

With it off, rows are dropped from the replayed history rather than sent verbatim. Verbatim would put two consecutive user turns on the wire, and the model answers the previous turn instead of the new prompt.

options.getToken?

() => Promise<string | null>

Function to retrieve the auth token for API requests

options.getWalletAddress?

() => Promise<string | null>

Async function that returns the wallet address when available. Used for polling during Privy embedded wallet initialization. When the wallet isn’t ready yet, should return null.

options.hooks?

RunHooks | RunHooks[]

Run lifecycle hooks for telemetry and tracing, for example from createMetricsHooks

options.inbox?

VaultInbox

The vault inbox that receives answers finished while no client was attached.

options.mcpR2Domain?

string

R2 domain for identifying MCP-generated image URLs. When set, enables OPFS caching of generated images. Defaults to the hardcoded MCP_R2_DOMAIN from clientConfig.

options.memoryStore?

MemoryStore | null

Route memory operations through this store; null disables memory access while undefined uses the local vault. Folders are unsupported. With piiRedaction on, build the store with embeddingOptions.maskInput or its memory calls throw.

options.minContentLength?

number

Minimum content length required to generate embeddings. Messages shorter than this are skipped as they provide limited semantic value.

Default

10

options.nerDetector?

NerDetector

Optional on-device NER detector for unstructured PII (names, locations, organizations) that regex can’t catch. When supplied AND piiRedaction is active, the conversation redactor merges its spans into the outbound message redaction (chat-send path only). Supply e.g. createTransformersNerDetector() from @anuma/sdk/pii/transformers on web. Ignored when piiRedaction is off. See NerDetector.

options.onData?

(chunk: string) => void

Callback invoked with each streamed response chunk

options.onError?

(error: Error) => void

Callback invoked when an error occurs during the request

options.onFinish?

(response: LlmapiResponseResponse) => void

Callback invoked when the response completes successfully

options.onPiiRedacted?

(matches: PiiMatch[]) => void

Called with the PII matches found whenever outbound messages are redacted. Only fired when piiRedaction is active and at least one match was found.

options.onServerToolCall?

(toolCall: ServerToolCallEvent) => void

Callback invoked when a server-side tool (MCP) is called during streaming. Use this to show activity indicators like “Searching…” in the UI.

options.onStreamMeta?

(meta: StreamResumeHandle & object) => void

Stream handle for each HTTP round, including client-tool continuations.

options.onThinking?

(chunk: string) => void

Callback invoked when thinking/reasoning content is received (from <think> tags or API reasoning)

options.onToolCallArgumentsDelta?

(event: ToolCallArgumentsDeltaEvent) => void

Called with partial tool call arguments as they stream in. Use for live preview of artifacts (HTML, slides) being generated.

options.onToolSelection?

(info: object) => void

Called once per sendMessage with the user prompt and the FINAL tool selection — after semantic filtering, tool-set expansion, and exclusions; exactly the tools the request carries. Intended for debug logging and selection QA (e.g. a prefixed plain-text console line you can filter on). Errors thrown by the callback are swallowed.

options.piiRedaction?

boolean | PiiRedactor

Enable best-effort, client-side PII obfuscation (NOT a compliance guarantee). Outbound message text is scanned for personally identifiable information and replaced with tagged placeholders before reaching the LLM provider; responses are de-anonymized automatically. Embedding inputs and the summarization prompt are redacted too. Regex-based detection does not cover names, non-text content, or tool-call arguments.

  • true: one redactor is shared per conversation
  • PiiRedactor instance: bring your own (tune via constructor options)

options.preProcessors?

PromptPreProcessor[]

Pre-processors run after the last user message is received but before the first LLM request. Each receives the prompt text and a shared embedding (computed once per request) and may return messages to enrich the conversation. Forwarded to the underlying useChat hook. See createWebSearchPreProcessor, createCryptoPricePreProcessor, createStockPricePreProcessor, createWeatherPreProcessor, or write a custom one matching PromptPreProcessor.

options.resumable?

boolean

Opt into the portal stream buffer for every generated round.

options.serverTools?

{ cache?: ToolsCacheBackend; cacheExpirationMs?: number; deferLoading?: DeferLoadingConfig; }

Configuration for the server tools cache and tool selection.

options.serverTools.cache?

ToolsCacheBackend

Cache backend; defaults to localStorage with a memory fallback on platforms without localStorage.

options.serverTools.cacheExpirationMs?

number

Cache expiration time in milliseconds (default: 86400000 = 1 day)

options.serverTools.deferLoading?

DeferLoadingConfig

Opt-in defer-loading (Phase 3). OFF by default → tools are sent exactly as today. When enabled, the full server catalog is emitted every turn in a deterministic, byte-stable order ([tool-search] → [hot] → [deferred, name-sorted]) with defer_loading:true on non-hot tools and an Anthropic tool-search tool prepended, so the leading tools prefix stays cacheable. See DeferLoadingConfig.

options.signMessage?

SignMessageFn

Function to sign a message for encryption key derivation. Typically from Privy’s useSignMessage hook. Required together with walletAddress for field-level encryption.

options.smoothing?

boolean | StreamSmoothingConfig

Output pacing forwarded to useChat. Set false when the UI batches streamed updates.

options.toolResultsHistoryExclude?

string[]

Tool names whose persisted results must never be replayed to the model.

A turn’s auto-executed tool results are stored as a synthetic [Tool Execution Results] row and, on a replayed send, folded back onto the assistant turn they belong to — that is what lets a follow-up question about a tool’s output work after a reload. Name a tool here when its payload exists for the RENDERER rather than the model: a display card can carry data the model was deliberately never given (People Nearby’s card holds third parties’ snapped coordinates, which the search result strips), and replaying it would hand that data straight back.

Hook-level rather than per-send on purpose: an exclusion that has to be remembered at every call site is one bad send away from leaking.

options.walletAddress?

string

Wallet address for encrypted file storage and field-level encryption. When provided with signMessage, all sensitive message content, conversation titles, and media metadata are encrypted at rest using AES-GCM with wallet-derived keys.

Requires:

  • OPFS browser support (for file storage)
  • signMessage function (for encryption key derivation)

When not provided, data is stored in plaintext (backwards compatible).

Returns

UseChatStorageResult

Chat state and methods plus storage operations

Example

import { Database } from '@nozbe/watermelondb'; import { useChatStorage } from '@anuma/sdk/react'; function ChatComponent({ database }: { database: Database }) { const { isLoading, sendMessage } = useChatStorage({ database, getToken: async () => getAuthToken(), onData: (chunk) => setResponse((prev) => prev + chunk), }); const handleSend = async () => { const result = await sendMessage({ messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello, how are you?' }] }], model: 'fireworks/accounts/fireworks/models/kimi-k2p5', includeHistory: true, }); if (result.error) console.error(result.error); }; return <button onClick={handleSend} disabled={isLoading}>Send</button>; }
Last updated on