conare 0.26.1 → 0.27.0

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
@@ -42,6 +42,22 @@ A key acts for its own organization. A multi-organization key (made in the conso
42
42
  each organization it names) acts for any of them: make one client per organization with
43
43
  `organization`. Without it, such a key answers 400 on every call but `organizations()`.
44
44
 
45
+ ### Organizations (a customer key)
46
+
47
+ One organization per company you serve, each with its own namespaces, keys, sources, usage and limits. A
48
+ customer key (made by an admin in the console, in your customer's default organization) manages them:
49
+
50
+ ```ts
51
+ const platform = new Conare({ apiKey: CUSTOMER_KEY })
52
+ const acme = await platform.createOrganization({ name: "Acme", externalId: "acme" }) // same externalId again: the same one
53
+ const { secret } = await new Conare({ apiKey: CUSTOMER_KEY, organization: acme.id }).createKey({ name: "acme" })
54
+ // Acme's traffic runs on `secret`, which reaches Acme's organization alone.
55
+ await platform.organizations({ externalId: "acme" }) // every organization of your customer, or the one with this id
56
+ await platform.spendByOrganization() // this month's bill by organization: { total, rows: [{ id, name, externalId, charges }] }
57
+ await platform.renameOrganization(acme.id, "Acme Capital")
58
+ await platform.deleteOrganization(acme.id) // 409 until its namespaces and sources are deleted
59
+ ```
60
+
45
61
  ### Namespaces and documents
46
62
 
47
63
  ```ts
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.26.1";
1
+ export declare const VERSION = "0.27.0";
2
2
  /** A metadata value: string, number, boolean or an array of strings. */
3
3
  export type MetadataValue = string | number | boolean | string[];
4
4
  export type Metadata = Record<string, MetadataValue>;
@@ -75,6 +75,13 @@ export interface DocumentInput {
75
75
  * the stored `seq` stays.
76
76
  */
77
77
  seq?: number;
78
+ /**
79
+ * An image of the document, such as the page its text was read from: standard base64 of a PNG or JPEG (at most
80
+ * 4 MiB, 40 megapixels). It is embedded together with the text, so a query finds the document by what it shows as
81
+ * well as what it says, and it is not stored. Organizations with images enabled only (else a ConareError 400
82
+ * `images_not_enabled`).
83
+ */
84
+ image?: string;
78
85
  }
79
86
  /** What a write did with one document. */
80
87
  export type WriteOutcome = "created" | "updated" | "unchanged" | "stale";
@@ -93,6 +100,8 @@ export interface WriteResult {
93
100
  chunks?: number;
94
101
  chunksEmbedded?: number;
95
102
  storedSeq?: number;
103
+ /** The document's `image` was embedded with its text (absent without one, or where its namespace reads none). */
104
+ imageEmbedded?: boolean;
96
105
  }
97
106
  /** A file type `uploadFile` can declare: the file is read as that type (`jpg` and `tif` are accepted too). */
98
107
  export type FileType = "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "png" | "jpeg" | "webp" | "tiff" | "gif" | "bmp" | "heic";
@@ -220,6 +229,11 @@ export interface FileUpload {
220
229
  imagesWithoutText: PictureWithoutText[];
221
230
  /** PDF pages with no text even after OCR (blank, or OCR could not read them): not stored. */
222
231
  pagesWithoutText: number[];
232
+ /**
233
+ * PDF or image pages embedded as their image together with their text (organizations with images enabled; empty
234
+ * otherwise). A query result of such a page carries `imageUrl`.
235
+ */
236
+ pagesWithImage: number[];
223
237
  /** Pages waiting for OCR to try them again (`state: "ocr"`). */
224
238
  ocrPending: number[];
225
239
  /**
@@ -280,6 +294,11 @@ export interface QueryResult {
280
294
  metadata: Metadata;
281
295
  /** The document's user, when it has one. */
282
296
  user?: string;
297
+ /**
298
+ * A page of an uploaded file embedded with its image: the API path of that image (a JPEG), relative to the API's
299
+ * base URL; GET it with your key (`Authorization: Bearer`), from your server or through your own proxy for a browser.
300
+ */
301
+ image_url?: string;
283
302
  }
284
303
  /** What a query fuses: the embedding model and BM25 keywords. */
285
304
  export type Retriever = "vector" | "keyword";
@@ -370,7 +389,7 @@ export interface Source {
370
389
  namespace: string;
371
390
  status: SourceStatus;
372
391
  error: string | null;
373
- documents: number;
392
+ documents: number | null;
374
393
  lastSyncedAt: Date | null;
375
394
  createdAt: Date;
376
395
  /** While syncing: records read from the app so far in the run in flight. */
@@ -422,7 +441,7 @@ export interface CustomSource {
422
441
  user: string | null;
423
442
  name: string | null;
424
443
  status: "active" | "deleting" | "deleted";
425
- /** `degraded`: the last snapshot was held or blocked, or the document count was corrected. */
444
+ /** `degraded`: the last snapshot was held or blocked. */
426
445
  health: "ok" | "degraded" | "failing";
427
446
  display: {
428
447
  state: string;
@@ -434,7 +453,7 @@ export interface CustomSource {
434
453
  runId: string | null;
435
454
  phase: string | null;
436
455
  };
437
- documents: number;
456
+ documents: number | null;
438
457
  documentsVerifiedAt: Date | null;
439
458
  createdAt: Date;
440
459
  updatedAt: Date;
@@ -547,6 +566,35 @@ export interface ConareOptions {
547
566
  */
548
567
  gzip?: boolean;
549
568
  }
569
+ /** A meter of the bill (`spendByOrganization()`); `vector` is the vector database. */
570
+ export type OrganizationMeter = "queries" | "indexing" | "embedding" | "reranking" | "storage" | "documents" | "sync" | "vector";
571
+ /** A month's charges by meter, in micro-dollars (1 USD = 1,000,000). */
572
+ export type OrganizationCharges = Record<OrganizationMeter | "total", number>;
573
+ /** This month's spend by organization (`spendByOrganization()`). */
574
+ export interface OrganizationSpend {
575
+ /** The month the charges are for, `YYYY-MM` (UTC). */
576
+ month: string;
577
+ /** Every organization of your customer, and how many cost anything. */
578
+ count: number;
579
+ active: number;
580
+ /** Every organization's charges, whatever the search. */
581
+ total: OrganizationCharges;
582
+ /** The ten most expensive organizations' part of the total, 0 to 1. */
583
+ top10Share: number;
584
+ /** How many organizations `q` kept. */
585
+ matched: number;
586
+ rows: Array<{
587
+ id: string;
588
+ name: string;
589
+ externalId?: string;
590
+ charges: OrganizationCharges;
591
+ }>;
592
+ /** The matches after this page, as one sum. */
593
+ rest: {
594
+ count: number;
595
+ charges: OrganizationCharges;
596
+ };
597
+ }
550
598
  /** An organization the key acts for (`organizations()`). */
551
599
  export interface Organization {
552
600
  /** The value of the `organization` option. */
@@ -554,6 +602,29 @@ export interface Organization {
554
602
  /** Empty when it cannot be read right now. */
555
603
  name: string;
556
604
  role: "admin" | "member";
605
+ /** Your own id for it, given when a customer key made it (`createOrganization()`). */
606
+ externalId?: string;
607
+ /** Your customer's default organization (a customer key's `organizations()`). */
608
+ default?: boolean;
609
+ /** When it was made (a customer key's `organizations()`). */
610
+ createdAt?: string;
611
+ }
612
+ /** An API key (`createKey()`, `keys()`). Its secret is shown once, by `createKey()`. */
613
+ export interface ApiKey {
614
+ id: string;
615
+ name: string;
616
+ /** `sk-conare-…` and the secret's last four characters. */
617
+ hint: string;
618
+ /** The key's scope; null reaches every namespace. */
619
+ namespaces: string[] | null;
620
+ modelsOnly: boolean;
621
+ /** The organizations it acts for, its own first. */
622
+ organizations: string[];
623
+ createdAt: string;
624
+ lastUsedAt: string | null;
625
+ expiresAt: string | null;
626
+ /** A customer key: it makes your organizations and acts in any of them. */
627
+ customer: boolean;
557
628
  }
558
629
  export interface RequestOptions {
559
630
  signal?: AbortSignal;
@@ -616,9 +687,62 @@ export declare class Conare {
616
687
  }): Promise<NamespaceInfo[]>;
617
688
  /**
618
689
  * The organizations this key acts for, its own first. A multi-organization key lists each other one
619
- * it still acts for; pass an `id` as the `organization` option of a client to act for it.
690
+ * it still acts for; pass an `id` as the `organization` option of a client to act for it. A
691
+ * customer key lists every organization of your customer (every page), or with `externalId` the
692
+ * one made with it.
693
+ */
694
+ organizations(options?: RequestOptions & {
695
+ externalId?: string;
696
+ }): Promise<Organization[]>;
697
+ /**
698
+ * A new organization of your customer, with a customer key: one per company you serve, with its own
699
+ * namespaces, keys, sources, usage and limits. `externalId` is your own id for it, unique within your
700
+ * customer: a create with one already used answers that organization and makes none. Mint the key its
701
+ * traffic runs on with `createKey()` on a client whose `organization` is its `id`.
702
+ */
703
+ createOrganization(input: {
704
+ name: string;
705
+ externalId?: string;
706
+ }, options?: RequestOptions): Promise<Organization>;
707
+ /** One organization of your customer, with a customer key. */
708
+ getOrganization(id: string, options?: RequestOptions): Promise<Organization>;
709
+ /** Renames one organization of your customer, with a customer key. */
710
+ renameOrganization(id: string, name: string, options?: RequestOptions): Promise<Organization>;
711
+ /**
712
+ * Deletes one organization of your customer for good, with a customer key. Delete its namespaces and
713
+ * sources first (a client whose `organization` is its `id`): until then it answers 409 `conflict`.
714
+ */
715
+ deleteOrganization(id: string, options?: RequestOptions): Promise<void>;
716
+ /**
717
+ * What each organization of your customer cost this month (UTC), by meter, with a customer key: the
718
+ * breakdown of your one bill. Amounts are micro-dollars (1 USD = 1,000,000). Rows come the most
719
+ * expensive first (`sort` picks the meter); `q` keeps the organizations whose name or id holds it;
720
+ * `limit` (10, at most 200) and `offset` page them, and `rest` sums the matches after the page.
721
+ */
722
+ spendByOrganization(input?: {
723
+ sort?: OrganizationMeter | "total";
724
+ q?: string;
725
+ limit?: number;
726
+ offset?: number;
727
+ }, options?: RequestOptions): Promise<OrganizationSpend>;
728
+ /**
729
+ * A key of this client's `organization`, with a customer key: the key a company's traffic runs on,
730
+ * reaching that organization alone. `namespaces` scopes it (exact names, or prefixes ending in `*`),
731
+ * `modelsOnly` keeps it to the model routes, `expiresAt` ends it. The secret is in this answer only.
620
732
  */
621
- organizations(options?: RequestOptions): Promise<Organization[]>;
733
+ createKey(input: {
734
+ name: string;
735
+ namespaces?: string[];
736
+ modelsOnly?: boolean;
737
+ expiresAt?: Date | string;
738
+ }, options?: RequestOptions): Promise<{
739
+ key: ApiKey;
740
+ secret: string;
741
+ }>;
742
+ /** The keys of this client's `organization`, with a customer key. */
743
+ keys(options?: RequestOptions): Promise<ApiKey[]>;
744
+ /** Revokes a key of this client's `organization`, with a customer key. */
745
+ revokeKey(id: string, options?: RequestOptions): Promise<void>;
622
746
  /**
623
747
  * Embed texts. Use type "query" for search queries and "document" (default) for stored text.
624
748
  * `outputDtype: "int8"` returns each vector as int8 values and one scale (vector ≈ values × scale),
@@ -663,8 +787,7 @@ export declare class Namespace {
663
787
  * Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
664
788
  * (one of your organization's models from `GET /models`) needs this: a write creates one with the
665
789
  * default model. Its model never changes: creating it again with another one is a 409. Returns
666
- * the model that embeds it. `regexIndex` makes `grep` and `$text` filters answer from an index,
667
- * chosen once: over a namespace that exists without one it is a 409.
790
+ * the model that embeds it. `regexIndex` is ignored: every namespace has the text index.
668
791
  */
669
792
  create(options?: RequestOptions & {
670
793
  embeddingModel?: string;
@@ -726,7 +849,7 @@ export declare class Namespace {
726
849
  /**
727
850
  * The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
728
851
  * with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
729
- * to go on; a namespace created without `regexIndex` reads its passages, so a page can stop short of `limit`.
852
+ * to go on; while a namespace's text index is still building, a page can stop short of `limit`.
730
853
  */
731
854
  grep(pattern: string | FuzzyText, options?: GrepOptions): Promise<GrepPage>;
732
855
  /**
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.26.1";
2
+ export const VERSION = "0.27.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  /** Above the API's 110 s deadline for a write: a call given up sooner is retried while the first still runs. */
@@ -59,6 +59,7 @@ function toFileUpload(body) {
59
59
  imagesOcr: body.images_ocr ?? 0,
60
60
  imagesWithoutText: body.images_without_text ?? [],
61
61
  pagesWithoutText: body.pages_without_text ?? [],
62
+ pagesWithImage: body.pages_with_image ?? [],
62
63
  ocrPending: body.ocr_pending ?? [],
63
64
  };
64
65
  }
@@ -66,6 +67,30 @@ function toFileUpload(body) {
66
67
  export function dequantize(embeddings) {
67
68
  return embeddings.values.map((v, i) => Array.from(v, (x) => x * (embeddings.scales[i] ?? 0)));
68
69
  }
70
+ function toOrganization(o) {
71
+ const out = { id: o.id, name: o.name, role: o.role };
72
+ if (o.external_id)
73
+ out.externalId = o.external_id;
74
+ if (o.default)
75
+ out.default = true;
76
+ if (o.created_at)
77
+ out.createdAt = o.created_at;
78
+ return out;
79
+ }
80
+ function toKey(k) {
81
+ return {
82
+ id: k.id,
83
+ name: k.name,
84
+ hint: k.hint,
85
+ namespaces: k.namespaces,
86
+ modelsOnly: k.models_only,
87
+ organizations: k.organizations,
88
+ createdAt: k.created_at,
89
+ lastUsedAt: k.last_used_at,
90
+ expiresAt: k.expires_at,
91
+ customer: k.customer ?? false,
92
+ };
93
+ }
69
94
  // ---- Errors ----------------------------------------------------------------
70
95
  /** Every failure the SDK throws. `status` is 0 when no response arrived. */
71
96
  export class ConareError extends Error {
@@ -180,11 +205,108 @@ export class Conare {
180
205
  }
181
206
  /**
182
207
  * The organizations this key acts for, its own first. A multi-organization key lists each other one
183
- * it still acts for; pass an `id` as the `organization` option of a client to act for it.
208
+ * it still acts for; pass an `id` as the `organization` option of a client to act for it. A
209
+ * customer key lists every organization of your customer (every page), or with `externalId` the
210
+ * one made with it.
184
211
  */
185
212
  async organizations(options = {}) {
186
- const body = await this.request("GET", "/organizations", undefined, options);
187
- return body.organizations;
213
+ const out = [];
214
+ let cursor = null;
215
+ do {
216
+ const query = new URLSearchParams();
217
+ if (options.externalId)
218
+ query.set("external_id", options.externalId);
219
+ if (cursor)
220
+ query.set("cursor", cursor);
221
+ const path = query.size ? `/organizations?${query}` : "/organizations";
222
+ const body = await this.request("GET", path, undefined, options);
223
+ out.push(...body.organizations.map(toOrganization));
224
+ cursor = body.next_cursor ?? null;
225
+ } while (cursor);
226
+ return out;
227
+ }
228
+ /**
229
+ * A new organization of your customer, with a customer key: one per company you serve, with its own
230
+ * namespaces, keys, sources, usage and limits. `externalId` is your own id for it, unique within your
231
+ * customer: a create with one already used answers that organization and makes none. Mint the key its
232
+ * traffic runs on with `createKey()` on a client whose `organization` is its `id`.
233
+ */
234
+ async createOrganization(input, options = {}) {
235
+ const request = { name: input.name };
236
+ if (input.externalId !== undefined)
237
+ request.external_id = input.externalId;
238
+ const body = await this.request("POST", "/organizations", request, options);
239
+ return toOrganization(body.organization);
240
+ }
241
+ /** One organization of your customer, with a customer key. */
242
+ async getOrganization(id, options = {}) {
243
+ const body = await this.request("GET", `/organizations/${encodeURIComponent(id)}`, undefined, options);
244
+ return toOrganization(body.organization);
245
+ }
246
+ /** Renames one organization of your customer, with a customer key. */
247
+ async renameOrganization(id, name, options = {}) {
248
+ const body = await this.request("PATCH", `/organizations/${encodeURIComponent(id)}`, { name }, options);
249
+ return toOrganization(body.organization);
250
+ }
251
+ /**
252
+ * Deletes one organization of your customer for good, with a customer key. Delete its namespaces and
253
+ * sources first (a client whose `organization` is its `id`): until then it answers 409 `conflict`.
254
+ */
255
+ async deleteOrganization(id, options = {}) {
256
+ await this.request("DELETE", `/organizations/${encodeURIComponent(id)}`, undefined, options);
257
+ }
258
+ /**
259
+ * What each organization of your customer cost this month (UTC), by meter, with a customer key: the
260
+ * breakdown of your one bill. Amounts are micro-dollars (1 USD = 1,000,000). Rows come the most
261
+ * expensive first (`sort` picks the meter); `q` keeps the organizations whose name or id holds it;
262
+ * `limit` (10, at most 200) and `offset` page them, and `rest` sums the matches after the page.
263
+ */
264
+ async spendByOrganization(input = {}, options = {}) {
265
+ const query = new URLSearchParams();
266
+ if (input.sort)
267
+ query.set("sort", input.sort);
268
+ if (input.q)
269
+ query.set("q", input.q);
270
+ if (input.limit !== undefined)
271
+ query.set("limit", String(input.limit));
272
+ if (input.offset !== undefined)
273
+ query.set("offset", String(input.offset));
274
+ const body = await this.request("GET", query.size ? `/billing/organizations?${query}` : "/billing/organizations", undefined, options);
275
+ return {
276
+ month: body.month,
277
+ count: body.count,
278
+ active: body.active,
279
+ total: body.total,
280
+ top10Share: body.top10_share,
281
+ matched: body.matched,
282
+ rows: body.rows.map((r) => ({ id: r.id, name: r.name, ...(r.external_id ? { externalId: r.external_id } : {}), charges: r.charges })),
283
+ rest: body.rest,
284
+ };
285
+ }
286
+ /**
287
+ * A key of this client's `organization`, with a customer key: the key a company's traffic runs on,
288
+ * reaching that organization alone. `namespaces` scopes it (exact names, or prefixes ending in `*`),
289
+ * `modelsOnly` keeps it to the model routes, `expiresAt` ends it. The secret is in this answer only.
290
+ */
291
+ async createKey(input, options = {}) {
292
+ const request = { name: input.name };
293
+ if (input.namespaces !== undefined)
294
+ request.namespaces = input.namespaces;
295
+ if (input.modelsOnly)
296
+ request.models_only = true;
297
+ if (input.expiresAt !== undefined)
298
+ request.expires_at = input.expiresAt instanceof Date ? input.expiresAt.toISOString() : input.expiresAt;
299
+ const body = await this.request("POST", "/keys", request, options);
300
+ return { key: toKey(body.key), secret: body.secret };
301
+ }
302
+ /** The keys of this client's `organization`, with a customer key. */
303
+ async keys(options = {}) {
304
+ const body = await this.request("GET", "/keys", undefined, options);
305
+ return body.keys.map(toKey);
306
+ }
307
+ /** Revokes a key of this client's `organization`, with a customer key. */
308
+ async revokeKey(id, options = {}) {
309
+ await this.request("DELETE", `/keys/${encodeURIComponent(id)}`, undefined, options);
188
310
  }
189
311
  async embed(input, options = {}) {
190
312
  const request = { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" };
@@ -334,8 +456,7 @@ export class Namespace {
334
456
  * Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
335
457
  * (one of your organization's models from `GET /models`) needs this: a write creates one with the
336
458
  * default model. Its model never changes: creating it again with another one is a 409. Returns
337
- * the model that embeds it. `regexIndex` makes `grep` and `$text` filters answer from an index,
338
- * chosen once: over a namespace that exists without one it is a 409.
459
+ * the model that embeds it. `regexIndex` is ignored: every namespace has the text index.
339
460
  */
340
461
  async create(options = {}) {
341
462
  const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel, regex_index: options.regexIndex }, options);
@@ -372,6 +493,7 @@ export class Namespace {
372
493
  user: d.user,
373
494
  seq: d.seq,
374
495
  if_version: d.ifVersion,
496
+ image: d.image,
375
497
  })),
376
498
  }, { timeout: this.client.writeTimeout, ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
377
499
  body.ids.forEach((id, j) => {
@@ -383,6 +505,8 @@ export class Namespace {
383
505
  result.chunksEmbedded = r.chunks_embedded;
384
506
  if (r.stored_seq !== undefined)
385
507
  result.storedSeq = r.stored_seq;
508
+ if (r.image_embedded !== undefined)
509
+ result.imageEmbedded = r.image_embedded;
386
510
  }
387
511
  out.push(result);
388
512
  });
@@ -441,7 +565,7 @@ export class Namespace {
441
565
  /**
442
566
  * The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
443
567
  * with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
444
- * to go on; a namespace created without `regexIndex` reads its passages, so a page can stop short of `limit`.
568
+ * to go on; while a namespace's text index is still building, a page can stop short of `limit`.
445
569
  */
446
570
  async grep(pattern, options = {}) {
447
571
  const body = await this.client.request("POST", this.path("/grep"), {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.26.1",
3
+ "version": "0.27.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",