Skip to Content
Baseera Docs

Hooks

Every hook @baseera/react exports, with its signature and an example.

Every hook runs inside BaseeraProvider. Each section shows what the hook returns and a short example.

useBaseeraChat

function useBaseeraChat(): BaseeraChat;

Returns the conversation and the actions on it.

Prop

Type

"use client";
import { useBaseeraChat } from "@baseera/react";

export function Chat() {
  const { messages, status, error, send, stop, pendingApprovals, approve, reject } = useBaseeraChat();
  const busy = status !== "idle" && status !== "error";

  return (
    <div>
      {messages.map((m) =>
        m.role === "user" ? (
          <p key={m.id}>{m.text}</p>
        ) : (
          <div key={m.id}>
            {m.toolCalls.map((c) => c.status === "running" && <em key={c.callId}>Checking {c.name}</em>)}
            <p>{m.text}</p>
          </div>
        ),
      )}

      {pendingApprovals.map((a) => (
        <div key={a.callId} role="group" aria-label="Approval needed">
          <p>{a.description}</p>
          <button onClick={() => approve(a.callId)}>Approve</button>
          <button onClick={() => reject(a.callId, "Not now")}>Reject</button>
        </div>
      ))}

      {status === "error" && <p role="alert">Something went wrong ({error?.code}).</p>}
      {busy && <button onClick={stop}>Stop</button>}

      <form
        onSubmit={(e) => {
          e.preventDefault();
          const input = e.currentTarget.elements.namedItem("q") as HTMLInputElement;
          void send(input.value);
          input.value = "";
        }}
      >
        <input name="q" />
        <button disabled={busy}>Send</button>
      </form>
    </div>
  );
}

A tool call's status is one of pending, awaiting_approval, running, done, failed, rejected or timed_out.

useBaseeraTool

function useBaseeraTool<S extends z.ZodObject>(options: BaseeraToolOptions<S>): void;

Registers a tool the model can call, while the component is mounted. See Tools and approvals for the full options and rules.

useBaseeraTool({
  name: "getInvoice",
  description: "Get an invoice by its number",
  kind: "read",
  input: z.object({ number: z.string() }),
  run: ({ number }) => api.getInvoice(number),
});

useBaseeraToolDefinition

function useBaseeraToolDefinition(tool: RegisteredTool): void;

The primitive under useBaseeraTool, for tools that do not use Zod. It takes a RegisteredTool ({ spec, run, validate?, describe?, undo?, inlineApproval? }) where spec.inputSchema is JSON Schema. It re-registers only when spec.name changes.

useBaseeraToolDefinition({
  spec: {
    name: "lookupOrder",
    description: "Look up an order",
    kind: "read",
    inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
  },
  run: (input) => api.getOrder((input as { id: string }).id),
});

useBaseeraContext

function useBaseeraContext(input: BaseeraContextInput): void;

Tells the assistant where the user is, so "mark this paid" means the invoice on screen. BaseeraContextInput is { page?: string; entity?: { type: string; ref: string; title?: string }; data?: Record<string, unknown> }.

function InvoicePage({ invoice }: { invoice: Invoice }) {
  useBaseeraContext({
    page: `/invoices/${invoice.id}`,
    entity: { type: "invoice", ref: invoice.id, title: invoice.number },
    data: { status: invoice.status, total: invoice.total },
  });
  return <InvoiceView invoice={invoice} />;
}
  • The context applies while the component is mounted and is removed on unmount. Inline objects are fine: values are compared by content.
  • Nested calls merge, outer first. The innermost page wins, the innermost entity wins as a whole, and data is shallow-merged with inner keys winning.
  • page, entity.type, entity.ref and entity.title are cut to 200 characters. data is at most 4,096 bytes serialized. If it is larger it is left out of that turn.
  • Everything in data goes to the model provider. Send only what the agent needs, and never secrets.

useBaseeraApprovals

function useBaseeraApprovals(): BaseeraApprovals;

For your own approval interface.

Prop

Type

const { pending, approve, reject, approveAll, rejectAll } = useBaseeraApprovals();

useBaseeraFeedback

function useBaseeraFeedback(): BaseeraFeedback;

For your own thumbs up and down. BaseeraSurface already has thumbs.

const { messages } = useBaseeraChat();
const { rate, ratings } = useBaseeraFeedback();

const recorded = await rate(message.id, "down", "The total is wrong"); // true when recorded
// ratings[message.id] is "up" or "down" once recorded in this page session
  • rate(messageId, rating, reason?) resolves true when the rating was recorded and false when it was not: no session yet, the message is not a finished assistant reply, you hit the rate limit (30 a minute per user), or the network failed.
  • It needs a verified user token. A dev-mode anonymous session cannot rate.
  • One rating per turn: rating again replaces it.
  • reason is for "down" only and is cut to FEEDBACK_REASON_MAX (500) characters. It is shown to your team as untrusted text and never given to the model.

useBaseeraKnowledgeUpload

