Examples
Real-world examples and use cases demonstrating the power of the Aisar SDK.
Quick Start Examples
Simple Chatbot
The most basic example - a conversational AI agent.
import { Aisar } from '@aisar/sdk';
const aisar = new Aisar({
apiKey: process.env.AISAR_API_KEY
});
// Create a simple chatbot
const agent = await aisar.createAgent({
name: 'Simple Chatbot',
instructions: 'You are a friendly and helpful chatbot. Keep responses concise and engaging.'
});
// Start a conversation
const session = await aisar.createSession(agent.id);
// Chat with the bot
const response = await session.addMessage('user', 'Tell me a joke!');
console.log(response.content);
// Output: "Why don't scientists trust atoms? Because they make up everything! 😄"→ See full Simple Chatbot example
Memory-Enabled Agent
An agent that remembers previous conversations and user preferences.
// Create agent with memory
const memoryAgent = await aisar.createAgent({
name: 'Personal Assistant',
instructions: 'You are a personal assistant that remembers user preferences and past conversations.',
memoryEnabled: true,
memoryConfig: {
maxTokens: 4000,
similarityThreshold: 0.7
}
});
const session = await aisar.createSession(memoryAgent.id, 'user_123');
// First conversation
await session.addMessage('user', 'My name is Sarah and I love Italian food');
const response1 = await session.addMessage('user', 'What should I cook tonight?');
console.log(response1.content);
// Output: "Hi Sarah! Since you love Italian food, how about making a delicious pasta carbonara..."
// Later conversation (hours or days later)
const laterSession = await aisar.createSession(memoryAgent.id, 'user_123');
const response2 = await laterSession.addMessage('user', 'Recommend a restaurant');
console.log(response2.content);
// Output: "Based on your love for Italian cuisine, I'd recommend Bella Vista - they have excellent pasta dishes!"→ See full Memory Agent example
Tool Integration
An agent that can execute external functions and integrate with APIs.
// Create a weather tool
const weatherTool = await aisar.createTool({
name: 'get_weather',
description: 'Get current weather information for a specific location',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
units: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'fahrenheit' }
},
required: ['location']
},
handler: async ({ location, units = 'fahrenheit' }) => {
// Call weather API
const weatherData = await fetch(`https://api.weather.com/v1/current?q=${location}`);
const data = await weatherData.json();
return {
location,
temperature: units === 'celsius' ? data.temp_c : data.temp_f,
condition: data.condition.text,
humidity: data.humidity
};
}
});
// Create agent with weather tool
const weatherAgent = await aisar.createAgent({
name: 'Weather Assistant',
instructions: 'Help users get weather information. Use the weather tool when they ask about weather.',
tools: [weatherTool.id]
});
// Use the agent
const session = await aisar.createSession(weatherAgent.id);
const response = await session.addMessage('user', 'What\'s the weather like in New York?');
console.log(response.content);
// Output: "The current weather in New York is 72°F with partly cloudy skies. The humidity is at 58%."→ See full Tool Integration example
Real-World Use Cases
Customer Support Bot
A comprehensive customer support system with knowledge base integration, ticket creation, and escalation handling.
Features:
- FAQ answering from knowledge base
- Support ticket creation and tracking
- Escalation to human agents
- Conversation history and context
- Customer satisfaction tracking
// Knowledge base tool
const knowledgeBaseTool = await aisar.createTool({
name: 'search_knowledge_base',
description: 'Search the company knowledge base for answers',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search query' }
},
required: ['query']
},
handler: async ({ query }) => {
return await knowledgeBase.search(query);
}
});
// Support ticket tool
const ticketTool = await aisar.createTool({
name: 'create_support_ticket',
description: 'Create a support ticket for complex issues',
parameters: {
type: 'object',
properties: {
subject: { type: 'string' },
description: { type: 'string' },
priority: { type: 'string', enum: ['low', 'medium', 'high'] }
},
required: ['subject', 'description']
},
handler: async ({ subject, description, priority = 'medium' }) => {
return await supportSystem.createTicket({ subject, description, priority });
}
});
const supportAgent = await aisar.createAgent({
name: 'Customer Support Agent',
instructions: `You are a helpful customer support representative...`,
memoryEnabled: true,
tools: [knowledgeBaseTool.id, ticketTool.id]
});→ See full Customer Support example
E-commerce Shopping Assistant
An intelligent shopping assistant that helps customers find products, provides recommendations, and tracks orders.
Features:
- Product search and recommendations
- Order tracking and status updates
- Personalized suggestions based on purchase history
- Shopping cart management
- Promotional code application
→ See full E-commerce Assistant example
Document Q&A System
A system that can answer questions about uploaded documents using semantic search and knowledge extraction.
Features:
- Document upload and processing
- Semantic search across document content
- Question answering with source citations
- Multi-document knowledge synthesis
- Export of insights and summaries
→ See full Document Q&A example
Advanced Patterns
Multi-Agent System
Coordinate multiple specialized agents working together on complex tasks.
// Research agent
const researchAgent = await aisar.createAgent({
name: 'Research Specialist',
instructions: 'You specialize in gathering and analyzing information from various sources.',
tools: [webSearchTool.id, documentAnalysisTool.id]
});
// Writing agent
const writingAgent = await aisar.createAgent({
name: 'Content Writer',
instructions: 'You create well-structured, engaging content based on research findings.',
memoryEnabled: true
});
// Coordination system
class MultiAgentOrchestrator {
async processTask(task: string) {
// Step 1: Research
const researchSession = await aisar.createSession(researchAgent.id);
const research = await researchSession.addMessage('user', `Research: ${task}`);
// Step 2: Writing (with research context)
const writingSession = await aisar.createSession(writingAgent.id);
await writingSession.addMessage('user', `Based on this research: ${research.content}, write an article about: ${task}`);
return writingSession;
}
}→ See full Multi-Agent example
Workflow Integration
Integrate agents into complex business workflows with state management and human-in-the-loop approval.
Features:
- Workflow state management
- Conditional branching based on agent responses
- Human approval gates
- Error handling and retry logic
- Audit trails and logging
→ See full Workflow Integration example
Custom Memory Store
Implement custom memory storage backends for specialized use cases.
class CustomMemoryStore {
async storeMemory(agentId: string, memory: MemoryInput) {
// Custom storage logic (Redis, Elasticsearch, etc.)
const embedding = await this.generateEmbedding(memory.content);
return await this.customDB.store({
agentId,
...memory,
embedding
});
}
async searchMemory(agentId: string, query: string, options: SearchOptions) {
// Custom search logic
const queryEmbedding = await this.generateEmbedding(query);
return await this.customDB.vectorSearch({
agentId,
vector: queryEmbedding,
...options
});
}
}
// Use custom memory store
const agent = await aisar.createAgent({
name: 'Custom Memory Agent',
memoryEnabled: true,
memoryStore: new CustomMemoryStore()
});→ See full Custom Memory example
Platform Integrations
Discord Bot
import { Client, GatewayIntentBits } from 'discord.js';
import { Aisar } from '@aisar/sdk';
const discordClient = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
const aisar = new Aisar({ apiKey: process.env.AISAR_API_KEY });
const discordAgent = await aisar.createAgent({
name: 'Discord Assistant',
instructions: 'You are a helpful Discord bot. Keep responses friendly and use Discord formatting when appropriate.',
memoryEnabled: true
});
discordClient.on('messageCreate', async (message) => {
if (message.author.bot) return;
const session = await aisar.createSession(discordAgent.id, message.author.id);
const response = await session.addMessage('user', message.content);
await message.reply(response.content);
});→ See full Discord Bot example
Slack App
WhatsApp Integration
Framework Examples
Next.js API Routes
// pages/api/chat.ts
import { Aisar } from '@aisar/sdk';
import type { NextApiRequest, NextApiResponse } from 'next';
const aisar = new Aisar({
apiKey: process.env.AISAR_API_KEY
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { agentId, message, userId } = req.body;
const session = await aisar.createSession(agentId, userId);
const response = await session.addMessage('user', message);
res.json({
success: true,
response: response.content,
sessionId: session.id
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
}Express.js Server
React Components
import { useState, useEffect } from 'react';
import { AisarClient } from '../lib/aisar-client';
export function ChatInterface({ agentId, userId }) {
const [messages, setMessages] = useState([]);
const [inputText, setInputText] = useState('');
const [isLoading, setIsLoading] = useState(false);
const sendMessage = async () => {
if (!inputText.trim()) return;
setIsLoading(true);
const userMessage = { role: 'user', content: inputText };
setMessages(prev => [...prev, userMessage]);
setInputText('');
try {
const response = await AisarClient.sendMessage(agentId, inputText, userId);
setMessages(prev => [...prev, { role: 'agent', content: response.content }]);
} catch (error) {
console.error('Failed to send message:', error);
} finally {
setIsLoading(false);
}
};
return (
<div className="chat-interface">
<div className="messages">
{messages.map((msg, idx) => (
<div key={idx} className={`message ${msg.role}`}>
{msg.content}
</div>
))}
{isLoading && <div className="message loading">Thinking...</div>}
</div>
<div className="input-area">
<input
value={inputText}
onChange={(e) => setInputText(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="Type your message..."
/>
<button onClick={sendMessage} disabled={isLoading}>
Send
</button>
</div>
</div>
);
}Deployment Examples
Cloudflare Workers
import { Aisar } from '@aisar/sdk';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const aisar = new Aisar({
apiKey: env.AISAR_API_KEY
});
if (request.method === 'POST') {
const { message, agentId, userId } = await request.json();
const session = await aisar.createSession(agentId, userId);
const response = await session.addMessage('user', message);
return new Response(JSON.stringify({
success: true,
response: response.content
}), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response('Method not allowed', { status: 405 });
}
};→ See full Cloudflare Workers example
Vercel Edge Functions
AWS Lambda
Testing Examples
Unit Testing
import { describe, it, expect, beforeEach } from 'vitest';
import { Aisar } from '@aisar/sdk';
describe('Aisar SDK', () => {
let aisar: Aisar;
let testAgent: any;
beforeEach(async () => {
aisar = new Aisar({
apiKey: process.env.AISAR_TEST_API_KEY
});
testAgent = await aisar.createAgent({
name: 'Test Agent',
instructions: 'You are a test agent. Always respond with "Test response"'
});
});
it('should create an agent', () => {
expect(testAgent.id).toBeDefined();
expect(testAgent.name).toBe('Test Agent');
});
it('should handle conversations', async () => {
const session = await aisar.createSession(testAgent.id);
const response = await session.addMessage('user', 'Hello');
expect(response.content).toContain('Test response');
expect(response.role).toBe('agent');
});
});Performance Examples
Caching and Optimization
class OptimizedAisarClient {
private cache = new Map<string, any>();
private sessionPool = new Map<string, any[]>();
async getCachedAgent(agentId: string) {
if (!this.cache.has(agentId)) {
const agent = await aisar.getAgent(agentId);
this.cache.set(agentId, agent);
}
return this.cache.get(agentId);
}
async getPooledSession(agentId: string, userId: string) {
const key = `${agentId}:${userId}`;
let sessions = this.sessionPool.get(key) || [];
if (sessions.length === 0) {
const session = await aisar.createSession(agentId, userId);
return session;
}
return sessions.pop();
}
}→ See full Performance example
Getting Started
- Choose a use case that matches your needs
- Copy the example code and adapt it to your requirements
- Set up your environment with the necessary API keys
- Test locally before deploying to production
- Scale gradually as your usage grows
Need Help?
- 📖 Documentation: Complete API Reference
- 💬 Community: Join our Discord
- 🐛 Issues: Report bugs on GitHub
- 📧 Support: Email us at support@aisar.ai
All examples are production-ready and include proper error handling, security considerations, and best practices.
