conare 0.26.0 → 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 +17 -1
- package/dist/cli/config.js +5 -2
- package/dist/cli/github/api.js +3 -0
- package/dist/cli/github/sync.js +4 -1
- package/dist/cli/main.js +6 -2
- package/dist/cli/sync.js +10 -3
- package/dist/cli/upload.js +2 -3
- package/dist/index.d.ts +134 -10
- package/dist/index.js +138 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,12 +36,28 @@ new Conare({ organization: "org_…" }) // acts for that one (X-Conare-
|
|
|
36
36
|
new Conare({ gzip: false }) // JSON bodies of 8 KiB or more go gzip by default
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
-
Every method also takes `{ signal, timeout }` as its last option.
|
|
39
|
+
Every method also takes `{ signal, timeout }` as its last option. The default timeout is 60 s, and 120 s for a write of documents.
|
|
40
40
|
|
|
41
41
|
A key acts for its own organization. A multi-organization key (made in the console by an admin of
|
|
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/cli/config.js
CHANGED
|
@@ -36,8 +36,11 @@ export function readExcluded(file) {
|
|
|
36
36
|
try {
|
|
37
37
|
text = readFileSync(file, "utf8");
|
|
38
38
|
}
|
|
39
|
-
catch {
|
|
40
|
-
|
|
39
|
+
catch (err) {
|
|
40
|
+
// Only an absent file means none: an unreadable one would upload what it excludes.
|
|
41
|
+
if (err.code === "ENOENT")
|
|
42
|
+
return new Set();
|
|
43
|
+
throw err;
|
|
41
44
|
}
|
|
42
45
|
return new Set(text.split(/\r?\n/).map((l) => l.replace(/#.*/, "").trim()).filter(Boolean));
|
|
43
46
|
}
|
package/dist/cli/github/api.js
CHANGED
|
@@ -76,6 +76,9 @@ export class GitHub {
|
|
|
76
76
|
for (const item of (await res.json()))
|
|
77
77
|
yield item;
|
|
78
78
|
url = nextLink(res.headers.get("link"));
|
|
79
|
+
// Every request carries the token: a next page goes nowhere else.
|
|
80
|
+
if (url && new URL(url).origin !== new URL(this.base).origin)
|
|
81
|
+
throw new GitHubError(0, `GitHub's next page is on another host: ${new URL(url).host}`);
|
|
79
82
|
}
|
|
80
83
|
}
|
|
81
84
|
async all(path) {
|
package/dist/cli/github/sync.js
CHANGED
|
@@ -264,7 +264,10 @@ async function fetchDocs(gh, repo, commit, files) {
|
|
|
264
264
|
for (const [j, f] of chunk.entries()) {
|
|
265
265
|
const blob = data.repository[`b${j}`];
|
|
266
266
|
const node = data.repository.head?.[`h${j}`]?.nodes?.[0];
|
|
267
|
-
|
|
267
|
+
// No blob is not a binary file: recorded as one, it is never fetched again and its document goes.
|
|
268
|
+
if (!blob)
|
|
269
|
+
throw new Error(`${repo}: GitHub answered no blob for ${f.path}`);
|
|
270
|
+
if (blob.isBinary) {
|
|
268
271
|
out.set(f.path, "binary");
|
|
269
272
|
continue;
|
|
270
273
|
}
|
package/dist/cli/main.js
CHANGED
|
@@ -166,9 +166,13 @@ async function syncSessions(args, paths, apiKey, say, fail) {
|
|
|
166
166
|
say(report.documents > 0 || report.deleted > 0
|
|
167
167
|
? `Synced ${report.sessions} sessions: ${report.documents} documents, ${formatBytes(report.bytes)}. ${report.unchanged} unchanged.`
|
|
168
168
|
: `Up to date: ${report.unchanged} sessions.`);
|
|
169
|
-
|
|
169
|
+
if (report.unread > 0)
|
|
170
|
+
say(`${report.unread} transcripts hold no message this version can read; they are read again next run.`);
|
|
171
|
+
for (const path of report.unreadable)
|
|
172
|
+
fail(`Could not read, tried again next run: ${path}`);
|
|
173
|
+
code = report.rejected.length > 0 || report.unreadable.length > 0 ? INCOMPLETE : 0;
|
|
170
174
|
if (code)
|
|
171
|
-
error = `${report.rejected.length} documents not accepted`;
|
|
175
|
+
error = `${report.rejected.length} documents not accepted, ${report.unreadable.length} transcripts not read`;
|
|
172
176
|
}
|
|
173
177
|
catch (err) {
|
|
174
178
|
if (err instanceof ConareError && err.status === 401) {
|
package/dist/cli/sync.js
CHANGED
|
@@ -18,7 +18,7 @@ export async function runSync(opts) {
|
|
|
18
18
|
const ns = opts.client?.namespace(NAMESPACE);
|
|
19
19
|
const log = opts.log ?? (() => { });
|
|
20
20
|
const state = loadState(opts.stateFile, opts.account);
|
|
21
|
-
const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, excluded: 0, deleted: 0, rejected: [], planned: [] };
|
|
21
|
+
const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, excluded: 0, unread: 0, unreadable: [], deleted: 0, rejected: [], planned: [] };
|
|
22
22
|
// The layout the server holds for a session: what the state said this tool stored last;
|
|
23
23
|
// on a fresh state (the first sync, after the migration of older history), or for a session
|
|
24
24
|
// whose upload an earlier run cut short after some of its documents were accepted (0: any
|
|
@@ -128,15 +128,22 @@ export async function runSync(opts) {
|
|
|
128
128
|
const transcript = file.read();
|
|
129
129
|
const project = projectName(transcript.cwd);
|
|
130
130
|
// Not stamped: taken off the list, the project's sessions upload on the next run.
|
|
131
|
-
|
|
131
|
+
// With a list, a session of no known project may be on it: held back too.
|
|
132
|
+
if (project === undefined ? opts.exclude?.size : opts.exclude?.has(project)) {
|
|
132
133
|
report.excluded++;
|
|
133
134
|
return;
|
|
134
135
|
}
|
|
136
|
+
// A new record format reads as no messages, and a stamp would keep the file from the CLI that can read it.
|
|
137
|
+
if (transcript.messages.length === 0) {
|
|
138
|
+
report.unread++;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
135
141
|
base = baseId(transcript);
|
|
136
|
-
docs =
|
|
142
|
+
docs = toDocuments(transcript, project);
|
|
137
143
|
}
|
|
138
144
|
catch (err) {
|
|
139
145
|
log(`Skipped ${file.path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
146
|
+
report.unreadable.push(file.path);
|
|
140
147
|
return;
|
|
141
148
|
}
|
|
142
149
|
// Two files of one session (a session copied between projects), even in different
|
package/dist/cli/upload.js
CHANGED
|
@@ -9,7 +9,6 @@ export const BATCH_DOCUMENTS = 100;
|
|
|
9
9
|
export const BATCH_BYTES = 1_000_000;
|
|
10
10
|
/** Batches sent at once (sync.ts). */
|
|
11
11
|
export const UPLOADS_IN_FLIGHT = 4;
|
|
12
|
-
const WRITE_TIMEOUT_MS = 120_000;
|
|
13
12
|
/** Groups documents in order into batches within both limits. */
|
|
14
13
|
export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES) {
|
|
15
14
|
const out = [];
|
|
@@ -41,7 +40,7 @@ function isDocumentError(err) {
|
|
|
41
40
|
export async function sendBatch(ns, batch) {
|
|
42
41
|
const unchanged = (results) => results.filter((r) => r.result === "unchanged").length;
|
|
43
42
|
try {
|
|
44
|
-
return { accepted: batch, unchanged: unchanged(await ns.write(batch
|
|
43
|
+
return { accepted: batch, unchanged: unchanged(await ns.write(batch)), rejected: [] };
|
|
45
44
|
}
|
|
46
45
|
catch (err) {
|
|
47
46
|
if (!isDocumentError(err))
|
|
@@ -52,7 +51,7 @@ export async function sendBatch(ns, batch) {
|
|
|
52
51
|
const result = { accepted: [], unchanged: 0, rejected: [] };
|
|
53
52
|
for (const doc of batch) {
|
|
54
53
|
try {
|
|
55
|
-
result.unchanged += unchanged(await ns.write(doc
|
|
54
|
+
result.unchanged += unchanged(await ns.write(doc));
|
|
56
55
|
result.accepted.push(doc);
|
|
57
56
|
}
|
|
58
57
|
catch (err) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
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
|
|
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;
|
|
@@ -528,7 +547,7 @@ export interface ConareOptions {
|
|
|
528
547
|
apiKey?: string;
|
|
529
548
|
/** Defaults to CONARE_BASE_URL, then https://api.conare.ai. */
|
|
530
549
|
baseURL?: string;
|
|
531
|
-
/** Per-request timeout in milliseconds. Default 60000. */
|
|
550
|
+
/** Per-request timeout in milliseconds. Default 60000, and 120000 for a write of documents, which the API may take 110 s over. */
|
|
532
551
|
timeout?: number;
|
|
533
552
|
/** Retries on 429, 5xx, 409 `idempotency_in_progress`, network errors and timeouts, every method: each write carries an Idempotency-Key, so a retry never applies it twice. Default 2. */
|
|
534
553
|
maxRetries?: number;
|
|
@@ -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;
|
|
@@ -600,6 +671,7 @@ export declare class Conare {
|
|
|
600
671
|
readonly organization: string | undefined;
|
|
601
672
|
private readonly apiKey;
|
|
602
673
|
private readonly timeout;
|
|
674
|
+
readonly writeTimeout: number;
|
|
603
675
|
private readonly maxRetries;
|
|
604
676
|
private readonly fetchFn;
|
|
605
677
|
private gzip;
|
|
@@ -615,9 +687,62 @@ export declare class Conare {
|
|
|
615
687
|
}): Promise<NamespaceInfo[]>;
|
|
616
688
|
/**
|
|
617
689
|
* The organizations this key acts for, its own first. A multi-organization key lists each other one
|
|
618
|
-
* 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.
|
|
619
732
|
*/
|
|
620
|
-
|
|
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>;
|
|
621
746
|
/**
|
|
622
747
|
* Embed texts. Use type "query" for search queries and "document" (default) for stored text.
|
|
623
748
|
* `outputDtype: "int8"` returns each vector as int8 values and one scale (vector ≈ values × scale),
|
|
@@ -662,8 +787,7 @@ export declare class Namespace {
|
|
|
662
787
|
* Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
|
|
663
788
|
* (one of your organization's models from `GET /models`) needs this: a write creates one with the
|
|
664
789
|
* default model. Its model never changes: creating it again with another one is a 409. Returns
|
|
665
|
-
* the model that embeds it. `regexIndex`
|
|
666
|
-
* 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.
|
|
667
791
|
*/
|
|
668
792
|
create(options?: RequestOptions & {
|
|
669
793
|
embeddingModel?: string;
|
|
@@ -725,7 +849,7 @@ export declare class Namespace {
|
|
|
725
849
|
/**
|
|
726
850
|
* The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
|
|
727
851
|
* with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
|
|
728
|
-
* to go on; a namespace
|
|
852
|
+
* to go on; while a namespace's text index is still building, a page can stop short of `limit`.
|
|
729
853
|
*/
|
|
730
854
|
grep(pattern: string | FuzzyText, options?: GrepOptions): Promise<GrepPage>;
|
|
731
855
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
|
|
2
|
-
export const VERSION = "0.
|
|
2
|
+
export const VERSION = "0.27.0";
|
|
3
3
|
const DEFAULT_BASE_URL = "https://api.conare.ai";
|
|
4
4
|
const BATCH_SIZE = 100;
|
|
5
|
+
/** Above the API's 110 s deadline for a write: a call given up sooner is retried while the first still runs. */
|
|
6
|
+
const WRITE_TIMEOUT_MS = 120_000;
|
|
5
7
|
// A JSON body this long or longer goes gzip-encoded: past the first ~14 KB a new connection may send,
|
|
6
8
|
// each doubling of the window costs a round trip, and JSON of documents is 3-4x smaller in gzip.
|
|
7
9
|
const GZIP_MIN_BYTES = 8 * 1024;
|
|
@@ -57,6 +59,7 @@ function toFileUpload(body) {
|
|
|
57
59
|
imagesOcr: body.images_ocr ?? 0,
|
|
58
60
|
imagesWithoutText: body.images_without_text ?? [],
|
|
59
61
|
pagesWithoutText: body.pages_without_text ?? [],
|
|
62
|
+
pagesWithImage: body.pages_with_image ?? [],
|
|
60
63
|
ocrPending: body.ocr_pending ?? [],
|
|
61
64
|
};
|
|
62
65
|
}
|
|
@@ -64,6 +67,30 @@ function toFileUpload(body) {
|
|
|
64
67
|
export function dequantize(embeddings) {
|
|
65
68
|
return embeddings.values.map((v, i) => Array.from(v, (x) => x * (embeddings.scales[i] ?? 0)));
|
|
66
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
|
+
}
|
|
67
94
|
// ---- Errors ----------------------------------------------------------------
|
|
68
95
|
/** Every failure the SDK throws. `status` is 0 when no response arrived. */
|
|
69
96
|
export class ConareError extends Error {
|
|
@@ -127,6 +154,7 @@ export class Conare {
|
|
|
127
154
|
organization;
|
|
128
155
|
apiKey;
|
|
129
156
|
timeout;
|
|
157
|
+
writeTimeout;
|
|
130
158
|
maxRetries;
|
|
131
159
|
fetchFn;
|
|
132
160
|
gzip;
|
|
@@ -143,6 +171,7 @@ export class Conare {
|
|
|
143
171
|
end--;
|
|
144
172
|
this.baseURL = baseURL.slice(0, end);
|
|
145
173
|
this.timeout = options.timeout ?? 60_000;
|
|
174
|
+
this.writeTimeout = options.timeout ?? WRITE_TIMEOUT_MS;
|
|
146
175
|
this.maxRetries = options.maxRetries ?? 2;
|
|
147
176
|
this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
|
|
148
177
|
this.organization = options.organization || undefined;
|
|
@@ -176,11 +205,108 @@ export class Conare {
|
|
|
176
205
|
}
|
|
177
206
|
/**
|
|
178
207
|
* The organizations this key acts for, its own first. A multi-organization key lists each other one
|
|
179
|
-
* 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.
|
|
180
211
|
*/
|
|
181
212
|
async organizations(options = {}) {
|
|
182
|
-
const
|
|
183
|
-
|
|
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);
|
|
184
310
|
}
|
|
185
311
|
async embed(input, options = {}) {
|
|
186
312
|
const request = { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" };
|
|
@@ -330,8 +456,7 @@ export class Namespace {
|
|
|
330
456
|
* Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
|
|
331
457
|
* (one of your organization's models from `GET /models`) needs this: a write creates one with the
|
|
332
458
|
* default model. Its model never changes: creating it again with another one is a 409. Returns
|
|
333
|
-
* the model that embeds it. `regexIndex`
|
|
334
|
-
* 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.
|
|
335
460
|
*/
|
|
336
461
|
async create(options = {}) {
|
|
337
462
|
const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel, regex_index: options.regexIndex }, options);
|
|
@@ -368,8 +493,9 @@ export class Namespace {
|
|
|
368
493
|
user: d.user,
|
|
369
494
|
seq: d.seq,
|
|
370
495
|
if_version: d.ifVersion,
|
|
496
|
+
image: d.image,
|
|
371
497
|
})),
|
|
372
|
-
}, { ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
|
|
498
|
+
}, { timeout: this.client.writeTimeout, ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
|
|
373
499
|
body.ids.forEach((id, j) => {
|
|
374
500
|
const r = body.results?.[j];
|
|
375
501
|
const result = { id, version: body.versions?.[j] ?? null };
|
|
@@ -379,6 +505,8 @@ export class Namespace {
|
|
|
379
505
|
result.chunksEmbedded = r.chunks_embedded;
|
|
380
506
|
if (r.stored_seq !== undefined)
|
|
381
507
|
result.storedSeq = r.stored_seq;
|
|
508
|
+
if (r.image_embedded !== undefined)
|
|
509
|
+
result.imageEmbedded = r.image_embedded;
|
|
382
510
|
}
|
|
383
511
|
out.push(result);
|
|
384
512
|
});
|
|
@@ -437,7 +565,7 @@ export class Namespace {
|
|
|
437
565
|
/**
|
|
438
566
|
* The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
|
|
439
567
|
* with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
|
|
440
|
-
* to go on; a namespace
|
|
568
|
+
* to go on; while a namespace's text index is still building, a page can stop short of `limit`.
|
|
441
569
|
*/
|
|
442
570
|
async grep(pattern, options = {}) {
|
|
443
571
|
const body = await this.client.request("POST", this.path("/grep"), {
|
|
@@ -510,7 +638,7 @@ export class Namespace {
|
|
|
510
638
|
* does not exist throws ConareError 404 `namespace_not_found`. Returns how many were deleted.
|
|
511
639
|
*/
|
|
512
640
|
async deleteMany(ids, options) {
|
|
513
|
-
const out = await this.client.request("POST", this.path("/documents/delete"), { ids }, options);
|
|
641
|
+
const out = await this.client.request("POST", this.path("/documents/delete"), { ids }, { timeout: this.client.writeTimeout, ...options });
|
|
514
642
|
return out.deleted;
|
|
515
643
|
}
|
|
516
644
|
/** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
|
|
@@ -519,7 +647,7 @@ export class Namespace {
|
|
|
519
647
|
const key = options?.idempotencyKey;
|
|
520
648
|
for (let round = 0;; round++) {
|
|
521
649
|
// Each round is its own call (the same body deletes the next batch): its own key.
|
|
522
|
-
const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: stepKey(key, round) });
|
|
650
|
+
const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { timeout: this.client.writeTimeout, ...options, idempotencyKey: stepKey(key, round) });
|
|
523
651
|
deleted += out.deleted;
|
|
524
652
|
if (!out.more)
|
|
525
653
|
return deleted;
|