Skip to Content
Anuma SDKExpoHooksuseChatStorage

useChatStorage

useChatStorage(options: object): UseChatStorageResult

Defined in: src/expo/useChatStorage.ts:664 

A React hook that wraps useChat with automatic message persistence using WatermelonDB.

Expo/React Native version - This is a lightweight version that only supports API-based chat completions. Local chat and client-side tools are not available.

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 ["documents"] when the conversation already contains a generated document, so short follow-up prompts (“make the background red”) still get the full document 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

Auto-flush queued operations when key becomes available.

Default

true

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.

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.

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 to poll for wallet address during Privy initialization.

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.onCancelResult?

(result: object) => void

Observability for the fire-and-forget cancel POST that stop() issues for a resumable stream. Forwarded to the underlying useChat. The stop-without-cancel billing risk must be visible: once the capability header ships, the portal no longer treats a dropped socket as cancellation, so a stop() whose cancel POST silently fails bills the full generation.

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: object) => void

Observe the stream metadata the portal issues at HEADERS_RECEIVED, once per round. Forwarded to the underlying useChat. The enriched payload carries the RESOLVED apiType and model alongside inferenceId, so a consumer can persist a rebuildable StreamResumeHandle for a cold-launch resume registry (mobile PR5). Additive — never alters the internal resume-handle capture.

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

Observability hook fired once per send with the tools actually selected for the turn (after server + client filtering). Never throws into the send path. Mirrors react’s onToolSelection.

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 resumable streaming. When true, sendMessage sends the resumable capability header, a stable assistantUniqueId is allocated for every turn (so the partial and the resumed completion reconcile onto ONE row), and detach() / resumeStream() become usable. Off by default.

Default

false

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.

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 field-level encryption. When provided with signMessage, all sensitive content is encrypted at rest.

Returns

UseChatStorageResult

An object containing chat state, methods, and storage operations

Example

import { Database } from '@nozbe/watermelondb'; import { useChatStorage } from '@anuma/sdk/expo'; function ChatScreen({ database }: { database: Database }) { const { isLoading, sendMessage, conversationId, getMessages, } = useChatStorage({ database, getToken: async () => getAuthToken(), onData: (chunk) => setResponse((prev) => prev + chunk), }); const handleSend = async () => { const result = await sendMessage({ content: 'Hello!', model: 'fireworks/accounts/fireworks/models/kimi-k2p5', includeHistory: true, }); }; return ( <View> <Button onPress={handleSend} disabled={isLoading} title="Send" /> </View> ); }
Last updated on