UNPKG

@agentdb/sdk

Version:

JavaScript SDK for AgentDB database service

277 lines (234 loc) 9.81 kB
/** * AgentDB SDK Natural Language to SQL Example * * This example demonstrates how to use the natural language to SQL conversion * feature of the AgentDB SDK. */ import { DatabaseService, ValidationError, AuthenticationError, DatabaseError } from '../index.js'; // Configuration - replace with your actual values const BASE_URL = process.env.AGENTDB_BASE_URL || 'https://api.agentdb.dev'; const API_KEY = process.env.AGENTDB_API_KEY; const TOKEN = process.env.AGENTDB_TOKEN || 'your-uuid-token-here'; if (!API_KEY) { console.error('Please set AGENTDB_API_KEY environment variable'); process.exit(1); } async function runNaturalLanguageExample() { console.log('=== AgentDB SDK Natural Language to SQL Example ===\n'); try { // Initialize the database service const service = new DatabaseService(BASE_URL, API_KEY, true); // Enable debug mode console.log('1. Setting up test database with sample data...'); const dbName = 'nl-test-db'; const connection = service.connect(TOKEN, dbName, 'sqlite'); // Create sample tables and data await connection.execute([ { sql: `CREATE TABLE IF NOT EXISTS employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, department TEXT NOT NULL, salary INTEGER NOT NULL, hire_date DATE NOT NULL, manager_id INTEGER, FOREIGN KEY (manager_id) REFERENCES employees(id) )` }, { sql: `CREATE TABLE IF NOT EXISTS projects ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, budget INTEGER NOT NULL, start_date DATE NOT NULL, end_date DATE, status TEXT DEFAULT 'active' )` }, { sql: `CREATE TABLE IF NOT EXISTS employee_projects ( employee_id INTEGER, project_id INTEGER, role TEXT NOT NULL, hours_allocated INTEGER DEFAULT 40, PRIMARY KEY (employee_id, project_id), FOREIGN KEY (employee_id) REFERENCES employees(id), FOREIGN KEY (project_id) REFERENCES projects(id) )` } ]); // Insert sample data await connection.execute([ { sql: `INSERT OR REPLACE INTO employees (id, name, department, salary, hire_date, manager_id) VALUES (1, 'Alice Johnson', 'Engineering', 95000, '2022-01-15', NULL), (2, 'Bob Smith', 'Engineering', 85000, '2022-03-01', 1), (3, 'Carol Davis', 'Marketing', 75000, '2021-11-10', NULL), (4, 'David Wilson', 'Engineering', 90000, '2023-02-20', 1), (5, 'Eve Brown', 'Sales', 80000, '2022-06-15', NULL), (6, 'Frank Miller', 'Marketing', 70000, '2023-01-05', 3)` }, { sql: `INSERT OR REPLACE INTO projects (id, name, budget, start_date, end_date, status) VALUES (1, 'Website Redesign', 150000, '2023-01-01', '2023-06-30', 'completed'), (2, 'Mobile App', 200000, '2023-03-01', NULL, 'active'), (3, 'Marketing Campaign', 75000, '2023-02-15', '2023-05-15', 'completed'), (4, 'Database Migration', 100000, '2023-07-01', NULL, 'active')` }, { sql: `INSERT OR REPLACE INTO employee_projects (employee_id, project_id, role, hours_allocated) VALUES (1, 1, 'Lead Developer', 40), (2, 1, 'Frontend Developer', 35), (1, 2, 'Technical Lead', 30), (4, 2, 'Backend Developer', 40), (3, 3, 'Campaign Manager', 40), (6, 3, 'Content Creator', 25), (1, 4, 'Database Architect', 20), (2, 4, 'Migration Specialist', 30)` } ]); console.log('✓ Test database created with sample data'); console.log('\n2. Testing basic natural language queries...'); const basicQueries = [ 'show me all employees', 'list all projects', 'find employees in the engineering department', 'show me active projects', 'what is the average salary by department?' ]; for (const query of basicQueries) { console.log(`\n Query: "${query}"`); try { const result = await connection.naturalLanguageToSql(query); console.log(` Generated SQL: ${result.sql}`); if (result.results && result.results[0]) { const rowCount = result.results[0].rows ? result.results[0].rows.length : 0; console.log(` Results: ${rowCount} rows returned`); // Show first few rows for small result sets if (rowCount > 0 && rowCount <= 3) { console.log(` Sample data:`, JSON.stringify(result.results[0].rows[0], null, 2)); } } } catch (error) { console.log(` ❌ Error: ${error.message}`); } } console.log('\n3. Testing complex analytical queries...'); const complexQueries = [ 'show me the total budget for each project status', 'find the highest paid employee in each department', 'list employees working on more than one project', 'show me project budgets and total hours allocated', 'find employees who are managers and their direct reports' ]; for (const query of complexQueries) { console.log(`\n Query: "${query}"`); try { const result = await connection.naturalLanguageToSql(query); console.log(` Generated SQL: ${result.sql}`); if (result.results && result.results[0]) { const rowCount = result.results[0].rows ? result.results[0].rows.length : 0; console.log(` Results: ${rowCount} rows returned`); } } catch (error) { console.log(` ❌ Error: ${error.message}`); } } console.log('\n4. Testing conversation history...'); // Build up a conversation history let conversationHistory = []; const conversationQueries = [ 'show me all employees in engineering', 'what are their average salaries?', 'which of them work on the mobile app project?', 'how many hours are they allocated to that project?' ]; for (const query of conversationQueries) { console.log(`\n Query: "${query}"`); try { const result = await connection.naturalLanguageToSql(query, conversationHistory); console.log(` Generated SQL: ${result.sql}`); if (result.results && result.results[0]) { const rowCount = result.results[0].rows ? result.results[0].rows.length : 0; console.log(` Results: ${rowCount} rows returned`); // Add to conversation history conversationHistory.push({ query: query, sql: result.sql, results: result.results }); console.log(` (Added to conversation history - now ${conversationHistory.length} entries)`); } } catch (error) { console.log(` ❌ Error: ${error.message}`); } } console.log('\n5. Testing edge cases and error handling...'); const edgeCases = [ '', // Empty query 'delete all employees', // Potentially dangerous query 'show me tables that do not exist', // Non-existent tables 'calculate the square root of the employee count' // Complex mathematical operation ]; for (const query of edgeCases) { console.log(`\n Query: "${query}"`); try { if (!query.trim()) { console.log(' ⚠ Skipping empty query'); continue; } const result = await connection.naturalLanguageToSql(query); console.log(` Generated SQL: ${result.sql}`); if (result.results && result.results[0]) { const rowCount = result.results[0].rows ? result.results[0].rows.length : 0; console.log(` Results: ${rowCount} rows returned`); } } catch (error) { console.log(` ❌ Expected error: ${error.message}`); } } console.log('\n6. Performance test with multiple queries...'); const startTime = Date.now(); const performanceQueries = [ 'count employees by department', 'show project completion status', 'find top 3 highest paid employees' ]; for (const query of performanceQueries) { const queryStart = Date.now(); try { const result = await connection.naturalLanguageToSql(query); const queryTime = Date.now() - queryStart; console.log(` "${query}" - ${queryTime}ms`); } catch (error) { console.log(` "${query}" - Error: ${error.message}`); } } const totalTime = Date.now() - startTime; console.log(` Total time for ${performanceQueries.length} queries: ${totalTime}ms`); console.log('\n7. Cleaning up...'); await service.deleteDatabase(TOKEN, dbName, 'sqlite'); console.log('✓ Test database deleted'); console.log('\n=== Natural Language to SQL Example Complete ==='); } catch (error) { console.error('\n❌ Error during natural language example:'); if (error instanceof AuthenticationError) { console.error('Authentication failed. Please check your API key.'); } else if (error instanceof ValidationError) { console.error('Validation error:', error.message); } else if (error instanceof DatabaseError) { console.error('Database error:', error.message); } else { console.error('Unexpected error:', error.message); } // Log debug information if available if (error.response && error.response.debugLogs) { console.error('\nDebug logs:'); error.response.debugLogs.forEach(log => { console.error(`[${log.level}] ${log.timestamp}: ${log.message}`); }); } process.exit(1); } } // Run the example runNaturalLanguageExample();