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
| Property | Type | Description |
|---|---|---|
messages | UIMessage[] | The conversation as AI SDK messages |
status | ChatStatus | AI SDK's chat status |
isLoading | boolean | Whether a turn is in flight |
isStreaming | boolean | Whether a reply is streaming in |
error | Error | null | Last error, if any |
send | (text: string) => Promise | Send 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 | () => void | Abort the current stream |
pendingApprovals | PendingApproval[] | Tool calls waiting for a decision (parts in approval-requested) |
respondToToolApprovals | (responses: ToolApprovalResponse[]) => void | Approve/reject every pending id in one batch resume |
Options
| Option | Type | Description |
|---|---|---|
model | string | ModelConfig | LLM model to use; a proxyUrl goes in its config |
systemPrompt | string | System prompt for the processor |
tools | Record<string, ToolDefinition> | Tools available to the processor |
responseSchema | ZodSchema | JSON Schema | Structured response schema (maps to Output.object()) |
maxToolIterations | number | Tool loop step cap |
storage | HistoryStorage | Where a browser conversation is kept |
api, sessionId | string | A createChatRoute server and its conversation (with headers, fetch) |
shouldAskApproval | (toolName: string) => boolean | Approve a tool's calls without asking |
onApprovalRequest | (pending: PendingApproval) => void | Fired 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 clientuseChat; for hosted crew chat use/api/chat- Server mode options:
apiUrl,chatId,multiAgent,agents,loadHistory,isResuming - Scalar approvals:
pendingApproval,approveToolCall,rejectToolCall SendStreamingOptions(mentions, etc.)segmentsandsendStreaming— the hook returns AI SDKmessages, andsendstreams- The
proxyUrloption — put it in the model's config
See useChat migration for before/after patterns.