@relevanceai/sdk 2.0.1 → 3.0.0-alpha.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.
Files changed (60) hide show
  1. package/esm/agent-task.d.ts +61 -0
  2. package/esm/agent-task.js +112 -0
  3. package/esm/agent.d.ts +17 -0
  4. package/esm/agent.js +52 -0
  5. package/esm/client.d.ts +36 -0
  6. package/esm/client.js +69 -0
  7. package/esm/events.d.ts +40 -0
  8. package/esm/events.js +39 -0
  9. package/esm/key.d.ts +86 -0
  10. package/esm/key.js +121 -0
  11. package/esm/message.d.ts +18 -0
  12. package/esm/message.js +18 -0
  13. package/esm/mod.d.ts +7 -0
  14. package/esm/mod.js +4 -0
  15. package/esm/package.json +3 -0
  16. package/esm/region.d.ts +5 -0
  17. package/esm/region.js +6 -0
  18. package/esm/task.d.ts +25 -0
  19. package/esm/task.js +96 -0
  20. package/esm/utils.d.ts +8 -0
  21. package/esm/utils.js +29 -0
  22. package/package.json +11 -36
  23. package/LICENSE +0 -21
  24. package/README.md +0 -121
  25. package/dist-cjs/generated/VecDBApi.js +0 -1682
  26. package/dist-cjs/generated/_VecDBApiSchemaTypes.js +0 -3
  27. package/dist-cjs/generated/index.js +0 -17
  28. package/dist-cjs/index.js +0 -18
  29. package/dist-cjs/services/discovery/Dataset.js +0 -126
  30. package/dist-cjs/services/discovery/index.js +0 -159
  31. package/dist-cjs/services/index.js +0 -18
  32. package/dist-cjs/services/vecdb/Dataset.js +0 -137
  33. package/dist-cjs/services/vecdb/index.js +0 -137
  34. package/dist-cjs/shared/BaseClient.js +0 -35
  35. package/dist-cjs/shared/generate.js +0 -90
  36. package/dist-cjs/shared/serviceConfigs.js +0 -10
  37. package/dist-es/generated/VecDBApi.js +0 -2579
  38. package/dist-es/generated/_VecDBApiSchemaTypes.js +0 -2
  39. package/dist-es/generated/index.js +0 -1
  40. package/dist-es/index.js +0 -2
  41. package/dist-es/services/discovery/Dataset.js +0 -126
  42. package/dist-es/services/discovery/index.js +0 -159
  43. package/dist-es/services/index.js +0 -2
  44. package/dist-es/services/vecdb/Dataset.js +0 -356
  45. package/dist-es/services/vecdb/index.js +0 -184
  46. package/dist-es/shared/BaseClient.js +0 -82
  47. package/dist-es/shared/generate.js +0 -224
  48. package/dist-es/shared/serviceConfigs.js +0 -7
  49. package/dist-types/generated/VecDBApi.d.ts +0 -632
  50. package/dist-types/generated/_VecDBApiSchemaTypes.d.ts +0 -22299
  51. package/dist-types/generated/index.d.ts +0 -1
  52. package/dist-types/index.d.ts +0 -2
  53. package/dist-types/services/discovery/Dataset.d.ts +0 -0
  54. package/dist-types/services/discovery/index.d.ts +0 -0
  55. package/dist-types/services/index.d.ts +0 -1
  56. package/dist-types/services/vecdb/Dataset.d.ts +0 -52
  57. package/dist-types/services/vecdb/index.d.ts +0 -44
  58. package/dist-types/shared/BaseClient.d.ts +0 -28
  59. package/dist-types/shared/generate.d.ts +0 -1
  60. package/dist-types/shared/serviceConfigs.d.ts +0 -8
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,5 @@
1
+ export type Region = "bcbe5a" | "d7b62b" | "f1db6c";
2
+ export declare const REGION_US = "bcbe5a";
3
+ export declare const REGION_EU = "d7b62b";
4
+ export declare const REGION_AU = "f1db6c";
5
+ export declare function regionBaseURL(region: Region): string;
package/esm/region.js ADDED
@@ -0,0 +1,6 @@
1
+ export const REGION_US = "bcbe5a";
2
+ export const REGION_EU = "d7b62b";
3
+ export const REGION_AU = "f1db6c";
4
+ export function regionBaseURL(region) {
5
+ return `https://api-${region}.stack.tryrelevance.com`;
6
+ }
package/esm/task.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { Client } from "./client.js";
2
+ import type { TaskMessage } from "./message.js";
3
+ export type TaskStatus = "not-started" | "idle" | "queued" | "running" | "action" | "complete" | "error";
4
+ export declare abstract class Task<S, E extends Record<string, unknown>> extends EventTarget {
5
+ #private;
6
+ readonly subject: S;
7
+ protected readonly client: Client;
8
+ private listenController;
9
+ abstract fetchMessages(fetchOptions?: {
10
+ from?: Date;
11
+ }): Promise<TaskMessage[]>;
12
+ abstract fetchStatus(): Promise<TaskStatus>;
13
+ constructor(subject: S, id?: string | undefined, client?: Client);
14
+ get id(): string | undefined;
15
+ protected setId(id: string, status?: TaskStatus): void;
16
+ listen(): void;
17
+ isListening(): boolean;
18
+ stopListening(): void;
19
+ addEventListener<K extends keyof E>(type: Extract<K, string>, listener: ((event: CustomEvent<E[K]>) => void) | {
20
+ handleEvent: (event: CustomEvent<E[K]>) => void;
21
+ } | null, options?: boolean | AddEventListenerOptions): void;
22
+ removeEventListener<K extends keyof E>(type: Extract<K, string>, listener: ((event: CustomEvent<E[K]>) => void) | {
23
+ handleEvent: (event: CustomEvent<E[K]>) => void;
24
+ } | null, options?: boolean | AddEventListenerOptions): void;
25
+ }
package/esm/task.js ADDED
@@ -0,0 +1,96 @@
1
+ import { Client } from "./client.js";
2
+ import { TaskErrorEvent, TaskMessageEvent, TaskStartEvent, TaskStatusEvent, TaskUpdateEvent, } from "./events.js";
3
+ import { runInterval } from "./utils.js";
4
+ export class Task extends EventTarget {
5
+ subject;
6
+ client;
7
+ #id;
8
+ listenController;
9
+ constructor(subject, id = undefined, client = Client.default()) {
10
+ super();
11
+ this.subject = subject;
12
+ this.client = client;
13
+ this.#id = id;
14
+ }
15
+ get id() {
16
+ return this.#id;
17
+ }
18
+ setId(id, status = "not-started") {
19
+ if (this.#id) {
20
+ throw new Error("task id is already set");
21
+ }
22
+ // @ts-ignore: allow assignment to readonly in this special case
23
+ this.#id = id;
24
+ this.dispatchEvent(new TaskStartEvent(id, status));
25
+ }
26
+ listen() {
27
+ if (this.isListening()) {
28
+ return;
29
+ }
30
+ this.listenController = new AbortController();
31
+ const signal = this.listenController.signal;
32
+ let currentStatus = null;
33
+ const messagesCursor = new Date(0);
34
+ void runInterval(async () => {
35
+ // no task, yet
36
+ if (!this.id) {
37
+ return;
38
+ }
39
+ const [status, messages] = await Promise.all([
40
+ this.fetchStatus(),
41
+ this.fetchMessages({
42
+ from: messagesCursor,
43
+ }),
44
+ ]);
45
+ if (!this.isListening()) {
46
+ return;
47
+ }
48
+ if (status !== currentStatus) {
49
+ currentStatus = status;
50
+ this.dispatchEvent(new TaskStatusEvent(status));
51
+ }
52
+ if (messages.length) {
53
+ for (const message of messages) {
54
+ switch (message.type) {
55
+ case "agent-error":
56
+ this.dispatchEvent(new TaskErrorEvent(message));
57
+ break;
58
+ case "tool-run":
59
+ this.dispatchEvent(new TaskUpdateEvent(message));
60
+ break;
61
+ case "agent-message":
62
+ case "user-message":
63
+ this.dispatchEvent(new TaskMessageEvent(message));
64
+ }
65
+ }
66
+ messagesCursor.setTime(
67
+ // +1 the api treats after inclusively
68
+ messages.at(-1).createdAt.getTime() + 1);
69
+ }
70
+ }, 15_000, { signal });
71
+ }
72
+ isListening() {
73
+ return this.listenController !== undefined;
74
+ }
75
+ stopListening() {
76
+ this.listenController?.abort();
77
+ this.listenController = undefined;
78
+ }
79
+ addEventListener(type, listener, options) {
80
+ this.listen();
81
+ const signal = AbortSignal.any([
82
+ ...(options && typeof options === "object" && options.signal
83
+ ? [options.signal]
84
+ : []),
85
+ this.listenController.signal,
86
+ ]);
87
+ const capture = typeof options === "boolean"
88
+ ? options
89
+ : Boolean(options?.capture);
90
+ const addOptions = Object.assign({}, options, { signal, capture });
91
+ super.addEventListener(type, listener, addOptions);
92
+ }
93
+ removeEventListener(type, listener, options) {
94
+ super.removeEventListener(type, listener, options);
95
+ }
96
+ }
package/esm/utils.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export declare function abortPromise(signal: AbortSignal, reject?: boolean): Promise<void>;
2
+ export declare function delay(timeout: number): Promise<void>;
3
+ export declare function runInterval(runner: () => Promise<void> | void, interval: number, { signal, }?: {
4
+ signal?: AbortSignal;
5
+ immediate?: boolean;
6
+ }): Promise<void>;
7
+ export declare function cleanPath(path: string, version?: string): string;
8
+ export declare function randomUUID(): Promise<any>;
package/esm/utils.js ADDED
@@ -0,0 +1,29 @@
1
+ export function abortPromise(signal, reject) {
2
+ return new Promise((res, rej) => signal.addEventListener("abort", () => reject ? rej() : res()));
3
+ }
4
+ export function delay(timeout) {
5
+ return new Promise((done) => setTimeout(done, timeout));
6
+ }
7
+ export async function runInterval(runner, interval, { signal, } = {}) {
8
+ while (true) {
9
+ if (signal?.aborted) {
10
+ break;
11
+ }
12
+ await runner();
13
+ await Promise.race([
14
+ delay(interval),
15
+ signal ? abortPromise(signal) : new Promise(() => { }),
16
+ ]);
17
+ }
18
+ }
19
+ export function cleanPath(path, version = "latest") {
20
+ return `/${version}/${path.trim().replace(/^\/+/, "")}`;
21
+ }
22
+ export async function randomUUID() {
23
+ if (typeof crypto !== "undefined") {
24
+ return crypto.randomUUID();
25
+ }
26
+ // @ts-ignore allow this import for node builds
27
+ const cryptoModule = await import("node:crypto");
28
+ return cryptoModule.randomUUID();
29
+ }
package/package.json CHANGED
@@ -1,38 +1,13 @@
1
1
  {
2
2
  "name": "@relevanceai/sdk",
3
- "version": "2.0.1",
4
- "description": "Javascript client for RelevanceAI APIs. Browser, Node.js and typescript support.",
5
- "main": "./dist-cjs/index.js",
6
- "types": "./dist-types/index.d.ts",
7
- "module": "./dist-es/index.js",
8
- "files": [
9
- "dist-*"
10
- ],
11
- "scripts": {
12
- "build": "tsc -p tsconfig.json && tsc -p tsconfig.es.json && tsc -p tsconfig.types.json",
13
- "generate": "ts-node ./src/shared/generate.ts",
14
- "test": "jest",
15
- "prepare": "npm run build",
16
- "sample": "ts-node ./test/sample.test.mjs"
17
- },
18
- "repository": {
19
- "type": "git",
20
- "url": "git+https://github.com/RelevanceAI/relevance-js-sdk.git"
21
- },
22
- "author": "",
23
- "license": "ISC",
24
- "bugs": {
25
- "url": "https://github.com/RelevanceAI/relevance-js-sdk/issues"
26
- },
27
- "homepage": "https://github.com/RelevanceAI/relevance-js-sdk#readme",
28
- "devDependencies": {
29
- "@types/jest": "^27.0.2",
30
- "openapi-typescript": "^4.4.0",
31
- "ts-jest": "^27.0.7",
32
- "ts-node": "^10.4.0",
33
- "typescript": "^4.4.4"
34
- },
35
- "dependencies": {
36
- "cross-fetch": "^3.1.4"
37
- }
38
- }
3
+ "version": "3.0.0-alpha.0",
4
+ "license": "MIT",
5
+ "module": "./esm/mod.js",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./esm/mod.js"
9
+ }
10
+ },
11
+ "scripts": {},
12
+ "_generatedBy": "dnt@dev"
13
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 Relevance AI
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,121 +0,0 @@
1
- # relevance-js-sdk
2
- Install with npm using:
3
- ```
4
- npm i @relevanceai/sdk
5
- ```
6
- ## Features
7
- - Node and Browser support
8
- - Typescript definitions for almost all [relevanceai.com](https://relevanceai.com/) apis
9
- - Insert millions of documents with one function call
10
- - Our SearchBuilder makes searching, filtering, and aggregating your data simple
11
- # Getting started
12
- Get started by creating an account in [cloud.relevanceai.com](https://cloud.relevanceai.com) - select the Vector Database onboarding option. Once set up you can fetch your API key and use the below snippet.
13
-
14
- ```javascript
15
- import {VecDBClient,QueryBuilder} from "@relevanceai/sdk";
16
-
17
- const discovery = new VecDBClient({
18
- project: '',
19
- api_key: '',
20
- endpoint: ''
21
- });
22
- const dataset = discovery.dataset('1000-movies');
23
-
24
- const movies = [{ title: 'Lord of the Rings: The Fellowship of the Ring', grenre: 'action', budget: 100 }, ...]
25
- await dataset.insertDocuments(movies, [{ model_name: 'text-embedding-ada-002', field: 'title' }]);
26
-
27
- const {results} = await dataset.search(QueryBuilder().vector('title_vector_', { query: 'LOTR', model: 'text-embeddings-ada-002' }));
28
- ```
29
- ## Set up your credentials
30
- ### Option 1 - Use environment variables
31
- First, set environment variables in your shell before you run your code.
32
-
33
- set RELEVANCE_PROJECT to your project name.
34
-
35
- set RELEVANCE_API_KEY to your api key.
36
- for more information, view the docs here: [Authorization docs](https://discovery.relevanceai.com/reference/api-usage)
37
-
38
- Heres a template to copy and paste in for linux environments:
39
- ```bash
40
- export RELEVANCE_PROJECT=#########
41
- export RELEVANCE_API_KEY=#########
42
- ```
43
- The SDK will use these variables when making api calls. You can then initialise your client like this:
44
- ```javascript
45
- import {VecDBClient} from "@relevanceai/sdk";
46
- const client = new VecDBClient({});
47
- ```
48
- ### Option 2 - Passing them in code.
49
- ```javascript
50
- import {VecDBClient} from "@relevanceai/sdk";
51
- const client = new VecDBClient({
52
- project:'########',
53
- api_key:'########',
54
- });
55
- ```
56
- # Examples
57
- ### You can import builders and type definitions like this
58
- ```javascript
59
- import {QueryBuilder,VecDBClient,BulkInsertOutput} from "@relevanceai/sdk";
60
- ```
61
- ## Insert millions of items with one function call
62
- ```javascript
63
- const discovery = new VecDBClient({ ... });
64
- const dataset = discovery.dataset('tshirts-prod');
65
- // Here we create some demo data. Replace this with your real data
66
- const fakeVector = [];
67
- for (let i = 0; i < 768; i++) fakeVector.push(1);
68
- const tshirtsData = [];
69
- for (let i = 0; i < 10000; i++) {
70
- tshirtsData.push({_id:`tshirt-${i}1`,color:'red',price:i/1000,'title-fake_vector_':fakeVector});
71
- tshirtsData.push({_id:`tshirt-${i}2`,color:'blue',price:i/1000});
72
- tshirtsData.push({_id:`tshirt-${i}3`,color:'orange',price:i/1000});
73
- }
74
- const res = await dataset.insertDocuments(tshirtsData,{batchSize:10000});
75
- ```
76
- ### insertDocuments will output:
77
- ```javascript
78
- {"inserted":30000,"failed_documents":[]}
79
- ```
80
- ## Text Search and Vector Search
81
- ```javascript
82
- const builder = QueryBuilder();
83
- builder.query('red').text().vector('title-fake_vector_',0.5).minimumRelevance(0.1);
84
- // .text() searches all fields. alternatively, use .text(field1).text(field2)... to search specific fields
85
- const searchResults = await dataset.search(builder);
86
- ```
87
- ## Filter and retrieve items
88
- ```javascript
89
- const filters = QueryBuilder();
90
- filters.match('color',['blue','red']).range('price',{lessThan:50});
91
- const filteredItems = await dataset.search(filters);
92
- ```
93
- ### search will output:
94
- ```javascript
95
- {
96
- results: [
97
- {
98
- color: 'red',
99
- price: 0,
100
- insert_date_: '2021-11-16T03:14:28.509Z',
101
- _id: 'tshirt-01',
102
- _relevance: 0
103
- }
104
- ...
105
- ],
106
- resultsSize: 10200,
107
- aggregations: {},
108
- aggregates: {},
109
- aggregateStats: {}
110
- }
111
- ```
112
-
113
-
114
- ```
115
- ## Call raw api methods directly
116
- ```javascript
117
- const discovery = new VecDBClient({ ... });
118
- const dataset = discovery.dataset('tshirts-prod');
119
- const {body} = await dataset.apiClient.FastSearch({filters:[{match:{key:'_id',value:`tshirt-01`}}]});
120
- expect((body.results[0] as any).color).toBe('red')
121
- ```