sel-chat-coach / src /lib /example-client.ts
james-d-taboola's picture
feat: add init commit according to Issac's repo
4018140
#!/usr/bin/env tsx
/**
* Example client demonstrating how to interact with the Educational AI Agents
*
* Usage:
* npm run example
*
* or directly:
* npx tsx src/example-client.ts
*/
const API_BASE = 'http://localhost:3000';
async function makeRequest(endpoint: string, options: RequestInit = {}) {
const response = await fetch(`${API_BASE}${endpoint}`, {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
return response.json();
}
async function chatWithAgent(message: string, conversationId = 'demo') {
console.log(`๐Ÿง‘ User: ${message}`);
const result = await makeRequest('/api/agent/chat', {
method: 'POST',
body: JSON.stringify({ message, conversationId }),
});
console.log(`๐Ÿค– Agent: ${result.response}`);
console.log('');
return result;
}
async function listTools() {
const result = await makeRequest('/api/agent/tools');
console.log('๐Ÿ”ง Available Tools:');
result.tools.forEach((tool: any) => {
console.log(` - ${tool.name}: ${tool.description}`);
});
console.log('');
}
async function getHistory(conversationId = 'demo') {
const result = await makeRequest(`/api/agent/history/${conversationId}`);
console.log(`๐Ÿ“œ Conversation History (${result.messageCount} messages):`);
result.history.forEach((msg: any, index: number) => {
const icon = msg.role === 'user' ? '๐Ÿง‘' : '๐Ÿค–';
console.log(` ${index + 1}. ${icon} ${msg.role}: ${msg.content.substring(0, 100)}${msg.content.length > 100 ? '...' : ''}`);
});
console.log('');
}
async function runDemo() {
console.log('๐ŸŽ“ Educational AI Agents Demo Starting...\n');
try {
// Check server health
const health = await makeRequest('/health');
console.log('โœ… Server is healthy:', health.status);
console.log('');
// List available tools
await listTools();
const conversationId = `demo-${Date.now()}`;
// Demo conversation showcasing educational capabilities
console.log('=== Educational Demo Conversation ===\n');
// Basic greeting
await chatWithAgent('Hello! I need help with my studies.', conversationId);
// Math help demo
await chatWithAgent('Can you help me solve this equation: 2x + 5 = 13?', conversationId);
// Calculator tool demo for learning
await chatWithAgent('Let me check: what is 15 * 7 + 23?', conversationId);
// Note taking demo for learning
await chatWithAgent('Please save a note: "Quadratic formula: x = (-b ยฑ โˆš(bยฒ-4ac)) / 2a"', conversationId);
// Learning question
await chatWithAgent('Can you explain how to approach word problems in algebra?', conversationId);
// Study summary
await chatWithAgent('Thanks for helping me learn! Can you summarize what we covered today?', conversationId);
// Show conversation history
await getHistory(conversationId);
console.log('โœ… Demo completed successfully!');
} catch (error) {
console.error('โŒ Demo failed:', error);
console.log('\nMake sure the server is running with: npm run dev');
}
}
// Interactive mode function
async function interactiveMode() {
console.log('๐ŸŽฎ Interactive Mode - Type "exit" to quit, "help" for commands\n');
const conversationId = `interactive-${Date.now()}`;
// Simple readline interface for Node.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const question = (prompt: string): Promise<string> => {
return new Promise((resolve) => {
rl.question(prompt, resolve);
});
};
try {
while (true) {
const input = await question('๐Ÿง‘ You: ');
if (input.toLowerCase() === 'exit') {
console.log('๐Ÿ‘‹ Goodbye!');
break;
}
if (input.toLowerCase() === 'help') {
console.log('๐Ÿ’ก Commands:');
console.log(' - Type any educational question to chat with the agent');
console.log(' - "tools" - List available learning tools');
console.log(' - "history" - Show conversation history');
console.log(' - "clear" - Clear conversation');
console.log(' - "exit" - Quit interactive mode');
console.log('');
continue;
}
if (input.toLowerCase() === 'tools') {
await listTools();
continue;
}
if (input.toLowerCase() === 'history') {
await getHistory(conversationId);
continue;
}
if (input.toLowerCase() === 'clear') {
await makeRequest(`/api/agent/history/${conversationId}`, { method: 'DELETE' });
console.log('๐Ÿ—‘๏ธ Conversation cleared\n');
continue;
}
if (input.trim()) {
await chatWithAgent(input, conversationId);
}
}
} catch (error) {
console.error('โŒ Interactive mode error:', error);
} finally {
rl.close();
}
}
// Main execution
async function main() {
const args = process.argv.slice(2);
if (args.includes('--interactive') || args.includes('-i')) {
await interactiveMode();
} else {
await runDemo();
}
}
// Run if this file is executed directly
if (require.main === module) {
main().catch(console.error);
}
export { chatWithAgent, listTools, getHistory, runDemo, interactiveMode };