@braingrid/agents
v1.0.2
Published
Production-ready agent framework with intelligent model selection, event system, and pluggable architecture
Readme
@braingrid/agents
Production-ready agent framework with intelligent model selection, event system, and pluggable architecture.
Features
- BaseAgent - Abstract class for building AI agents with ToolLoopAgent integration
- Event System - Complete observability with 15+ event types
- Model Selection - Intelligent, complexity-based routing across providers
- Prompt Management - Context interpolation with pluggable storage
- Type Safety - 100% type-safe with zero
anytypes in production code - Optional Multi-Tenancy - userId/organizationId when needed
- Pluggable Everything - Logger, events, storage, tools
- Framework-Agnostic - Works anywhere Node.js runs
Installation
pnpm add @braingrid/agents ai @ai-sdk/anthropicQuick Start
import { BaseAgent, createAgent, InMemoryEventBus, registerAgentClass } from '@braingrid/agents';
import { tool } from 'ai';
import { z } from 'zod';
// 1. Create a custom agent
class WeatherAgent extends BaseAgent {
protected getTools() {
return {
getWeather: tool({
description: 'Get current weather',
inputSchema: z.object({
city: z.string(),
}),
execute: async ({ city }) => ({
city,
temperature: 72,
conditions: 'Sunny',
}),
}),
};
}
}
// 2. Register the agent
registerAgentClass('weather', WeatherAgent);
// 3. Create event bus (optional)
const eventBus = new InMemoryEventBus();
eventBus.subscribe(event => {
console.log('[EVENT]', event.type, event);
});
// 4. Create and use agent
const agent = createAgent({
agentType: 'weather',
events: eventBus,
promptContext: { userName: 'Alice' },
});
const result = await agent.sendMessage({
prompt: 'What is the weather in San Francisco?',
stream: false,
});
console.log(result.text);Event System
The event system provides complete observability:
import { InMemoryEventBus, Filters, FilteredEventBus } from '@braingrid/agents';
// Create event bus
const eventBus = new InMemoryEventBus();
// Subscribe to all events
eventBus.subscribe(event => {
console.log(event.type, event);
});
// Subscribe to specific event types
eventBus.subscribe('agent.completed', event => {
console.log('Agent completed in', event.durationMs, 'ms');
console.log('Used', event.totalTokens, 'tokens');
});
// Filter events
const errorBus = new FilteredEventBus(
eventBus,
Filters.errorsOnly()
);Event Types
- Lifecycle:
agent.created,agent.started,agent.completed,agent.failed - Steps:
step.started,step.completed - Tools:
tool.called,tool.completed - Model:
model.selected - Prompts:
prompt.loaded,prompt.interpolated - Tokens:
tokens.consumed - Streaming:
stream.started,stream.chunk,stream.completed
Event Bus Implementations
- InMemoryEventBus - For testing and local subscriptions
- CallbackEventBus - Simple single-callback integration
- MultiEventBus - Fan-out to multiple destinations
- FilteredEventBus - Filter events before publishing
- ValidatingEventBus - Validate events with Zod schemas
Multi-Tenancy (Optional)
const agent = createAgent({
agentType: 'chat',
tenancy: {
userId: 'user-123',
organizationId: 'org-456',
},
});
const tenancy = agent.getTenancy();
console.log(tenancy.userId); // 'user-123'Custom Logging
import { type AgentLogger } from '@braingrid/agents';
import pino from 'pino';
class PinoLogger implements AgentLogger {
private logger = pino();
debug(msg: string, data?: unknown) {
this.logger.debug(data, msg);
}
info(msg: string, data?: unknown) {
this.logger.info(data, msg);
}
warn(msg: string, data?: unknown) {
this.logger.warn(data, msg);
}
error(msg: string, error: Error, data?: unknown) {
this.logger.error({ err: error, ...data }, msg);
}
}
const agent = createAgent({
agentType: 'chat',
logger: new PinoLogger(),
});License
Apache-2.0
