Class: ChatBot<TResult>
Defined in: chat/src/chat-bot.ts:247
Simplified ChatBot - thin wrapper around Loop + Chain
Examples
Simple user chat
const assistant = Baleybot.create({ ... });
const chat = ChatBot.forUser(assistant);
await chat.send("Hello!");
With custom history (file-based)
const chat = ChatBot.forUser(assistant, {
history: History.file('chat.json')
});
Multi-agent
const chat = ChatBot.forAgents([researcher, writer], {
maxTurns: 10,
handlers: {
onToolCallStart: (botName, event) => console.log(event.toolName)
}
});
Type Parameters
TResult
TResult = JsonValue
The expected result type
Implements
Processable<string,TResult>
Methods
clearHistory()
clearHistory():
Promise<void>
Defined in: chat/src/chat-bot.ts:1119
Clear the conversation history
Returns
Promise<void>
getBotNames()
getBotNames():
string[]
Defined in: chat/src/chat-bot.ts:1084
Get all bot names in this processable (including nested processables)
Returns
string[]
Array of bot names that can emit events
Example
const pipeline = pipeline()
.step(chatBot)
.parallel({ sentiment: sentimentBot, tone: toneBot })
.build();
const botNames = pipeline.getBotNames();
// ['assistant', 'sentiment', 'tone']
Implementation of
getChildren()
getChildren():
ProcessableChild[]
Defined in: chat/src/chat-bot.ts:1096
The participants, as the turn loop that drives them.
A chat is a repeat edge by construction — the same participant chain
runs once per turn until maxTurns or a stop condition — so the loop is
the honest shape here, not a flat list of participants that would suggest
each runs once.
Returns
ProcessableChild[]
Implementation of
getHistory()
getHistory():
History
Defined in: chat/src/chat-bot.ts:1127
Get the underlying History instance Useful for advanced history management or sharing between ChatBot instances
Returns
getId()
getId():
string
Defined in: chat/src/chat-bot.ts:1070
Get the unique ID of this processable instance
Each processable has a unique ID that persists for its lifetime. IDs are useful for:
- Filtering specific instances in subscriptions
- Tracking performance metrics per instance
- Debugging nested compositions
Returns
string
Unique ID string
Example
const bot1 = Baleybot.create({ name: 'analyzer' });
const bot2 = Baleybot.create({ name: 'analyzer' });
bot1.getId(); // 'baleybot-1-a3f891'
bot2.getId(); // 'baleybot-2-b4c2d3'
// Same semantic name, different IDs
bot1.getName(); // 'analyzer'
bot2.getName(); // 'analyzer'
Implementation of
getMessages()
getMessages():
Promise<ChatMessage[]>
Defined in: chat/src/chat-bot.ts:1104
Get all messages in the conversation history in API-compatible format Returns ChatMessage[] suitable for sending to LLM APIs
Returns
Promise<ChatMessage[]>
getName()
getName():
string
Defined in: chat/src/chat-bot.ts:604
Get the name of this chat
Returns
string
Implementation of
getSegments()
getSegments():
StreamSegment[]
Defined in: chat/src/chat-bot.ts:1112
Get conversation as stream segments StreamSegment[] is the canonical UI representation
Returns
onAllEvents()
onAllEvents(
listener): () =>void
Defined in: chat/src/chat-bot.ts:630
Subscribe to all conversation events
Parameters
listener
(event) => void
Returns
() => void
onEvent()
onEvent(
eventType,listener): () =>void
Defined in: chat/src/chat-bot.ts:611
Subscribe to conversation events
Parameters
eventType
"error" | "turn_start" | "turn_complete" | "tool_call_start" | "tool_call_output" | "tool_call_stream_start" | "tool_call_stream_delta" | "tool_call_stream_complete" | "tool_validation_error" | "text_delta" | "structured_output_delta" | "reasoning" | "tool_execution_stream" | "conversation_complete"
listener
(event) => void
Returns
() => void
process()
process(
input,options?):Promise<InferSchemaOutput<TResult>>
Defined in: chat/src/chat-bot.ts:488
Process input through the conversation. Accepts plain text or multimodal input (files, images, etc.). Multimodal input is passed through to the participant Baleybot which handles content part translation and schema validation.
Parameters
input
string | UnifiedMessageInput
options?
ProcessOptions
Returns
Promise<InferSchemaOutput<TResult>>
Implementation of
processSafe()
processSafe(
input,options?):Promise<Result<TResult,Error>>
Defined in: chat/src/chat-bot.ts:577
Process with Result type for safe error handling
Parameters
input
string
options?
ProcessOptions
Returns
Promise<Result<TResult, Error>>
send()
send(
message,options?):Promise<TResult>
Defined in: chat/src/chat-bot.ts:594
Send a message (chat-friendly alias for process)
Parameters
message
string | UnifiedMessageInput
options?
ProcessOptions
Returns
Promise<TResult>
streamConversation()
streamConversation(
input,options?):AsyncGenerator<{participant:string;result:JsonValue;shouldStop:boolean;timestamp:Date;turnNumber:number; },void,unknown>
Defined in: chat/src/chat-bot.ts:653
Stream conversation turns as an async generator
Parameters
input
string
options?
ProcessOptions
Returns
AsyncGenerator<{ participant: string; result: JsonValue; shouldStop: boolean; timestamp: Date; turnNumber: number; }, void, unknown>
subscribeToAll()
subscribeToAll(
options?):Subscription
Defined in: chat/src/chat-bot.ts:1074
Subscribe to categorized events from this processable and all nested processables
Provides fine-grained control over event handling with categorized callbacks:
- onStreamEvent: Real-time content streaming (text_delta, structured_output_delta, tool_call_arguments_delta)
- onProgressUpdate: Status updates (tool_execution_start, tool_call_stream_start, tool_call_stream_complete, reasoning)
- onComplete: Emitted when each bot finishes processing with final output
- onError: Error events (error, tool_validation_error)
Callbacks now receive both bot ID and name for precise identification:
- botId: Unique instance identifier (e.g., 'baleybot-1-a3f891')
- botName: Semantic name (e.g., 'analyzer', 'router', 'processor')
Parameters
options?
Optional categorized callbacks and bot filter
omit?
string[]
onComplete?
(botId, botName, output) => void
onError?
(botId, botName, event) => void
onProgressUpdate?
(botId, botName, event) => void
onStreamEvent?
(botId, botName, event) => void
Returns
Subscription
Subscription object with unsubscribe method
Examples
Subscribe to all events
const subscription = pipeline.subscribeToAll({
onStreamEvent(botId, botName, event) {
// Real-time streaming content
if (event.type === 'text_delta') {
console.log(`[${botId}] ${botName}:`, event.content);
}
},
onProgressUpdate(botId, botName, event) {
// Status updates
if (event.type === 'tool_execution_start') {
console.log(`${botName} (${botId}) executing ${event.toolName}`);
}
},
onComplete(botId, botName, output) {
// Bot finished processing
console.log(`${botName} completed:`, output);
},
onError(botId, botName, event) {
// Errors
console.error(`${botName} error:`, event);
}
});
await pipeline.process('input');
subscription.unsubscribe();
Filter specific bots by name or ID
const subscription = pipeline.subscribeToAll({
onStreamEvent(botId, botName, event) {
console.log(`${botName}:`, event);
},
omit: ['chat-step', 'processor-42-8a3f91'] // Filter by name or ID
});
Implementation of
create()
staticcreate<T>(config):ChatBot<T>
Defined in: chat/src/chat-bot.ts:347
Type Parameters
T
T = JsonValue
Parameters
config
Returns
ChatBot<T>
forAgents()
staticforAgents<TAgents,TLast,TOutput>(agents,options?):ChatBot<TOutput>
Defined in: chat/src/chat-bot.ts:450
Create a multi-agent conversation
Type inference:
- Automatically infers output type from the last agent in the array
- If agents array is empty or inference fails, defaults to
JsonValue - For maximum type safety, ensure all agents have compatible output types
Type Parameters
TAgents
TAgents extends readonly Processable<unknown, unknown>[]
TLast
TLast extends Processable<unknown, unknown> = TAgents extends readonly [unknown, Last] ? Last extends Processable<unknown, unknown> ? Last : Processable<unknown, unknown> : Processable<unknown, unknown>
TOutput
TOutput = TLast extends Processable<unknown, O> ? O : JsonValue
Parameters
agents
TAgents
Array of agents to participate in the conversation
options?
Optional configuration
formatTimestamp?
(date) => string
Custom timestamp formatter (defaults to ISO 8601)
handlers?
Token handlers for streaming events
history?
History instance (defaults to in-memory)
includeTimestamps?
boolean
When true, prefixes user and assistant messages with timestamps
maxTurns?
number
Maximum number of conversation turns
name?
string
Custom name for this chat
Returns
ChatBot<TOutput>
Example
const researcher = Baleybot.create({
outputSchema: z.object({ findings: z.string() })
});
const writer = Baleybot.create({
outputSchema: z.object({ article: z.string() })
});
// ✅ Type automatically inferred from last agent (writer)!
const chat = ChatBot.forAgents([researcher, writer], {
maxTurns: 10,
includeTimestamps: true, // Add timestamps to conversation
});
const result = await chat.process("Research and write");
// result is typed as { article: string } (from writer's schema)
forUser()
staticforUser<TBot>(agent,options?):ChatBot<InferBotOutput<TBot>>
Defined in: chat/src/chat-bot.ts:391
Create a user chat with automatic type inference
Type is automatically inferred from agent's output schema - no manual annotation needed!
The return type is automatically inferred from the agent's outputSchema:
- If agent has a Zod schema, the output type is inferred from that schema
- If agent has no schema, the output type defaults to
string - Full TypeScript autocomplete and type safety work automatically
Type Parameters
TBot
TBot extends Processable<unknown, unknown>
Parameters
agent
TBot
The agent to chat with
options?
Optional configuration
formatTimestamp?
(date) => string
Custom timestamp formatter (defaults to ISO 8601)
handlers?
Token handlers for streaming events
history?
History instance (defaults to in-memory)
includeTimestamps?
boolean
When true, prefixes user and assistant messages with timestamps
name?
string
Custom name for this chat
Returns
ChatBot<InferBotOutput<TBot>>
Example
const assistant = Baleybot.create({
outputSchema: z.object({
response: z.string(),
confidence: z.number()
})
});
// ✅ Type automatically inferred! No manual <Type> annotation needed!
const chat = ChatBot.forUser(assistant, {
includeTimestamps: true, // Add timestamps to messages
});
const result = await chat.send("Hello");
// TypeScript knows the exact shape automatically:
result.response; // ✅ string
result.confidence; // ✅ number
// @ts-expect-error
result.invalid; // ❌ Type error!