UNPKG

snake-query

Version:
460 lines (373 loc) 10.1 kB
# SnakeQuery Node.js SDK Documentation The official Node.js SDK for SnakeQuery - Transform natural language into structured data queries with AI. ## 🚀 Quick Start ### Installation ```bash npm install snake-query ``` ### Basic Usage ```javascript const SnakeQuery = require('snake-query'); const { SchemaBuilder } = SnakeQuery; // Initialize client with your API key const client = new SnakeQuery('your-api-key-here'); // Query with structured response const result = await client.query({ query: 'Find products under $100', fetchUrl: 'https://api.example.com/products', responseSchema: SchemaBuilder.create() .array( SchemaBuilder.create() .object() .addStringProperty('name') .addNumberProperty('price', { minimum: 0 }) .required(['name', 'price']) .build() ) .build() }); console.log(result.response); // Structured data array console.log(result.usageCount); // Token usage info ``` ## 📖 Table of Contents - [Authentication](#authentication) - [Core Concepts](#core-concepts) - [API Reference](#api-reference) - [Schema Building](#schema-building) - [Examples](#examples) - [Error Handling](#error-handling) - [Best Practices](#best-practices) ## 🔐 Authentication Get your API key from the [SnakeQuery Dashboard](https://app.snakequery.com) and initialize the client: ```javascript const client = new SnakeQuery('sk-1234567890abcdef...'); ``` ### Environment Variables (Recommended) ```bash export SNAKE_QUERY_API_KEY="sk-1234567890abcdef..." ``` ```javascript const client = new SnakeQuery(process.env.SNAKE_QUERY_API_KEY); ``` ## 💡 Core Concepts ### Natural Language Queries SnakeQuery converts natural language into structured data operations: ```javascript // Instead of complex filtering logic const expensiveProducts = data.filter(p => p.price > 500 && p.category === 'electronics'); // Use natural language const result = await client.query({ query: 'Find electronics products that cost more than $500', data: products }); ``` ### Structured Responses Control output format with schemas for consistent, type-safe results: ```javascript const schema = SchemaBuilder.create() .array( SchemaBuilder.create() .object() .addStringProperty('productName') .addNumberProperty('price', { minimum: 0 }) .addStringProperty('category') .required(['productName', 'price']) .build() ) .build(); ``` ## 📚 API Reference ### SnakeQuery Class #### Constructor ```typescript new SnakeQuery(apiKey: string) ``` #### Methods ##### `query(options: QueryOptions): Promise<SnakeQueryResponse>` Main method for all query operations. **Parameters:** ```typescript interface QueryOptions { query: string; // Natural language query data?: any; // Direct data to query (optional) fetchUrl?: string; // URL to fetch data from (optional) responseSchema?: Schema; // Response structure schema (optional) debug?: boolean; // Enable debug mode (optional) } ``` **Response:** ```typescript interface SnakeQueryResponse<T = any> { usageCount: UsageCount; // Token usage information response: T; // Query results } interface UsageCount { inputTokens: number; outputTokens: number; totalTokens: number; } ``` ## 🏗️ Schema Building ### SchemaBuilder Class Create structured response schemas using fluent API: #### Basic Types ```javascript const { SchemaBuilder } = SnakeQuery; // String field SchemaBuilder.create() .string({ minLength: 1, maxLength: 100 }) .build(); // Number field SchemaBuilder.create() .number({ minimum: 0, maximum: 1000 }) .build(); // Boolean field SchemaBuilder.create() .boolean() .build(); ``` #### Objects ```javascript const userSchema = SchemaBuilder.create() .object() .addStringProperty('name') .addNumberProperty('age', { minimum: 0 }) .addStringProperty('email') .required(['name', 'age']) .build(); ``` #### Arrays ```javascript const usersArraySchema = SchemaBuilder.create() .array(userSchema) .build(); // Or inline const productsSchema = SchemaBuilder.create() .array( SchemaBuilder.create() .object() .addStringProperty('title') .addNumberProperty('price', { minimum: 0 }) .required(['title', 'price']) .build() ) .build(); ``` #### Nested Objects ```javascript const orderSchema = SchemaBuilder.create() .object() .addStringProperty('orderId') .addObjectProperty('customer', { name: { type: 'string' }, email: { type: 'string' } }) .addArrayProperty('items', { type: 'object', properties: { product: { type: 'string' }, quantity: { type: 'number', minimum: 1 }, price: { type: 'number', minimum: 0 } } }) .required(['orderId', 'customer', 'items']) .build(); ``` ## 💻 Examples ### Query Direct Data ```javascript const products = [ { name: 'iPhone', price: 999, category: 'electronics' }, { name: 'Shoes', price: 129, category: 'fashion' }, { name: 'Book', price: 19, category: 'books' } ]; const result = await client.query({ query: 'Find products under $500 and group by category', data: products, responseSchema: SchemaBuilder.create() .array( SchemaBuilder.create() .object() .addStringProperty('category') .addArrayProperty('products', { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }) .required(['category', 'products']) .build() ) .build() }); ``` ### Query External API ```javascript const result = await client.query({ query: 'Show me the top 5 most expensive products with their details', fetchUrl: 'https://api.store.com/products', responseSchema: SchemaBuilder.create() .array( SchemaBuilder.create() .object() .addStringProperty('productName') .addNumberProperty('price', { minimum: 0 }) .addStringProperty('description') .addStringProperty('category') .required(['productName', 'price']) .build() ) .build() }); ``` ### Complex Analytics ```javascript const result = await client.query({ query: 'Calculate average order value by month and show trends', fetchUrl: 'https://api.store.com/orders', responseSchema: SchemaBuilder.create() .object() .addArrayProperty('monthlyStats', { type: 'object', properties: { month: { type: 'string' }, averageOrderValue: { type: 'number', minimum: 0 }, totalOrders: { type: 'number', minimum: 0 }, revenue: { type: 'number', minimum: 0 } } }) .addObjectProperty('trends', { direction: { type: 'string' }, percentageChange: { type: 'number' }, insight: { type: 'string' } }) .required(['monthlyStats']) .build() }); ``` ## ⚠️ Error Handling ### Common Errors ```javascript try { const result = await client.query({ query: 'Analyze sales data', fetchUrl: 'https://api.example.com/sales' }); } catch (error) { switch (error.status) { case 401: console.error('Invalid API key'); break; case 402: console.error('Insufficient credits'); break; case 500: console.error('Server error:', error.message); break; case 504: console.error('Request timeout - try a simpler query'); break; default: console.error('Unknown error:', error.message); } } ``` ### Network Errors ```javascript try { const result = await client.query(options); } catch (error) { if (error.message.includes('Network error')) { console.error('Check your internet connection'); } else if (error.message.includes('timeout')) { console.error('Query took too long - try optimizing your request'); } } ``` ## ✨ Best Practices ### 1. Always Use Schemas for Production ```javascript // ❌ Don't rely on free-form responses const result = await client.query({ query: 'Get user data', data: users }); // ✅ Use structured schemas const result = await client.query({ query: 'Get user data', data: users, responseSchema: userSchema }); ``` ### 2. Environment Variables for API Keys ```javascript // ❌ Don't hardcode API keys const client = new SnakeQuery('sk-1234567890abcdef...'); // ✅ Use environment variables const client = new SnakeQuery(process.env.SNAKE_QUERY_API_KEY); ``` ### 3. Handle Errors Gracefully ```javascript // ✅ Always wrap in try-catch try { const result = await client.query(options); return result.response; } catch (error) { console.error('Query failed:', error.message); return null; // or default value } ``` ### 4. Optimize Queries for Performance ```javascript // ✅ Be specific in your queries const result = await client.query({ query: 'Find the 5 most recent orders with status "completed"', fetchUrl: url, responseSchema: schema }); // ❌ Avoid overly broad queries const result = await client.query({ query: 'Give me everything about all orders', fetchUrl: url }); ``` ### 5. Use Appropriate Data Sources ```javascript // ✅ For small datasets, use direct data const result = await client.query({ query: 'Find users by department', data: smallUserList, responseSchema: schema }); // ✅ For large datasets, use URL endpoints const result = await client.query({ query: 'Analyze sales trends', fetchUrl: 'https://api.company.com/sales/big-data', responseSchema: schema }); ``` ## 📊 Response Format All successful queries return: ```typescript { usageCount: { inputTokens: 150, outputTokens: 75, totalTokens: 225 }, response: [ // Your structured data here { "productName": "iPhone 14", "price": 999, "category": "Electronics" } ] } ``` ## 🔗 Additional Resources - [SnakeQuery Dashboard](https://app.snakequery.com) - [GitHub Repository](https://github.com/snakequery/snake-query-node-sdk) ## 📝 License MIT License - see [LICENSE](../LICENSE) file for details.