nttp 1.4.10 → 1.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +171 -297
  2. package/dist/cli.js +1 -1
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,310 +1,152 @@
1
1
  # NTTP - Natural Text Transfer Protocol
2
2
 
3
- Query databases with natural language using an LLM.
3
+ > Query databases with natural language using an LLM
4
4
 
5
- ## Installation
5
+ ```bash
6
+ npx nttp setup
7
+ npx nttp query "show me 5 users"
8
+ ```
9
+
10
+ ## Quick Start
11
+
12
+ ### 1. Install
6
13
 
7
14
  ```bash
8
15
  npm install nttp
9
16
  ```
10
17
 
11
- ## Quick Start with CLI (Recommended)
18
+ ### 2. Setup
12
19
 
13
- ### For Humans: Interactive Setup
14
-
15
- The easiest way to get started is with our **interactive setup wizard** (powered by [Ink](https://github.com/vadimdemedes/ink) for a beautiful CLI experience):
20
+ **Interactive (recommended):**
16
21
 
17
22
  ```bash
18
23
  npx nttp setup
19
24
  ```
20
25
 
21
- This will:
22
- - ✅ Guide you through database configuration
23
- - ✅ Help you choose an LLM provider
24
- - ✅ Automatically install required dependencies
25
- - ✅ Create your `.env` file
26
- - ✅ Generate example code
27
-
28
- ### For LLM Agents: Non-Interactive Setup
29
-
30
- Perfect for automation, CI/CD, or LLM agents:
26
+ **Non-interactive (for agents/CI):**
31
27
 
32
28
  ```bash
33
29
  npx nttp setup --non-interactive \
34
30
  --database-type=pg \
35
31
  --database-url=postgresql://user:pass@localhost:5432/db \
36
32
  --llm-provider=anthropic \
37
- --llm-api-key=sk-ant-... \
38
- --redis-url=redis://localhost:6379 \
39
- --enable-l2-cache \
40
- --embedding-api-key=sk-...
41
- ```
42
-
43
- **Minimal example (SQLite + Claude):**
44
- ```bash
45
- npx nttp setup --non-interactive \
46
- --database-type=better-sqlite3 \
47
- --database-path=./data.db \
48
- --llm-provider=anthropic \
49
33
  --llm-api-key=sk-ant-...
50
34
  ```
51
35
 
52
- **All available flags:**
53
- - `--database-type` - Required: `pg`, `mysql2`, `better-sqlite3`, `mssql`
54
- - `--database-url` - Required (except for SQLite): Connection URL
55
- - `--database-path` - Required for SQLite: Path to .db file
56
- - `--llm-provider` - Required: `anthropic`, `openai`, `cohere`, `mistral`, `google`
57
- - `--llm-model` - Optional: Model name (auto-selected if omitted)
58
- - `--llm-api-key` - Required: API key for LLM provider
59
- - `--redis-url` - Optional: Redis URL for L1 cache persistence
60
- - `--enable-l2-cache` - Optional: Enable semantic caching
61
- - `--embedding-api-key` - Required if L2 enabled: OpenAI API key
62
-
63
- ### Query Your Database
64
-
65
- ```bash
66
- npx nttp query "show me 5 users"
67
- ```
36
+ ### 3. Query
68
37
 
69
- ### Get Documentation (Great for LLM Agents)
38
+ **CLI:**
70
39
 
71
40
  ```bash
72
- # Show all documentation
73
- npx nttp docs
74
-
75
- # Search documentation
76
- npx nttp docs redis
77
- npx nttp docs "cache configuration"
78
- npx nttp docs setup
79
- npx nttp docs --query "semantic cache"
41
+ npx nttp query "show active users"
42
+ npx nttp query "count pending orders"
43
+ npx nttp query "top 10 products by price"
80
44
  ```
81
45
 
82
- Returns relevant sections instantly - perfect for agents to quickly find information!
83
-
84
- Or use in your code:
46
+ **Code:**
85
47
 
86
48
  ```typescript
87
49
  import { NTTP } from 'nttp';
88
50
 
89
- // Load configuration from .env automatically
90
51
  const nttp = await NTTP.fromEnv();
91
- const result = await nttp.query("show me users");
92
- await nttp.close();
93
- ```
94
-
95
- ## Manual Setup (Advanced)
96
-
97
- ```typescript
98
- import { NTTP } from 'nttp';
99
-
100
- const nttp = new NTTP({
101
- database: {
102
- client: 'pg',
103
- connection: process.env.DATABASE_URL
104
- },
105
- llm: {
106
- provider: 'anthropic',
107
- model: 'claude-sonnet-4-5-20250929',
108
- apiKey: process.env.ANTHROPIC_API_KEY
109
- }
110
- });
111
-
112
- // Initialize (connects to database, builds schema cache)
113
- await nttp.init();
114
-
115
- // Query naturally!
116
- const users = await nttp.query("get all active users");
117
- console.log(users.data); // Array of users
118
-
119
- // Close when done
52
+ const result = await nttp.query("show active users");
53
+ console.log(result.data);
120
54
  await nttp.close();
121
55
  ```
122
56
 
123
- ## API Reference
57
+ ---
124
58
 
125
- ### `new NTTP(config)`
59
+ ## How It Works
126
60
 
127
- Create a new NTTP instance.
61
+ 3-layer caching system optimizes cost and performance:
128
62
 
129
- **Config:**
130
- ```typescript
131
- {
132
- database: {
133
- client: 'pg' | 'mysql2' | 'better-sqlite3' | 'mssql',
134
- connection: string | object // Knex connection config
135
- },
136
- llm: {
137
- provider: 'anthropic' | 'openai' | 'cohere' | 'mistral' | 'google',
138
- model: string, // e.g., 'claude-sonnet-4-5-20250929', 'gpt-4o'
139
- apiKey: string,
140
- maxTokens?: number // Default: 2048
141
- },
142
- cache?: {
143
- l1?: {
144
- enabled?: boolean, // Default: true
145
- maxSize?: number // Default: 1000
146
- },
147
- l2?: {
148
- enabled?: boolean, // Default: false
149
- provider?: 'openai',
150
- model?: string, // e.g., 'text-embedding-3-small'
151
- apiKey?: string,
152
- maxSize?: number, // Default: 500
153
- similarityThreshold?: number // Default: 0.85
154
- },
155
- redis?: {
156
- url: string // Redis connection URL for L1 cache persistence
157
- }
158
- },
159
- limits?: {
160
- maxQueryLength?: number, // Default: 500
161
- defaultLimit?: number, // Default: 100
162
- maxLimit?: number // Default: 1000
163
- }
164
- }
165
63
  ```
166
-
167
- ### `nttp.init()`
168
-
169
- Initialize NTTP. Must be called before querying.
170
-
171
- ```typescript
172
- await nttp.init();
64
+ L1: EXACT Hash match $0 <1ms (in-memory) or ~5ms (Redis)
65
+ L2: SEMANTIC Embedding match $0.0001 80ms
66
+ L3: LLM Claude/GPT $0.01 2-3s
173
67
  ```
174
68
 
175
- ### `nttp.query(query, options?)`
69
+ Most queries hit L1 or L2. Only novel queries reach the LLM.
176
70
 
177
- Execute a natural language query.
71
+ ---
178
72
 
179
- ```typescript
180
- const result = await nttp.query("show pending orders over $500");
181
-
182
- // Result structure:
183
- {
184
- query: string, // Original query
185
- data: any[], // Query results
186
- schemaId: string, // Cache key
187
- cacheHit: boolean, // Was cached?
188
- executionTimeMs: number, // Execution time
189
- intent: {...}, // Parsed intent
190
- sql?: string, // Generated SQL (debug)
191
- params?: any[] // SQL parameters (debug)
192
- }
193
- ```
73
+ ## Features
194
74
 
195
- **Options:**
196
- ```typescript
197
- {
198
- useCache?: boolean, // Use cache (default: true)
199
- forceNewSchema?: boolean // Force new schema (default: false)
200
- }
201
- ```
75
+ - **Natural Language Queries** - "show active users" → `SELECT * FROM users WHERE status = 'active'`
76
+ - **3-Layer Caching** - Exact, semantic, and LLM-generated query caching
77
+ - **Multi-LLM Support** - Claude, GPT-4, Cohere, Mistral, Gemini
78
+ - **Multi-Database** - PostgreSQL, MySQL, SQLite, SQL Server
79
+ - **Redis Persistence** - Optional cache persistence across restarts
80
+ - **Type-Safe** - Full TypeScript support
81
+ - **CLI + SDK** - Use from command line or code
202
82
 
203
- ### `nttp.explain(query)`
83
+ ---
204
84
 
205
- Explain what SQL would be generated without executing.
85
+ ## Documentation
206
86
 
207
- ```typescript
208
- const explanation = await nttp.explain("top 10 customers by revenue");
209
-
210
- // Returns:
211
- {
212
- query: string,
213
- intent: {...},
214
- sql: string,
215
- params: any[],
216
- schemaId: string,
217
- cachedSchema: SchemaDefinition | null
218
- }
219
- ```
87
+ - **Quick Reference:** `npx nttp docs [topic]`
88
+ - **Full Guides:** [/docs](/docs)
220
89
 
221
- ### Schema Management
90
+ ### Guides
222
91
 
223
- ```typescript
224
- // List all cached schemas
225
- const schemas = await nttp.listSchemas();
92
+ - [API Reference](docs/api.md) - Complete API documentation
93
+ - [Caching System](docs/caching.md) - 3-layer cache deep dive
94
+ - [Configuration](docs/configuration.md) - All config options
95
+ - [LLM Models](docs/models.md) - Model selection guide
96
+ - [Examples](docs/examples.md) - Usage examples
97
+ - [Production](docs/production.md) - Deployment best practices
98
+ - [Troubleshooting](docs/troubleshooting.md) - Common issues
226
99
 
227
- // Get specific schema
228
- const schema = await nttp.getSchema(schemaId);
229
-
230
- // Delete schema
231
- await nttp.deleteSchema(schemaId);
232
-
233
- // Pin schema (prevent eviction)
234
- await nttp.pinSchema(schemaId);
235
-
236
- // Unpin schema
237
- await nttp.unpinSchema(schemaId);
238
-
239
- // Get cache statistics
240
- const stats = await nttp.getCacheStats();
241
- ```
242
-
243
- ### Database Inspection
244
-
245
- ```typescript
246
- // Get all tables
247
- const tables = await nttp.getTables();
248
-
249
- // Get table schema
250
- const schema = await nttp.getTableSchema('users');
251
-
252
- // Get schema description (for LLM)
253
- const description = nttp.getSchemaDescription();
254
- ```
100
+ ---
255
101
 
256
102
  ## Example Queries
257
103
 
258
104
  ```typescript
259
- // Simple queries
260
- await nttp.query("get all users");
261
- await nttp.query("show products");
262
- await nttp.query("list orders");
263
-
264
- // Filtered queries
265
- await nttp.query("active users only");
266
- await nttp.query("products in Electronics category");
267
- await nttp.query("pending orders");
105
+ // Simple
106
+ await nttp.query("show users");
107
+ await nttp.query("list products");
268
108
 
269
- // With limits
270
- await nttp.query("top 10 products by price");
271
- await nttp.query("show me 5 recent orders");
109
+ // Filtered
110
+ await nttp.query("active users from California");
111
+ await nttp.query("products under $50");
272
112
 
273
113
  // Aggregations
274
- await nttp.query("count all users");
114
+ await nttp.query("count pending orders");
275
115
  await nttp.query("total revenue by category");
276
- await nttp.query("average order value");
277
116
 
278
- // Complex conditions
279
- await nttp.query("products with 4+ star rating under $100");
280
- await nttp.query("orders from California in the last 30 days");
117
+ // Complex
118
+ await nttp.query("top 10 products by revenue");
281
119
  await nttp.query("users who joined this year");
282
120
  ```
283
121
 
284
- ## Database Support
122
+ ---
285
123
 
286
- NTTP works with any SQL database supported by Knex.js:
124
+ ## Configuration
287
125
 
288
- - **PostgreSQL** - Recommended for production
289
- - **MySQL** - Widely supported
290
- - **SQLite** - Perfect for development
291
- - **SQL Server** - Enterprise-ready
126
+ ### Environment Variables (`.env`)
292
127
 
293
- ## Performance
128
+ ```bash
129
+ # Database
130
+ DATABASE_TYPE=pg
131
+ DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
294
132
 
295
- - **Cache Hit**: <50ms average
296
- - **Cache Miss**: ~2-3s (LLM call)
297
- - **Throughput**: >10,000 req/s (cached)
133
+ # LLM
134
+ LLM_PROVIDER=anthropic
135
+ LLM_MODEL=claude-sonnet-4-5-20250929
136
+ ANTHROPIC_API_KEY=sk-ant-...
298
137
 
299
- ## Cache Persistence with Redis
138
+ # Cache (optional but recommended)
139
+ REDIS_URL=redis://localhost:6379
140
+ OPENAI_API_KEY=sk-... # For L2 semantic cache
141
+ ```
300
142
 
301
- By default, L1 cache uses in-memory storage that resets on each process restart. For production deployments or CLI usage, enable Redis to persist cache across invocations:
143
+ ### Programmatic
302
144
 
303
145
  ```typescript
304
146
  const nttp = new NTTP({
305
147
  database: {
306
148
  client: 'pg',
307
- connection: process.env.DATABASE_URL
149
+ connection: 'postgresql://user:pass@localhost:5432/mydb'
308
150
  },
309
151
  llm: {
310
152
  provider: 'anthropic',
@@ -312,94 +154,101 @@ const nttp = new NTTP({
312
154
  apiKey: process.env.ANTHROPIC_API_KEY
313
155
  },
314
156
  cache: {
315
- redis: {
316
- url: 'redis://localhost:6379'
317
- }
157
+ redis: { url: 'redis://localhost:6379' },
158
+ l2: { enabled: true, provider: 'openai', apiKey: process.env.OPENAI_API_KEY }
318
159
  }
319
160
  });
161
+
162
+ await nttp.init();
320
163
  ```
321
164
 
322
- Or via environment variables with `NTTP.fromEnv()`:
165
+ See [Configuration Guide](docs/configuration.md) for all options.
323
166
 
324
- ```bash
325
- # .env file
326
- REDIS_URL=redis://localhost:6379
327
- ```
167
+ ---
328
168
 
329
- **Benefits:**
330
- - ✅ Cache persists across CLI invocations
331
- - ✅ Shared cache in multi-instance deployments
332
- - ✅ Reduced cold-start latency
333
- - ✅ 24-hour TTL for cached entries
169
+ ## Performance
334
170
 
335
- **Performance with Redis:**
336
- - L1 cache hit: ~5ms (vs <1ms in-memory)
337
- - Still 400x faster than LLM call
338
- - Negligible latency increase for significant persistence benefits
171
+ - **L1 Cache (Exact):** <1ms (in-memory) or ~5ms (Redis) - $0
172
+ - **L2 Cache (Semantic):** ~75ms - ~$0.0001
173
+ - **L3 (LLM):** 2-3s - ~$0.01
174
+ - **Throughput:** >10,000 req/s (cached)
339
175
 
340
- ## CLI Commands
176
+ **Cost Savings:** With caching, 90%+ cost reduction after warm-up.
341
177
 
342
- ### `npx nttp setup`
178
+ ---
343
179
 
344
- Beautiful interactive setup wizard (powered by Ink) with Vercel-inspired DX:
180
+ ## Supported Databases
345
181
 
346
- - Choose database type (PostgreSQL, MySQL, SQLite, SQL Server)
347
- - Configure connection details
348
- - Select LLM provider (Anthropic, OpenAI, Cohere, Mistral, Google)
349
- - Optional: Enable Redis cache (L1 persistence)
350
- - Optional: Enable semantic caching (L2 cache)
351
- - Automatically installs dependencies
352
- - Creates `.env` file
353
- - Generates example code
182
+ - **PostgreSQL** - Recommended for production
183
+ - **MySQL** - Widely supported
184
+ - **SQLite** - Perfect for development
185
+ - **SQL Server** - Enterprise-ready
186
+
187
+ ---
354
188
 
355
- For non-interactive setup (agents/automation), see the section above.
189
+ ## Supported LLMs
356
190
 
357
- ### `npx nttp init`
191
+ - **Anthropic Claude** (recommended) - Best SQL generation
192
+ - **OpenAI GPT** - Fast and reliable
193
+ - **Cohere** - Enterprise support
194
+ - **Mistral** - Open-source preference
195
+ - **Google Gemini** - Multimodal capabilities
358
196
 
359
- Alias for `npx nttp setup`. Quick project initialization.
197
+ See [Model Selection Guide](docs/models.md) for detailed comparison.
360
198
 
361
- ### `npx nttp query <text>`
199
+ ---
362
200
 
363
- Execute a natural language query from the command line:
201
+ ## CLI Commands
364
202
 
365
203
  ```bash
366
- npx nttp query "show me 5 products"
367
- npx nttp query "count active users"
368
- npx nttp query "top 10 customers by revenue" --format json
204
+ # Setup wizard
205
+ npx nttp setup
206
+
207
+ # Query database
208
+ npx nttp query "your question"
209
+ npx nttp query "show users" --format json
210
+
211
+ # Documentation
212
+ npx nttp docs # Show all docs
213
+ npx nttp docs redis # Search for "redis"
214
+ npx nttp docs "semantic cache" # Multi-word search
369
215
  ```
370
216
 
371
- Options:
372
- - `--format <type>` - Output format: `table` (default) or `json`
217
+ ---
373
218
 
374
- ### `npx nttp docs [query]`
219
+ ## API Overview
375
220
 
376
- Show documentation or search for specific topics (perfect for LLM agents):
221
+ ```typescript
222
+ import { NTTP } from 'nttp';
377
223
 
378
- ```bash
379
- # Show all documentation
380
- npx nttp docs
381
-
382
- # Search for specific topics
383
- npx nttp docs redis # Find Redis-related docs
384
- npx nttp docs cache # Find cache documentation
385
- npx nttp docs setup # Find setup instructions
386
- npx nttp docs "l2 semantic" # Multi-word search
387
- npx nttp docs --query "api key" # Alternative syntax
224
+ // Initialize from environment variables
225
+ const nttp = await NTTP.fromEnv();
226
+
227
+ // Execute query
228
+ const result = await nttp.query("show active users");
229
+ console.log(result.data); // Query results
230
+ console.log(result.cacheHit); // true/false
231
+ console.log(result.meta); // Cache metadata
232
+
233
+ // Explain query (without executing)
234
+ const explanation = await nttp.explain("show users");
235
+ console.log(explanation.sql); // Generated SQL
236
+
237
+ // Database inspection
238
+ const tables = await nttp.getTables();
239
+ const schema = await nttp.getTableSchema('users');
240
+
241
+ // Cache management
242
+ const stats = await nttp.getCacheStats();
243
+ await nttp.pinSchema(schemaId);
244
+
245
+ // Clean up
246
+ await nttp.close();
388
247
  ```
389
248
 
390
- **Searchable Topics:**
391
- - `setup` - Setup command and configuration
392
- - `cache` - 3-layer cache system (L1, L2, L3)
393
- - `redis` - Redis persistence configuration
394
- - `query` - Query command and examples
395
- - `api` - Programmatic API usage
396
- - `databases` - Supported databases
397
- - `llm` - LLM providers and models
398
- - `performance` - Performance metrics and optimization
399
- - `troubleshooting` - Common issues and solutions
400
- - `examples` - Example natural language queries
249
+ See [API Reference](docs/api.md) for complete documentation.
401
250
 
402
- **Agent-Friendly Output:** Returns only relevant sections with context, making it easy for LLM agents to quickly find information without parsing full documentation files.
251
+ ---
403
252
 
404
253
  ## Error Handling
405
254
 
@@ -407,18 +256,23 @@ npx nttp docs --query "api key" # Alternative syntax
407
256
  import { IntentParseError, SQLGenerationError, SQLExecutionError } from 'nttp';
408
257
 
409
258
  try {
410
- const result = await nttp.query("ambiguous query");
259
+ const result = await nttp.query("your query");
411
260
  } catch (error) {
412
261
  if (error instanceof IntentParseError) {
413
262
  console.error('Could not understand query');
263
+ console.log('Suggestions:', error.suggestions);
414
264
  } else if (error instanceof SQLGenerationError) {
415
265
  console.error('Could not generate SQL');
416
266
  } else if (error instanceof SQLExecutionError) {
417
- console.error('SQL execution failed');
267
+ console.error('Query execution failed');
418
268
  }
419
269
  }
420
270
  ```
421
271
 
272
+ All errors include helpful suggestions. See [Troubleshooting Guide](docs/troubleshooting.md).
273
+
274
+ ---
275
+
422
276
  ## TypeScript
423
277
 
424
278
  Full TypeScript support with exported types:
@@ -433,6 +287,26 @@ import type {
433
287
  } from 'nttp';
434
288
  ```
435
289
 
290
+ ---
291
+
292
+ ## Examples
293
+
294
+ - [Basic Usage](docs/examples.md#basic-queries)
295
+ - [Express Integration](docs/examples.md#using-with-express)
296
+ - [Next.js Integration](docs/examples.md#using-with-nextjs)
297
+ - [CLI Tools](docs/examples.md#cli-integration)
298
+
299
+ ---
300
+
301
+ ## Links
302
+
303
+ - [GitHub](https://github.com/tylergibbs/nttp)
304
+ - [npm](https://www.npmjs.com/package/nttp)
305
+ - [Issues](https://github.com/tylergibbs/nttp/issues)
306
+ - [Documentation](/docs)
307
+
308
+ ---
309
+
436
310
  ## License
437
311
 
438
312
  MIT
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ const program = new Command();
11
11
  program
12
12
  .name('nttp')
13
13
  .description('Query databases with natural language')
14
- .version('1.4.10');
14
+ .version('1.4.11');
15
15
  program
16
16
  .command('setup')
17
17
  .description('Interactive setup wizard (or use --non-interactive for agents)')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nttp",
3
- "version": "1.4.10",
3
+ "version": "1.4.11",
4
4
  "description": "natural text to query - Query databases with natural language",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",