Skip to main content

useAgent hook (headless mode)

Use the hook directly if you build your own UI:

import { useAgent } from "stacgis-ai-react";

const {
messages, // Message[] — incl. per-message ReAct `steps`
isLoading,
error,
currentSteps, // AgentStep[] — live steps of the running loop
pendingApproval, // ApprovalRequest | null
sendMessage,
cancelCurrentRun,
clearHistory,
resolveApproval, // (id, approved, reason?) => void
isQueued, // true while the server reports it is at capacity (503)
queueInfo, // QueueInfo | null — server capacity details
cancelQueue, // cancel the queue wait and drop the pending message
restoreMessages, // replace the current conversation (chat history panel)
} = useAgent({ apiBaseUrl: "http://localhost:8000/api/v1" });

sendMessage(text, options?)

interface SendMessageOptions {
mode?: "stream" | "chat"; // default "stream"
lat?: number; // optional map viewport centre
lng?: number;
selectedFeature?: Record<string, any>;
geometry?: GeoFeature | null; // GeoJSON Feature drawn by the user
approvalTimeoutS?: number; // HitL auto-reject, default 120
}
  • streamPOST {apiBaseUrl}/agent/stream (multipart/form-data), consumes the SSE stream and updates currentSteps / messages live.
  • chatPOST {apiBaseUrl}/agent/chat (JSON), single final response.

cancelCurrentRun() aborts an in-flight run (AbortController); the assistant message is annotated with a cancellation step.

Server capacity queue (HTTP 503)

If the server answers 503 (agent at capacity), the hook queues the request and retries automatically instead of failing:

  1. The empty assistant placeholder is dropped and the user message stays visible.

  2. isQueued becomes true and queueInfo carries the server's capacity payload:

    interface QueueInfo {
    active_count: number; // slots currently in use
    max_slots: number; // total agent slots
    available: number; // free slots
    retry_after: number; // suggested retry delay (seconds)
    }
  3. After retry_after seconds the hook re-sends the exact same message (retries up to 8 times; after that it surfaces "The agent is at capacity. Please try again in a few seconds.").

  4. AgentChat renders the ChatQueueOverlay (usage ring, retry countdown, Cancel button) while this is happening.

With a custom UI you can drive your own overlay off isQueued / queueInfo, or call cancelQueue() to drop the pending message.

restoreMessages(restored) replaces the current conversation with previously saved Message[] (it first cancels any in-flight run or queue wait) — this is how the chat-history panel reloads older sessions.

Human-in-the-loop

  • pendingApproval is set when the agent calls an approval-gated tool.
  • Resolve it with resolveApproval(id, approved, reason?), or let AgentChat render the ApprovalModal with an auto-reject countdown and an optional rejection reason.

Sessions, voice & TTS hooks

useChatSessions

Persist and manage chat sessions in localStorage (no backend needed).

import { useChatSessions } from "stacgis-ai-react";

const { sessions, upsertSession, getMessages, renameSession, deleteSession, clearAll } =
useChatSessions({
storageKey: "stacgis-ai-chat-sessions", // default
enabled: true, // disable entirely if false
});
MemberDescription
sessions: ChatSession[]Saved sessions, sorted by last update (max 50 kept)
upsertSession(id, title, messages)Create or update a session and persist its messages
getMessages(id): Message[] | nullLoad a session's messages (null when not found)
renameSession(id, title)Rename a session
deleteSession(id)Delete a session and its stored messages
clearAll()Remove every stored session

ChatSession is { id, title, createdAt, updatedAt, messageCount }. AgentChat wires all of this up for you when enableHistory is true.

useVoiceInput

Microphone dictation built on the Web Speech API (SpeechRecognition). Streams interim results and emits final transcripts, auto-stopping after a silence timeout.

import { useVoiceInput } from "stacgis-ai-react";

const voice = useVoiceInput({
onFinal: (text) => appendToInput(text), // finalized transcript fragment
onInterim: (text) => setInterim(text), // in-progress transcript
silenceTimeoutMs: 4000, // stop after 4 s of silence (default)
lang: "en-US", // BCP-47 tag (default)
});

// voice.isListening / voice.isSupported / voice.start() / voice.stop() / voice.toggle()

The mic button in AgentChat is hidden automatically when voice.isSupported is false (unsupported browser).

useTextToSpeech

Speak text with the Web Speech API. Markdown is stripped before speaking, so the audio is clean.

import { useTextToSpeech } from "stacgis-ai-react";

const { isSpeaking, isSupported, speakingMessageId, speak, stop } =
useTextToSpeech({ rate: 1.05, pitch: 1, volume: 1 });

speak(message.content, message.id); // start (auto-cancels the previous utterance)
stop(); // cancel

AgentChat exposes the per-message read aloud action built on this hook, and autoSpeak reuses it to read the final answer when a run completes.