API Reference
Complete reference for all Aisar SDK classes, methods, types, and interfaces.
Core Classes
The Aisar SDK is built around these core classes:
Aisar
The main SDK client class for managing agents, sessions, and configuration.
typescript
import { Aisar } from '@aisar/sdk';
const aisar = new Aisar({
apiKey: 'your-api-key',
baseUrl: 'https://api.aisar.ai'
});Agent
Represents an AI agent with specific instructions, tools, and capabilities.
typescript
const agent = await aisar.createAgent({
name: 'Customer Support',
instructions: 'Be helpful and professional',
memoryEnabled: true
});Session
Manages conversation state and message flow between users and agents.
typescript
const session = await aisar.createSession(agent.id, 'user_123');
const response = await session.addMessage('user', 'Hello!');Memory
Handles vector-based memory storage and semantic search.
typescript
await aisar.storeMemory(agent.id, {
content: 'User prefers coffee over tea',
type: 'preference'
});Tool
Defines external functions that agents can execute.
typescript
const tool = await aisar.createTool({
name: 'get_weather',
description: 'Get weather information',
parameters: { /* JSON Schema */ }
});Type Definitions
Agent Types
Memory Types
Session Types
Tool Types
Common Types
Error Handling
Error Classes
AisarError- Base error classAuthenticationError- Authentication failuresValidationError- Input validation errorsRateLimitError- Rate limiting errorsNetworkError- Network connectivity issues
typescript
try {
const agent = await aisar.createAgent(config);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Invalid configuration:', error.details);
} else if (error instanceof RateLimitError) {
console.error('Rate limited, retry after:', error.retryAfter);
}
}Response Formats
Standard Response Format
All API methods return responses in a consistent format:
typescript
interface APIResponse<T> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
details?: any;
};
metadata?: {
requestId: string;
timestamp: string;
rateLimit?: {
limit: number;
remaining: number;
resetAt: string;
};
};
}Streaming Response Format
Streaming responses provide real-time chunks:
typescript
interface StreamingChunk {
type: 'content' | 'tool_call' | 'tool_result' | 'done' | 'error';
content?: string;
toolName?: string;
parameters?: any;
result?: any;
message?: Message;
error?: string;
}Configuration Options
SDK Configuration
typescript
interface AisarConfig {
apiKey: string; // Required: Your API key
baseUrl?: string; // Optional: API base URL
timeout?: number; // Optional: Request timeout (ms)
retries?: number; // Optional: Max retry attempts
debug?: boolean; // Optional: Enable debug logging
defaultModel?: string; // Optional: Default AI model
rateLimiting?: { // Optional: Rate limiting config
maxRequestsPerMinute?: number;
maxConcurrentRequests?: number;
};
}Memory Configuration
typescript
interface MemoryConfig {
maxTokens?: number; // Max tokens to store
similarityThreshold?: number; // Minimum similarity for retrieval
maxMemories?: number; // Max memories to retrieve
embeddingModel?: string; // Embedding model to use
autoArchiveAge?: number; // Days before auto-archiving
compressionEnabled?: boolean; // Enable compression
}Streaming Configuration
typescript
interface StreamingConfig {
bufferSize?: number; // Chunk buffer size
flushInterval?: number; // Milliseconds between flushes
enableToolStreaming?: boolean; // Stream tool execution
wordBoundary?: boolean; // Respect word boundaries
}Usage Patterns
Basic Usage Pattern
typescript
// 1. Initialize SDK
const aisar = new Aisar({ apiKey: 'your-key' });
// 2. Create agent
const agent = await aisar.createAgent({
name: 'Assistant',
instructions: 'Be helpful'
});
// 3. Create session
const session = await aisar.createSession(agent.id);
// 4. Send message
const response = await session.addMessage('user', 'Hello!');
console.log(response.content);Advanced Usage Pattern
typescript
// 1. Initialize with advanced config
const aisar = new Aisar({
apiKey: process.env.AISAR_API_KEY,
timeout: 30000,
retries: 3,
debug: true
});
// 2. Create agent with memory and tools
const agent = await aisar.createAgent({
name: 'Advanced Assistant',
instructions: 'You are a helpful assistant with memory and tools',
memoryEnabled: true,
memoryConfig: {
maxTokens: 4000,
similarityThreshold: 0.7
},
tools: [weatherTool.id, calculatorTool.id]
});
// 3. Create session with streaming
const session = await aisar.createSession(agent.id, 'user_123', {
streamingEnabled: true,
metadata: { priority: 'high' }
});
// 4. Stream response
const stream = await session.streamMessage('user', 'What\'s the weather?');
for await (const chunk of stream) {
if (chunk.type === 'content') {
process.stdout.write(chunk.content);
}
}Migration Guide
From v0.x to v1.x
Key changes in v1.x:
Renamed Methods:
typescript// v0.x aisar.createBot() → aisar.createAgent() aisar.chat() → session.addMessage() // v1.x const agent = await aisar.createAgent(config); const session = await aisar.createSession(agent.id); await session.addMessage('user', 'Hello');Memory Integration:
typescript// v0.x - Memory was separate const memory = new AisarMemory(); // v1.x - Memory is integrated const agent = await aisar.createAgent({ memoryEnabled: true });Tool System:
typescript// v0.x - Tools were callbacks const bot = aisar.createBot({ tools: { weather: (params) => getWeather(params) } }); // v1.x - Tools are first-class objects const tool = await aisar.createTool({ name: 'weather', parameters: { /* schema */ }, handler: (params) => getWeather(params) });
Best Practices
Error Handling
typescript
// Comprehensive error handling
try {
const response = await session.addMessage('user', 'Hello');
} catch (error) {
switch (error.constructor) {
case AuthenticationError:
// Handle auth errors
break;
case RateLimitError:
// Handle rate limiting
await new Promise(resolve =>
setTimeout(resolve, error.retryAfter * 1000)
);
break;
case ValidationError:
// Handle validation errors
console.error('Validation failed:', error.details);
break;
default:
// Handle unexpected errors
console.error('Unexpected error:', error.message);
}
}Resource Management
typescript
// Proper resource cleanup
class ChatManager {
private sessions = new Map<string, Session>();
async createSession(agentId: string, userId: string) {
const session = await aisar.createSession(agentId, userId);
this.sessions.set(session.id, session);
// Auto-cleanup after inactivity
setTimeout(() => {
this.cleanupSession(session.id);
}, 30 * 60 * 1000); // 30 minutes
return session;
}
async cleanupSession(sessionId: string) {
const session = this.sessions.get(sessionId);
if (session) {
await session.close();
this.sessions.delete(sessionId);
}
}
}Performance Optimization
typescript
// Batch operations for better performance
const batchOperations = {
async createMultipleAgents(configs: CreateAgentInput[]) {
return Promise.all(configs.map(config => aisar.createAgent(config)));
},
async storeMultipleMemories(agentId: string, memories: MemoryInput[]) {
return aisar.storeMemories(agentId, memories);
}
};Next Steps
- Explore specific class documentation
- Check out type definitions
- See practical examples
- Review error handling
