conare 0.7.4 → 0.9.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.
@@ -0,0 +1,137 @@
1
+ // Sending documents through the SDK client. The client retries 429, 5xx and network errors
2
+ // with backoff, honouring Retry-After (bounded by its maxRetries); what still fails here is
3
+ // either one bad document (sent again alone, then left for the next run) or a server or
4
+ // auth problem that stops the run.
5
+ import { ConareError } from "../index.js";
6
+ import { partId } from "./documents.js";
7
+ /** The API takes 1-100 documents per write; a byte budget keeps each request's embedding work small. */
8
+ export const BATCH_DOCUMENTS = 100;
9
+ export const BATCH_BYTES = 1_000_000;
10
+ export const WRITE_TIMEOUT_MS = 120_000;
11
+ /** Groups documents in order into batches within both limits. */
12
+ export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES) {
13
+ const out = [];
14
+ let current = [];
15
+ let bytes = 0;
16
+ for (const doc of docs) {
17
+ const size = Buffer.byteLength(doc.text);
18
+ if (current.length > 0 && (current.length >= maxDocs || bytes + size > maxBytes)) {
19
+ out.push(current);
20
+ current = [];
21
+ bytes = 0;
22
+ }
23
+ current.push(doc);
24
+ bytes += size;
25
+ }
26
+ if (current.length > 0)
27
+ out.push(current);
28
+ return out;
29
+ }
30
+ /** A request the API refused because of what one of its documents holds. */
31
+ function isDocumentError(err) {
32
+ return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422);
33
+ }
34
+ /**
35
+ * Write one batch. When the API refuses the batch for its content, each document is sent
36
+ * alone so one bad document does not hold back the others. Any other failure throws.
37
+ */
38
+ export async function sendBatch(ns, batch) {
39
+ try {
40
+ await ns.add(batch, { timeout: WRITE_TIMEOUT_MS });
41
+ return { accepted: batch, rejected: [] };
42
+ }
43
+ catch (err) {
44
+ if (!isDocumentError(err))
45
+ throw err;
46
+ if (batch.length === 1)
47
+ return { accepted: [], rejected: [{ doc: batch[0], error: err }] };
48
+ }
49
+ const result = { accepted: [], rejected: [] };
50
+ for (const doc of batch) {
51
+ try {
52
+ await ns.add(doc, { timeout: WRITE_TIMEOUT_MS });
53
+ result.accepted.push(doc);
54
+ }
55
+ catch (err) {
56
+ if (!isDocumentError(err))
57
+ throw err;
58
+ result.rejected.push({ doc, error: err });
59
+ }
60
+ }
61
+ return result;
62
+ }
63
+ /** Delete one document; false when it does not exist (404 document_not_found). */
64
+ export async function deleteIfPresent(ns, id) {
65
+ try {
66
+ await ns.delete(id);
67
+ return true;
68
+ }
69
+ catch (err) {
70
+ if (err instanceof ConareError && err.status === 404)
71
+ return false;
72
+ throw err;
73
+ }
74
+ }
75
+ /** Loop guard for the part probe; a 256 KB-per-part session would need to exceed 25 GB. */
76
+ const MAX_PARTS = 100_000;
77
+ const PART_ID = /^(.+):part:(\d{6})$/;
78
+ /** List every id in the namespace once and group them by session; an absent namespace holds nothing. */
79
+ export async function listLayouts(ns) {
80
+ const layouts = new Map();
81
+ try {
82
+ for await (const doc of ns.list({ limit: 100 })) {
83
+ const m = PART_ID.exec(doc.id);
84
+ const base = m ? m[1] : doc.id;
85
+ const held = layouts.get(base) ?? { whole: false, parts: [] };
86
+ if (m)
87
+ held.parts.push(Number(m[2]));
88
+ else
89
+ held.whole = true;
90
+ layouts.set(base, held);
91
+ }
92
+ }
93
+ catch (err) {
94
+ if (!(err instanceof ConareError && err.status === 404))
95
+ throw err;
96
+ }
97
+ return layouts;
98
+ }
99
+ /** The layout of a session this tool stored as `count` documents. */
100
+ export function heldAs(count) {
101
+ return count > 1 ? { whole: false, parts: Array.from({ length: count }, (_, i) => i + 1) } : { whole: true, parts: [] };
102
+ }
103
+ /**
104
+ * Remove what an earlier layout of a session left behind, once its k new documents are
105
+ * accepted. A session is stored as the single document <base> or as the parts
106
+ * <base>:part:000001..k (this tool and the migration of older history both write that):
107
+ * with parts, <base> is stale; otherwise every part is; with parts, those after k are.
108
+ *
109
+ * When the old layout is known (`held`: what this tool stored last, or a listing of the
110
+ * namespace), exactly its stale ids are deleted, gaps included. Otherwise the parts are
111
+ * probed from the first stale number until the first 404. Returns the ids deleted.
112
+ */
113
+ export async function removeStaleParts(ns, base, k, held) {
114
+ const deleted = [];
115
+ const remove = async (id) => {
116
+ if (await deleteIfPresent(ns, id))
117
+ deleted.push(id);
118
+ };
119
+ const firstStale = k > 1 ? k + 1 : 1;
120
+ if (held) {
121
+ if (k > 1 && held.whole)
122
+ await remove(base);
123
+ for (const n of [...held.parts].sort((a, b) => a - b))
124
+ if (n >= firstStale)
125
+ await remove(partId(base, n));
126
+ return deleted;
127
+ }
128
+ if (k > 1)
129
+ await remove(base);
130
+ for (let n = firstStale; n <= MAX_PARTS; n++) {
131
+ const id = partId(base, n);
132
+ if (!(await deleteIfPresent(ns, id)))
133
+ break;
134
+ deleted.push(id);
135
+ }
136
+ return deleted;
137
+ }
@@ -0,0 +1,190 @@
1
+ export declare const VERSION = "0.9.0";
2
+ /** A metadata value: string, number, boolean or an array of strings. */
3
+ export type MetadataValue = string | number | boolean | string[];
4
+ export type Metadata = Record<string, MetadataValue>;
5
+ type Scalar = string | number | boolean;
6
+ /**
7
+ * Operators for one metadata key: `$eq` and `$in`. Filters match values exactly; the API
8
+ * answers 400 invalid_filter for the operators typed `never` here, so they do not compile.
9
+ */
10
+ export interface FilterOperators {
11
+ $eq?: Scalar;
12
+ $in?: Scalar[];
13
+ $ne?: never;
14
+ $nin?: never;
15
+ $gt?: never;
16
+ $gte?: never;
17
+ $lt?: never;
18
+ $lte?: never;
19
+ }
20
+ /**
21
+ * A metadata filter. `{ team: "support" }` means equals (or, for an array value, contains);
22
+ * use `$eq` / `$in` per key and `$and` / `$or` to combine:
23
+ * `{ $or: [{ team: "support" }, { year: { $in: [2024, 2025] } }] }`.
24
+ */
25
+ export interface Filter {
26
+ $and?: Filter[];
27
+ $or?: Filter[];
28
+ [key: string]: Scalar | FilterOperators | Filter[] | undefined;
29
+ }
30
+ export interface DocumentInput {
31
+ /** 1-256 characters of [A-Za-z0-9._:-]. Omit to let Conare generate one. Same id replaces. */
32
+ id?: string;
33
+ text: string;
34
+ metadata?: Metadata;
35
+ }
36
+ export interface Document {
37
+ id: string;
38
+ text: string;
39
+ metadata: Metadata;
40
+ updatedAt: Date;
41
+ }
42
+ export interface DocumentSummary {
43
+ id: string;
44
+ metadata: Metadata;
45
+ updatedAt: Date;
46
+ }
47
+ export interface QueryResult {
48
+ id: string;
49
+ /** The best matching passage of the document. */
50
+ text: string;
51
+ score: number;
52
+ metadata: Metadata;
53
+ }
54
+ export interface NamespaceInfo {
55
+ name: string;
56
+ documents: number;
57
+ }
58
+ export interface RerankResult {
59
+ index: number;
60
+ score: number;
61
+ document: string;
62
+ }
63
+ export type SourceStatus = "connecting" | "syncing" | "ready" | "error";
64
+ export interface Source {
65
+ id: string;
66
+ type: string;
67
+ name: string;
68
+ namespace: string;
69
+ status: SourceStatus;
70
+ error: string | null;
71
+ documents: number;
72
+ lastSyncedAt: Date | null;
73
+ createdAt: Date;
74
+ }
75
+ export interface SourceType {
76
+ type: string;
77
+ name: string;
78
+ logoUrl: string;
79
+ }
80
+ export interface ConareOptions {
81
+ /** Defaults to the CONARE_API_KEY environment variable. */
82
+ apiKey?: string;
83
+ /** Defaults to CONARE_BASE_URL, then https://api.conare.ai. */
84
+ baseURL?: string;
85
+ /** Per-request timeout in milliseconds. Default 60000. */
86
+ timeout?: number;
87
+ /** Retries on 429, 5xx and network errors (a request that could create something twice only on 429 and 503). Default 2. */
88
+ maxRetries?: number;
89
+ /** Custom fetch, e.g. for proxies or tests. */
90
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
91
+ }
92
+ export interface RequestOptions {
93
+ signal?: AbortSignal;
94
+ /** Overrides the client timeout for this call, in milliseconds. */
95
+ timeout?: number;
96
+ }
97
+ /** Every failure the SDK throws. `status` is 0 when no response arrived. */
98
+ export declare class ConareError extends Error {
99
+ readonly status: number;
100
+ readonly code: string;
101
+ readonly requestId: string | null;
102
+ constructor(status: number, code: string, message: string, requestId?: string | null);
103
+ }
104
+ /**
105
+ * The Conare client.
106
+ *
107
+ * const conare = new Conare() // reads CONARE_API_KEY
108
+ * const docs = conare.namespace("docs")
109
+ */
110
+ export declare class Conare {
111
+ readonly baseURL: string;
112
+ readonly sources: Sources;
113
+ private readonly apiKey;
114
+ private readonly timeout;
115
+ private readonly maxRetries;
116
+ private readonly fetchFn;
117
+ constructor(options?: ConareOptions);
118
+ /** A handle to one namespace. Nothing is sent until you call a method; the first write creates it. */
119
+ namespace(name: string): Namespace;
120
+ /** Every namespace in the organization with its document count. */
121
+ namespaces(options?: RequestOptions): Promise<NamespaceInfo[]>;
122
+ /** Embed texts. Use type "query" for search queries and "document" (default) for stored text. */
123
+ embed(input: string | string[], options?: RequestOptions & {
124
+ type?: "document" | "query";
125
+ }): Promise<number[][]>;
126
+ /** Rerank documents against a query, best first. */
127
+ rerank(query: string, documents: string[], options?: RequestOptions & {
128
+ topK?: number;
129
+ }): Promise<RerankResult[]>;
130
+ private send;
131
+ }
132
+ /** One namespace: a named set of documents, e.g. "docs" or "user-42". */
133
+ export declare class Namespace {
134
+ private readonly client;
135
+ readonly name: string;
136
+ constructor(client: Conare, name: string);
137
+ private path;
138
+ /**
139
+ * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
140
+ * A document without an id gets one here, so a retried batch replaces instead of duplicating.
141
+ */
142
+ add(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<string[]>;
143
+ /** Hybrid search, reranked. One result per document: its best passage. */
144
+ query(query: string, options?: RequestOptions & {
145
+ topK?: number;
146
+ filter?: Filter;
147
+ rerank?: boolean;
148
+ }): Promise<QueryResult[]>;
149
+ /** One document by id, or null if it does not exist. */
150
+ get(id: string, options?: RequestOptions): Promise<Document | null>;
151
+ /** Every document (id, metadata, updatedAt), fetched page by page as you iterate. `limit` is the page size: 1-100, default 50. */
152
+ list(options?: RequestOptions & {
153
+ limit?: number;
154
+ }): AsyncGenerator<DocumentSummary>;
155
+ /** Delete one document. Throws a ConareError with status 404 (`document_not_found`) if it does not exist. */
156
+ delete(id: string, options?: RequestOptions): Promise<void>;
157
+ /** Delete the namespace and every document in it. Succeeds as well when it holds no documents (already deleted or never written). */
158
+ drop(options?: RequestOptions): Promise<void>;
159
+ }
160
+ /** Apps connected through Conare that keep syncing into a namespace. */
161
+ export declare class Sources {
162
+ private readonly client;
163
+ constructor(client: Conare);
164
+ /**
165
+ * Start connecting an app. Send the app owner to `connectUrl`; they come back to `redirectUrl`.
166
+ * For your own users, connect each one into their own namespace, e.g. "user-42".
167
+ */
168
+ connect(params: {
169
+ type: string;
170
+ namespace: string;
171
+ name?: string;
172
+ redirectUrl?: string;
173
+ }, options?: RequestOptions): Promise<{
174
+ source: Source;
175
+ connectUrl: string;
176
+ }>;
177
+ /** Every connected source. */
178
+ list(options?: RequestOptions): Promise<Source[]>;
179
+ /** One source by id. */
180
+ get(id: string, options?: RequestOptions): Promise<Source>;
181
+ /** Start a sync now. */
182
+ sync(id: string, options?: RequestOptions): Promise<Source>;
183
+ /** Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. */
184
+ delete(id: string, options?: RequestOptions & {
185
+ deleteDocuments?: boolean;
186
+ }): Promise<void>;
187
+ /** The apps you can connect. */
188
+ types(options?: RequestOptions): Promise<SourceType[]>;
189
+ }
190
+ export {};