function useBaseeraKnowledgeUpload(options: BaseeraKnowledgeUploadOptions): BaseeraKnowledgeUpload;

The logic behind tenant uploads: the tenant's own documents with their status, uploading and deleting. The tenant, knowledge base and user are not arguments; they are in the token your server signs. See Pushing knowledge.

const { sources, uploads, upload, remove, refresh, disabled, error, loading } = useBaseeraKnowledgeUpload({
  getUploadToken: () => fetch("/api/baseera/upload-token", { method: "POST" }).then((r) => r.json()).then((b) => b.token),
  pollMs: 3000,
});

upload(files) reserves a signed upload, sends the bytes straight to storage and confirms. remove(sourceId) resolves true when deleted. disabled is true when the agent has tenant uploads off. error is a code such as quota, rate_limited or token. The ready-made component is BaseeraKnowledgeUpload in @baseera/ui/connected.

useBaseeraImmersive

function useBaseeraImmersive(def: BaseeraImmersiveInput): void;

Starts immersive mode on the record the screen shows, and ends it on unmount. While it is on, the assistant sees the record's fields and the results of your checks with every turn, and your UI can block a finish button while something serious is open. def is { entity, fields, checks, aiChecks?, finish }.

useBaseeraImmersive({
  entity: { type: "invoice", ref: invoice.id, title: invoice.number },
  fields: [
    { name: "taxId", label: { ar: "الرقم الضريبي", en: "Tax ID" }, kind: "text", get: () => form.taxId },
  ],
  checks: [
    {
      id: "tax-id-missing",
      severity: "blocking",
      fields: ["taxId"],
      run: (record) => (record.taxId ? { ok: true } : { ok: false, message: "Tax ID is missing" }),
    },
  ],
  finish: {
    label: "Send invoice",
    closed: invoice.status === "closed",
    action: ({ receipt }) => sendInvoice(invoice.id, receipt),
  },
});
  • Field kind is text, number, date or select. Check severity is blocking, warning or info. run(record, { signals }) returns { ok: true } or { ok: false, message, fix? }.
  • Checks run when the mode starts and 250 ms after a field's value changes (values are compared as JSON).
  • Only one record is in immersive mode at a time. A second call replaces the first.
  • Each turn carries at most 50 fields and 100 checks, field values over 2 KB are cut, and the whole object stays under 16 KB. Everything sent goes to the model provider, so do not declare fields holding secrets.
  • finish() records the finish with Baseera first and only then runs your finish.action({ receipt, override }). Your route must call verifyFinish from @baseera/node with the receipt.

useBaseeraImmersiveState

function useBaseeraImmersiveState(): BaseeraImmersiveState;

The immersive state, for the interface around the record.

Prop

Type

The object has a few more fields (entity, counts, checksFailed, fieldLabels, boundFields, lastApplied, lastRunAt, focusField, undoLastDraft). Your editor lists them with their types.

useBaseeraSignal

function useBaseeraSignal(): (name: string, data?: unknown) => void;

Returns signal(name, data?). Call it when something happens in your UI that a check may depend on, such as a document being uploaded. With a record open, a signal re-runs the checks at once.

const signal = useBaseeraSignal();
<Uploader onUploaded={(file) => signal("document.uploaded", { name: file.name })} />;

name must match ^[a-z0-9_.-]{1,64}$ and data is JSON of at most 2 KB. A bad signal, or one with no record open, is ignored with a development warning.

useBaseeraField

function useBaseeraField(name: string, options: BaseeraFieldOptions): BaseeraFieldState;

The headless version of BaseeraField. It returns { draft, flag, focused, approve, reject, bindRef, focusControl }. Put bindRef on your wrapper element. draft is { value, reason, source }, flag is { severity, message, checkId }, and focused is { at } for 2 seconds after Baseera focuses the field. approve() writes the draft through your onChange; reject(reason?) drops it and writes nothing.

const { draft, flag, approve, reject, bindRef } = useBaseeraField("taxId", { onChange: setTaxId });

firstControl(root) returns the first control inside an element that is not part of Baseera's own UI (elements marked data-baseera-ui).

useBaseeraTheme and useBaseeraAgentTheme

function useBaseeraTheme(): BaseeraTheme | undefined;
function useBaseeraAgentTheme(): { theme: AgentTheme | null; logoUrl: string | null };

useBaseeraTheme returns the provider's theme prop. useBaseeraAgentTheme returns the theme and logo the agent's owner published in the console. Both fields are null until loaded and when the agent has none. logoUrl is a blob: URL.

Other exports

ExportWhat it is
BaseeraRejectionThe error a custom tool throws when the user declines inside your UI. See Tools and approvals.
CHECK_FAILED_MESSAGEThe message of a check whose code threw.
FOCUS_FIELD_TOOL, PREFILL_DRAFT_TOOLThe names of the built-in tools ui.focusField and ui.prefillDraft.
FEEDBACK_REASON_MAX500, the longest feedback reason.
PROTOCOL_VERSIONThe wire protocol version, "v0".

Next steps

On this page