@horribleprogram/sdk 0.1.6 → 0.1.8

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.
package/README.md CHANGED
@@ -3,18 +3,21 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@horribleprogram/sdk.svg)](https://www.npmjs.com/package/@horribleprogram/sdk)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- Official JavaScript/TypeScript SDK for **Botcierge Intent Classification**.
6
+ Official JavaScript/TypeScript SDK for **Botcierge Intent Classification** and **Company Embeddings Semantic Search & CRUD**.
7
7
 
8
- Starting with `v0.1.5`, the SDK runs **completely locally** on your machine. It loads the `sentence-transformers/all-MiniLM-L12-v2` model using ONNX runtime and performs classification via cosine similarity against a built-in static intents taxonomy.
8
+ Starting with `v0.1.5`, the SDK runs **completely locally** on your machine by default. It loads the `sentence-transformers/all-MiniLM-L12-v2` model using ONNX runtime and performs classification and embedding generation offline.
9
9
 
10
- No API keys, configuration, or active internet connection (after first run) are required.
10
+ ---
11
11
 
12
12
  ## Features
13
13
 
14
- - **Purely Local**: High-speed offline intent classification with zero external API calls or latency.
15
- - **ONNX-Powered**: Powered by `@xenova/transformers` for running `all-MiniLM-L12-v2` locally.
16
- - **TypeScript Native**: Full type safety for class instances, options, and classification outputs.
17
- - **Automatic Caching**: Model weights (approx. 120MB) are downloaded automatically on the first run and cached locally.
14
+ - **Purely Local Intent Classification**: High-speed offline intent classification with zero external API calls or latency.
15
+ - **MongoDB Semantic Search**: Store, manage, and query company records in MongoDB based on semantic similarity.
16
+ - **Flexible Embeddings Backend**: Run embedding generation 100% locally with the ONNX-powered `all-MiniLM-L12-v2` model, or switch to OpenAI's `text-embedding-3-small` API for high-quality remote embeddings if configured.
17
+ - **Parallel Batch Processing**: Fast bulk CSV seeding with parallelizable embedding generation.
18
+ - **TypeScript Native**: Full type safety for configs, company models, and query results.
19
+
20
+ ---
18
21
 
19
22
  ## Installation
20
23
 
@@ -22,8 +25,12 @@ No API keys, configuration, or active internet connection (after first run) are
22
25
  npm install @horribleprogram/sdk
23
26
  ```
24
27
 
28
+ ---
29
+
25
30
  ## Quick Start
26
31
 
32
+ ### 1. Intent Classification (Local Only)
33
+
27
34
  ```typescript
28
35
  import { query_intent } from '@horribleprogram/sdk';
29
36
 
@@ -35,23 +42,55 @@ console.log(result.intent); // share_food
35
42
  console.log(result.confidence); // high
36
43
  ```
37
44
 
38
- ## Usage
45
+ ### 2. Company Embeddings & MongoDB CRUD
39
46
 
40
- ### Simple Usage
41
- The simplest way to use the SDK is through the default helper function:
47
+ Manage companies in MongoDB and perform semantic queries over them:
42
48
 
43
- ```javascript
44
- import { query_intent } from '@horribleprogram/sdk';
49
+ ```typescript
50
+ import { addCompany, queryCompanies, closeConnection } from '@horribleprogram/sdk';
51
+
52
+ const config = {
53
+ uri: 'mongodb://localhost:27017',
54
+ dbName: 'distance_metrics',
55
+ collectionName: 'companies',
56
+ };
57
+
58
+ // 1. Add a company (embeddings are computed automatically)
59
+ await addCompany({
60
+ company_name: 'Antigravity Code Labs',
61
+ website: 'https://antigravity.ai',
62
+ short_description: 'An advanced AI programming assistant team designed by Google DeepMind.',
63
+ product_description: 'We build autonomous agent systems that help users write, debug, and ship software at scale.',
64
+ mapped_function: 'AI Software Development',
65
+ mapped_industry: 'Developer Tools',
66
+ match_keywords: 'ai, programming, agent, coding, deepmind',
67
+ aliases: 'Antigravity AI',
68
+ active: true,
69
+ priority: 'High',
70
+ source: 'manual',
71
+ zone: 'N/A'
72
+ }, config);
73
+
74
+ // 2. Query companies semantically
75
+ const results = await queryCompanies('AI coding assistant by DeepMind', 3, config);
76
+
77
+ for (const match of results) {
78
+ console.log(`${match.company_name} (Similarity: ${match.similarity.toFixed(4)})`);
79
+ // "Antigravity Code Labs (Similarity: 0.7245)"
80
+ }
45
81
 
46
- const result = await query_intent("I'm hungry");
47
- console.log(result);
48
- // { domain: 'FOODLINK', intent: 'request_food', confidence: 'high', scores: { request_food: 0.975 } }
82
+ // 3. Clean up database connection
83
+ await closeConnection();
49
84
  ```
50
85
 
51
- ### Dedicated Instance
86
+ ---
87
+
88
+ ## Usage & Integration Guides
89
+
90
+ ### Intent Classification
52
91
  For class-based architectures, instantiate the `Botcierge` class:
53
92
 
54
- ```javascript
93
+ ```typescript
55
94
  import { Botcierge } from '@horribleprogram/sdk';
56
95
 
57
96
  const client = new Botcierge();
@@ -60,20 +99,122 @@ console.log(result);
60
99
  // { domain: 'SHOP_SAVVY', intent: 'add_item', confidence: 'high', scores: { add_item: 0.884 } }
61
100
  ```
62
101
 
102
+ ### Company Embedding Management (`CompanyEmbeddingManager`)
103
+ For long-lived database operations or custom integration, use the `CompanyEmbeddingManager` class directly.
104
+
105
+ #### Basic Usage (Local MongoDB)
106
+ ```typescript
107
+ import { CompanyEmbeddingManager } from '@horribleprogram/sdk';
108
+
109
+ const manager = new CompanyEmbeddingManager({
110
+ uri: 'mongodb://localhost:27017',
111
+ dbName: 'distance_metrics',
112
+ collectionName: 'companies',
113
+ // Use OpenAI instead of local model if key is provided:
114
+ openAIApiKey: process.env.OPENAI_API_KEY,
115
+ preferOpenAI: true
116
+ });
117
+
118
+ // Perform database operations
119
+ const col = await manager.getCollection();
120
+ const count = await col.countDocuments();
121
+ console.log(`Connected to local database. Document count: ${count}`);
122
+
123
+ await manager.disconnect();
124
+ ```
125
+
126
+ #### MongoDB Atlas Cluster Usage (Secure Cloud Connection)
127
+ The SDK natively supports MongoDB Atlas secure clusters via `mongodb+srv://` URIs. Under Node.js, the `mongodb` v7 driver handles DNS resolving, SSL/TLS, and authentication automatically out-of-the-box, with no extra external dependencies or configuration required.
128
+
129
+ Simply provide your Atlas connection string and specify options like `serverApi` in the `mongoOptions` object (which is passed directly to the internal `MongoClient` constructor):
130
+
131
+ ```typescript
132
+ import { CompanyEmbeddingManager } from '@horribleprogram/sdk';
133
+
134
+ const manager = new CompanyEmbeddingManager({
135
+ uri: 'mongodb+srv://<username>:<password>@cluster0.xxxx.mongodb.net/myDatabase?retryWrites=true&w=majority',
136
+ dbName: 'distance_metrics',
137
+ // Custom options passed directly to the MongoClient constructor:
138
+ mongoOptions: {
139
+ serverApi: {
140
+ version: '1' as any, // ServerApiVersion.v1 (ensures long-term API compatibility)
141
+ strict: true,
142
+ deprecationErrors: true,
143
+ }
144
+ }
145
+ });
146
+
147
+ // Perform operations on MongoDB Atlas
148
+ const col = await manager.getCollection();
149
+ const count = await col.countDocuments();
150
+ console.log(`Connected to MongoDB Atlas! Document count: ${count}`);
151
+
152
+ await manager.disconnect();
153
+ ```
154
+
155
+ #### Seeding Companies from CSV
156
+ You can batch-onboard/seed companies directly from a CSV file. It reads the CSV, generates embeddings in parallel batches, and inserts/overwrites the MongoDB collection.
157
+
158
+ ```typescript
159
+ import { seedCompanies, closeConnection } from '@horribleprogram/sdk';
160
+
161
+ async function seed() {
162
+ const count = await seedCompanies('./companies.csv', {
163
+ uri: 'mongodb://localhost:27017',
164
+ dbName: 'distance_metrics',
165
+ });
166
+ console.log(`Seeded ${count} companies!`);
167
+ await closeConnection();
168
+ }
169
+ ```
170
+
171
+ ---
172
+
63
173
  ## API Reference
64
174
 
65
- ### `query_intent(utterance: string): Promise<IntentResult>`
175
+ ### Intent Classification
176
+
177
+ #### `query_intent(utterance: string): Promise<IntentResult>`
66
178
  Classifies a string using the default local instance.
67
179
 
68
- ### `class Botcierge`
69
- #### `constructor(config?: BotciergeConfig)`
70
- Creates a new intent classification instance.
71
- - `config`: Currently empty (reserved for future options).
180
+ #### `class Botcierge`
181
+ * `constructor(config?: BotciergeConfig)`
182
+ * `query_intent(utterance: string): Promise<IntentResult>`
72
183
 
73
- #### `query_intent(utterance: string): Promise<IntentResult>`
74
- Classifies a string locally into a specific domain and intent.
184
+ ---
185
+
186
+ ### Company Embeddings & CRUD
187
+
188
+ #### `seedCompanies(csvPath: string, config?: MongoEmbeddingConfig): Promise<number>`
189
+ Seeds the MongoDB collection with companies from a CSV file. Returns the number of seeded records.
190
+
191
+ #### `addCompany(company: Omit<Company, "embedding"> & { embedding?: number[] }, config?: MongoEmbeddingConfig): Promise<void>`
192
+ Upserts a company record in the database. If no `embedding` is provided, it is automatically computed based on the company's fields.
193
+
194
+ #### `removeCompany(companyName: string, config?: MongoEmbeddingConfig): Promise<boolean>`
195
+ Deletes a company by name (case-insensitive regular expression match). Returns `true` if a record was deleted, `false` otherwise.
196
+
197
+ #### `queryCompanies(prompt: string, limit?: number, config?: MongoEmbeddingConfig): Promise<(Company & { similarity: number })[]>`
198
+ Performs a vector search over the MongoDB database by calculating the cosine similarity of the company embeddings against the input prompt embedding. Returns list of companies sorted descending by `similarity`.
199
+
200
+ #### `closeConnection(): Promise<void>`
201
+ Disconnects and clears the default active database manager.
202
+
203
+ #### `class CompanyEmbeddingManager`
204
+ * `constructor(config?: MongoEmbeddingConfig)`
205
+ * `connect(): Promise<MongoClient>`
206
+ * `disconnect(): Promise<void>`
207
+ * `getCollection(): Promise<Collection<Company>>`
208
+ * `getEmbedding(text: string): Promise<number[]>`
209
+ * `getEmbeddings(texts: string[]): Promise<number[][]>`
210
+ * `addCompany(company: Company): Promise<void>`
211
+ * `removeCompany(companyName: string): Promise<boolean>`
212
+ * `queryCompanies(prompt: string, limit?: number): Promise<(Company & { similarity: number })[]>`
213
+ * `seedFromCSV(csvPath: string): Promise<number>`
75
214
 
76
- ### Types
215
+ ---
216
+
217
+ ## Types
77
218
 
78
219
  #### `IntentResult`
79
220
  ```typescript
@@ -85,6 +226,40 @@ interface IntentResult {
85
226
  }
86
227
  ```
87
228
 
229
+ #### `MongoEmbeddingConfig`
230
+ ```typescript
231
+ interface MongoEmbeddingConfig {
232
+ uri?: string;
233
+ dbName?: string;
234
+ collectionName?: string;
235
+ openAIApiKey?: string;
236
+ preferOpenAI?: boolean;
237
+ mongoOptions?: MongoClientOptions; // Passed directly to MongoClient constructor
238
+ }
239
+ ```
240
+
241
+ #### `Company`
242
+ ```typescript
243
+ interface Company {
244
+ company_name: string;
245
+ website: string;
246
+ short_description: string;
247
+ product_description: string;
248
+ mapped_function: string;
249
+ mapped_industry: string;
250
+ match_keywords: string;
251
+ aliases: string;
252
+ active: boolean | string;
253
+ priority: string;
254
+ source: string;
255
+ zone: string;
256
+ embedding?: number[];
257
+ [key: string]: any;
258
+ }
259
+ ```
260
+
261
+ ---
262
+
88
263
  ## Development
89
264
 
90
265
  To build and test the SDK locally:
@@ -94,13 +269,15 @@ To build and test the SDK locally:
94
269
  cd sdk-js
95
270
  npm install
96
271
 
97
- # Run unit tests
272
+ # Run unit tests (runs MongoDB tests against mongodb://localhost:27017)
98
273
  npm test
99
274
 
100
275
  # Build files (CJS + ESM + DTS)
101
276
  npm run build
102
277
  ```
103
278
 
279
+ ---
280
+
104
281
  ## License
105
282
 
106
283
  MIT © [horribleprogram](https://npmjs.com/~horribleprogram)