Skip to main content

React Hooks

The @baleybots/react package provides React hooks for building chat interfaces and using Baleybots processors in React applications.

Installation​

npm install @baleybots/react @baleybots/core

useChat​

useChat is an adapter over AI SDK's useChat (@ai-sdk/react): the conversation is AI SDK UIMessages. With api and sessionId it talks to a createChatRoute server from @baleybots/proxy-server, which keeps the conversation. Otherwise the processor runs in the browser (or React Native) and its model calls go to the provider, or through the proxy named in the model's config. Both stream through core's UI message projection, so the same renderers draw either.

For server-hosted multi-agent crew chat, use the product UI's /api/chat endpoint and useCrewSessions.

Basic usage​

import { useChat, ChatTurns, ChatTurn } from '@baleybots/react';
import { openai } from '@baleybots/core';
import { z } from 'zod';

const ResponseSchema = z.object({
response: z.string(),
});

function ChatComponent() {
const { messages, send, isStreaming, pendingApprovals, respondToToolApprovals } =
useChat({
model: openai('gpt-5.6-luna'),
systemPrompt: 'Answer concisely and accurately',
responseSchema: ResponseSchema,
});

const handleSend = async (text: string) => {
const result = await send(text); // typed from ResponseSchema
};

return (
<div>
<ChatTurns messages={messages}>
{(message) => (
<ChatTurn key={message.id} message={message} />
)}
</ChatTurns>
{isStreaming && <div>Typing…</div>}
{pendingApprovals.length > 0 && (
<button
onClick={() =>
respondToToolApprovals(
pendingApprovals.map((p) => ({ approvalId: p.approvalId, approved: true })),
)
}
>
Approve all
</button>
)}
</div>
);
}

// The same hook against a createChatRoute server:
const chat = useChat({ api: '/chat', sessionId });

Return values​

PropertyTypeDescription
messagesUIMessage[]The conversation as AI SDK messages
statusChatStatusAI SDK's chat status
isLoadingbooleanWhether a turn is in flight
isStreamingbooleanWhether a reply is streaming in
errorError | nullLast error, if any
send(text: string) => PromiseSend a message; streams, then resolves with the turn's result
clearHistory() => Promise<void>Clear the conversation
retryLast() => Promise<void>Run the last user message again
stopStreaming() => voidAbort the current stream
pendingApprovalsPendingApproval[]Tool calls waiting for a decision (parts in approval-requested)
respondToToolApprovals(responses: ToolApprovalResponse[]) => voidApprove/reject every pending id in one batch resume

Options​

OptionTypeDescription
modelstring | ModelConfigLLM model to use; a proxyUrl goes in its config
systemPromptstringSystem prompt for the processor
toolsRecord<string, ToolDefinition>Tools available to the processor
responseSchemaZodSchema | JSON SchemaStructured response schema (maps to Output.object())
maxToolIterationsnumberTool loop step cap
storageHistoryStorageWhere a browser conversation is kept
api, sessionIdstringA createChatRoute server and its conversation (with headers, fetch)
shouldAskApproval(toolName: string) => booleanApprove a tool's calls without asking
onApprovalRequest(pending: PendingApproval) => voidFired when a new approval request appears

ChatTurns and custom rendering​

ChatTurns draws one turn per message; MessagePartRenderer draws one part, picking a tool's card by the kind the tool declares (toolMetadata.display.kind). Override single parts with a function child on ChatTurn:

import { useChat, ChatTurns, ChatTurn } from '@baleybots/react';

function Chat() {
const { messages } = useChat({ model: 'openai|gpt-5.6-luna' });

return (
<ChatTurns messages={messages}>
{(message) => (
<ChatTurn
key={message.id}
message={message}
className={message.role === 'user' ? 'user-bubble' : 'assistant-bubble'}
>
{(part, index) =>
part.type === 'text' ? (
<p key={index}>{part.text}</p>
) : undefined
}
</ChatTurn>
)}
</ChatTurns>
);
}

useBaleybot​

useBaleybot wraps a Baleybot processor for direct use in React. It manages the agent lifecycle and provides a simple interface.

The hook accepts outputSchema (Zod or JSON Schema) and converts it to Output.object() when creating the underlying processor.

import { useBaleybot } from '@baleybots/react';
import { z } from 'zod';

function SentimentAnalyzer() {
const { process, result, isProcessing } = useBaleybot({
name: 'sentiment',
analysisGoal: 'Analyze the sentiment of text',
outputSchema: z.object({
sentiment: z.enum(['positive', 'negative', 'neutral']),
confidence: z.number(),
}),
});

return (
<div>
<button onClick={() => process('I love this product!')}>
Analyze
</button>
{result && <p>Sentiment: {result.sentiment} ({result.confidence})</p>}
</div>
);
}

For direct Baleybot.create() usage outside React, prefer the output config with Output.object() — see Structured Outputs.

Removed APIs​

The following were removed from @baleybots/react useChat:

  • useGroupChat — use client useChat; for hosted crew chat use /api/chat
  • Server mode options: apiUrl, chatId, multiAgent, agents, loadHistory, isResuming
  • Scalar approvals: pendingApproval, approveToolCall, rejectToolCall
  • SendStreamingOptions (mentions, etc.)
  • segments and sendStreaming — the hook returns AI SDK messages, and send streams
  • The proxyUrl option — put it in the model's config

See useChat migration for before/after patterns.