@relevanceai/sdk 2.0.2 → 3.0.0-alpha.1

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/LICENSE +1 -1
  2. package/README.md +304 -105
  3. package/esm/agent-task.d.ts +61 -0
  4. package/esm/agent-task.js +112 -0
  5. package/esm/agent.d.ts +17 -0
  6. package/esm/agent.js +52 -0
  7. package/esm/client.d.ts +36 -0
  8. package/esm/client.js +69 -0
  9. package/esm/events.d.ts +40 -0
  10. package/esm/events.js +39 -0
  11. package/esm/key.d.ts +86 -0
  12. package/esm/key.js +121 -0
  13. package/esm/message.d.ts +18 -0
  14. package/esm/message.js +18 -0
  15. package/esm/mod.d.ts +7 -0
  16. package/esm/mod.js +4 -0
  17. package/esm/package.json +3 -0
  18. package/esm/region.d.ts +5 -0
  19. package/esm/region.js +6 -0
  20. package/esm/task.d.ts +25 -0
  21. package/esm/task.js +96 -0
  22. package/esm/utils.d.ts +8 -0
  23. package/esm/utils.js +29 -0
  24. package/package.json +11 -36
  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
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2021 Relevance AI
3
+ Copyright (c) 2025 Relevance AI
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,121 +1,320 @@
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: ''
1
+ # Relevance AI JavaScript SDK
2
+
3
+ Build full-stack AI applications using our JavaScript SDK. This multi-environment
4
+ SDK enables you to integrate, extend, or build end-to-end solutions on top of
5
+ our powerful AI Workforce platform.
6
+
7
+ > **Note:** The SDK is in active development and not all features are available
8
+ > yet. Please refer to our roadmap for updates.
9
+
10
+ ## Quickstart
11
+
12
+ ```js
13
+ import { createClient, AU_REGION } from "@relevanceai/sdk";
14
+
15
+ // Create a client with your credentials
16
+ const client = createClient({
17
+ apiKey: "sk-abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKL",
18
+ region: AU_REGION,
19
+ project: "12345678-90ab-cdef-1234-567890abcdef",
20
+ });
21
+
22
+ // Create a task for an agent
23
+ const task = client.createTask({
24
+ agent: "fedcba09-8765-4321-fedc-ba0987654321",
21
25
  });
22
- const dataset = discovery.dataset('1000-movies');
23
26
 
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' }]);
27
+ // Send a message to the agent
28
+ task.sendMessage(
29
+ "What is the weather like in Sydney, Australia this weekend?"
30
+ );
26
31
 
27
- const {results} = await dataset.search(QueryBuilder().vector('title_vector_', { query: 'LOTR', model: 'text-embeddings-ada-002' }));
32
+ // Listen for responses
33
+ task.addEventListener("message", ({ detail }) => {
34
+ const { message } = detail;
35
+ console.log(message.text);
36
+
37
+ task.sendMessage("Thanks!");
38
+
39
+ // Important: Stop listening when done to prevent memory leaks
40
+ task.stopListening();
41
+ });
28
42
  ```
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
43
 
33
- set RELEVANCE_PROJECT to your project name.
44
+ ## Getting Started
45
+
46
+ The JavaScript SDK is a stateless, event-driven toolkit that provides the
47
+ flexibility to build any application you need. It sits on top of our API and
48
+ offers a streamlined developer experience, making it easier for your apps to
49
+ integrate with agents, tools, and workforces.
50
+
51
+ This multi-environment library allows you to build wherever modern JavaScript
52
+ runs:
34
53
 
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)
54
+ - Node.js
55
+ - Deno
56
+ - Bun
57
+ - Cloudflare Workers
58
+ - Browser
59
+
60
+ ### Installation
61
+
62
+ Install the SDK for your environment:
37
63
 
38
- Heres a template to copy and paste in for linux environments:
39
64
  ```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:'########',
65
+ # Node.js / Cloudflare Workers / Browser (with bundler)
66
+ npm install @relevanceai/sdk@latest
67
+
68
+ # Deno
69
+ deno add jsr:@relevanceai/sdk
70
+
71
+ # Bun
72
+ bun add @relevanceai/sdk@latest
73
+ ```
74
+
75
+ #### Browser (CDN)
76
+
77
+ If you are developing a frontend application and not using a bundler like
78
+ [Vite](https://vite.dev) or [Webpack](https://webpack.js.org), you can use the
79
+ CDN version directly:
80
+
81
+ ```html
82
+ <script type="importmap">
83
+ {
84
+ "imports": {
85
+ "@relevanceai/sdk": "https://esm.run/@relevanceai/sdk"
86
+ }
87
+ }
88
+ </script>
89
+ <script type="module">
90
+ import { createClient } from "@relevanceai/sdk";
91
+ // ...
92
+ </script>
93
+ ```
94
+
95
+ ## Usage
96
+
97
+ ### Keys
98
+
99
+ To communicate with Relevance AI, you will need a key. Keys authenticate your
100
+ requests and grant access to your project.
101
+
102
+ There are two types of keys: _API_ and _Embed_.
103
+
104
+ #### API Key
105
+
106
+ API keys grant access to the entire project, including agents, tools, and
107
+ workforces. This key is best used for server-side applications or protected web
108
+ apps where third parties do not have access.
109
+
110
+ Using the default client `createClient({ apiKey, region, project })` will create
111
+ an API Key for convenience. Alternatively, you can create a `Key` instance and
112
+ pass it to the client.
113
+
114
+ ```js
115
+ import { createClient, Key, AU_REGION } from "@relevanceai/sdk";
116
+
117
+ const apiKey = "sk-...";
118
+ const region = AU_REGION;
119
+ const project = "1234...";
120
+
121
+ const key = new Key({ apiKey, region, project });
122
+ const client = createClient(key);
123
+ ```
124
+
125
+ #### Embed Key
126
+
127
+ If you are developing a web app that allows third-party access, such as for your
128
+ customers, it's best to share resources from the Relevance AI platform. This
129
+ makes them available for public use and requires an embed key scoped only to
130
+ that resource.
131
+
132
+ To get an embed key, specify which public resource you wish to scope it to. For
133
+ example, to create an embed key for a publicly available agent in your project:
134
+
135
+ ```js
136
+ import { createClient, Key, AU_REGION } from "@relevanceai/sdk";
137
+
138
+ const region = AU_REGION;
139
+ const project = "1234...";
140
+ const agent = "abcd..."; // a *public* agent
141
+
142
+ const embedKey = await Key.generateEmbedKey({ region, project, agent });
143
+ const client = createClient(embedKey);
144
+ ```
145
+
146
+ ### Clients
147
+
148
+ A client is the main entry point for the SDK. It configures communication with
149
+ Relevance AI and manages authentication.
150
+
151
+ You can create multiple clients, which is useful for multi-project setups.
152
+
153
+ ```js
154
+ import { Client, Key, AU_REGION } from "@relevanceai/sdk";
155
+
156
+ const apiKey = "sk-...";
157
+ const region = AU_REGION;
158
+ const projectOne = "1234...";
159
+ const projectTwo = "abcd...";
160
+
161
+ const oneKey = new Key({ apiKey, region, project: projectOne });
162
+ const twoKey = new Key({ apiKey, region, project: projectTwo });
163
+
164
+ const oneClient = new Client(oneKey);
165
+ const twoClient = new Client(twoKey);
166
+ ```
167
+
168
+ #### Default client
169
+
170
+ Typically, you will only need a single client. In this case, use the default
171
+ client factory as shown in the quickstart:
172
+
173
+ ```js
174
+ import { createClient, Client } from "@relevanceai/sdk";
175
+
176
+ const client = createClient({ apiKey, region, project });
177
+
178
+ // elsewhere in your app
179
+ Client.default();
180
+ ```
181
+
182
+ Attempting to create more than one default client will throw an error. Referencing
183
+ the default client before creating one will also throw an error.
184
+
185
+ ### Tasks
186
+
187
+ Whenever you run anything in Relevance AI, these are known as tasks. Tasks have
188
+ a subject: an agent, tool, or workforce. You can send messages to these subjects,
189
+ receive replies, and follow updates and errors.
190
+
191
+ > **Important:** Always call `task.stopListening()` when you're done with a task
192
+ > to prevent memory leaks and clean up resources properly.
193
+
194
+ #### Creating Tasks
195
+
196
+ The easiest way to create a new task is to use the client's convenient method
197
+ `createTask` and provide the subject ID.
198
+
199
+ ```js
200
+ const agentId = "1234...";
201
+ const task = client.createTask({ agent: agentId });
202
+ ```
203
+
204
+ #### Sending a Message
205
+
206
+ Once you have a task instance, you can send messages to the subject using the
207
+ `sendMessage()` method.
208
+
209
+ ```js
210
+ task.sendMessage("How many letter r's are there in the word 'strawberry'?");
211
+ ```
212
+
213
+ Note that this call is not `async`. It sends the message and does not `await`
214
+ a reply. This is intentional, as tasks are event-driven.
215
+
216
+ ### Events
217
+
218
+ Tasks are event-driven and an application must listen to predefined events to
219
+ manage the status and messages of a task.
220
+
221
+ Use `.addEventListener()` to listen for task events.
222
+
223
+ ```js
224
+ task.sendMessage("What came first; the chicken or the egg?");
225
+
226
+ task.addEventListener("message", ({ detail }) => {
227
+ const { message } = detail;
228
+ console.log("> %s", message.text);
54
229
  });
55
230
  ```
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});
231
+
232
+ Tasks dispatch `CustomEvent`. Event properties will be set in the `detail`
233
+ field of the event. You can see the types of events for more information about
234
+ the properties associated with different events.
235
+
236
+ Remember to call `task.stopListening()` once you no longer need to listen to
237
+ the task.
238
+
239
+ ---
240
+
241
+ The following events are available for agent subjects.
242
+
243
+ #### `start`
244
+
245
+ When a _new_ task starts.
246
+
247
+ **Details**
248
+
249
+ ```ts
250
+ interface StartEventDetails {
251
+ id: string;
252
+ status: TaskStatus;
73
253
  }
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: {}
254
+ ```
255
+
256
+ #### `status`
257
+
258
+ Whenever the task's _status_ changes.
259
+
260
+ > **Note:** this event does **not** fire for starting status. Use the `start`
261
+ > event if you need the initial status.
262
+
263
+ **Details**
264
+
265
+ ```ts
266
+ interface StatusEventDetails {
267
+ status: TaskStatus;
268
+ }
269
+ ```
270
+
271
+ ##### `update`
272
+
273
+ A task has updated. This update will always be a tool for now but may expand in
274
+ the future.
275
+
276
+ **Details**
277
+
278
+ ```ts
279
+ interface UpdateEventDetails {
280
+ update: TaskMessage<"tool">;
281
+ }
282
+ ```
283
+
284
+ #### `message`
285
+
286
+ A task has received a message.
287
+
288
+ > **Note:** you will receive messages from _both_ subjects and users.
289
+
290
+ **Details**
291
+
292
+ ```ts
293
+ interface MessageEventDetails {
294
+ message: TaskMessage<"agent" | "user">;
110
295
  }
111
296
  ```
112
297
 
298
+ #### `error`
299
+
300
+ Whenever the task has failed.
113
301
 
302
+ **Details**
303
+
304
+ ```ts
305
+ interface ErrorEventDetails {
306
+ error: TaskMessage<"error">;
307
+ }
308
+ ```
309
+
310
+ **Example**
311
+
312
+ ```js
313
+ task.addEventListener("error", ({ detail }) => {
314
+ const { error } = detail;
315
+ console.error("Task failed:", error.text);
316
+
317
+ // clean up
318
+ task.stopListening();
319
+ });
114
320
  ```
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
- ```
@@ -0,0 +1,61 @@
1
+ import type { Agent } from "./agent.js";
2
+ import { TaskMessage } from "./message.js";
3
+ import { Task, type TaskStatus } from "./task.js";
4
+ type AgentTaskEvents = {
5
+ start: {
6
+ status: TaskStatus;
7
+ };
8
+ status: {
9
+ status: TaskStatus;
10
+ };
11
+ message: {
12
+ message: TaskMessage<"agent-message" | "user-message">;
13
+ };
14
+ update: {
15
+ message: TaskMessage<"tool-run">;
16
+ };
17
+ };
18
+ export type AgentTaskState = "idle" | "starting-up" | "running" | "pending-approval" | "waiting-for-capacity" | "cancelled" | "timed-out" | "escalated" | "unrecoverable" | "paused" | "completed" | "errored-pending-approval" | "queued-for-approval" | "queued-for-rerun";
19
+ /**
20
+ * AgentTask represents a conversation task with an AI agent. It extends the
21
+ * base Task class with agent-specific functionality for sending messages and
22
+ * retrieving conversation history.
23
+ *
24
+ * @see {@link Task} for the base task functionality.
25
+ * @see {@link Agent} for the agent this task is associated with.
26
+ *
27
+ * @class AgentTask
28
+ * @extends Task<Agent, AgentTaskEvents>
29
+ */
30
+ export declare class AgentTask extends Task<Agent, AgentTaskEvents> {
31
+ /**
32
+ * Sends a message to the agent. This method triggers the agent with the
33
+ * message and updates the task ID if this is the first message.
34
+ *
35
+ * Note: This method is asynchronous but doesn't return a promise. Use event
36
+ * listeners to track the response.
37
+ *
38
+ * @param {string} message
39
+ */
40
+ sendMessage(message: string): void;
41
+ /**
42
+ * Fetches the current status of the task from the API.
43
+ *
44
+ * @returns {Promise<TaskStatus>} The current task status.
45
+ * @throws {Error} if the agent or task ID is missing.
46
+ */
47
+ fetchStatus(): Promise<TaskStatus>;
48
+ /**
49
+ * Fetches messages from the conversation.
50
+ *
51
+ * @param {Object} [options] Optional fetch options.
52
+ * @param {Date} [options.from] Fetch messages after this timestamp.
53
+ *
54
+ * @returns {Promise<TaskMessage[]>} Array of messages in ascending order.
55
+ * @throws {Error} if the agent or task ID is missing.
56
+ */
57
+ fetchMessages({ from }?: {
58
+ from?: Date;
59
+ }): Promise<TaskMessage[]>;
60
+ }
61
+ export {};
@@ -0,0 +1,112 @@
1
+ import { TaskMessage } from "./message.js";
2
+ import { Task } from "./task.js";
3
+ /**
4
+ * Converts an AgentTaskState to a simplified TaskStatus.
5
+ *
6
+ * @internal
7
+ *
8
+ * @param {AgentTaskState} state The agent task state to convert.
9
+ * @returns {TaskStatus} The simplified task status.
10
+ */
11
+ function stateToStatus(state) {
12
+ switch (state) {
13
+ case "paused":
14
+ case "idle":
15
+ return "idle";
16
+ case "starting-up":
17
+ case "waiting-for-capacity":
18
+ case "queued-for-approval":
19
+ case "queued-for-rerun":
20
+ return "queued";
21
+ case "running":
22
+ return "running";
23
+ case "pending-approval":
24
+ case "escalated":
25
+ return "action";
26
+ case "timed-out":
27
+ return "error";
28
+ case "cancelled":
29
+ case "completed":
30
+ return "complete";
31
+ case "unrecoverable":
32
+ case "errored-pending-approval":
33
+ return "error";
34
+ default:
35
+ throw new Error(`unhandled task state: ${state}`);
36
+ }
37
+ }
38
+ /**
39
+ * AgentTask represents a conversation task with an AI agent. It extends the
40
+ * base Task class with agent-specific functionality for sending messages and
41
+ * retrieving conversation history.
42
+ *
43
+ * @see {@link Task} for the base task functionality.
44
+ * @see {@link Agent} for the agent this task is associated with.
45
+ *
46
+ * @class AgentTask
47
+ * @extends Task<Agent, AgentTaskEvents>
48
+ */
49
+ export class AgentTask extends Task {
50
+ /**
51
+ * Sends a message to the agent. This method triggers the agent with the
52
+ * message and updates the task ID if this is the first message.
53
+ *
54
+ * Note: This method is asynchronous but doesn't return a promise. Use event
55
+ * listeners to track the response.
56
+ *
57
+ * @param {string} message
58
+ */
59
+ sendMessage(message) {
60
+ this.subject.trigger(message, this.id || undefined).then(({ id, state }) => {
61
+ // started
62
+ if (!this.id) {
63
+ this.setId(id, stateToStatus(state));
64
+ }
65
+ });
66
+ }
67
+ /**
68
+ * Fetches the current status of the task from the API.
69
+ *
70
+ * @returns {Promise<TaskStatus>} The current task status.
71
+ * @throws {Error} if the agent or task ID is missing.
72
+ */
73
+ async fetchStatus() {
74
+ if (!this.subject.id) {
75
+ throw new Error("expecting agent id");
76
+ }
77
+ if (!this.id) {
78
+ return "not-started";
79
+ }
80
+ const url = `/agents/${this.subject.id}/tasks/${this.id}/metadata`;
81
+ const res = await this.client.fetch(url);
82
+ return stateToStatus(res.metadata.conversation.state);
83
+ }
84
+ /**
85
+ * Fetches messages from the conversation.
86
+ *
87
+ * @param {Object} [options] Optional fetch options.
88
+ * @param {Date} [options.from] Fetch messages after this timestamp.
89
+ *
90
+ * @returns {Promise<TaskMessage[]>} Array of messages in ascending order.
91
+ * @throws {Error} if the agent or task ID is missing.
92
+ */
93
+ async fetchMessages({ from = new Date(0) } = {}) {
94
+ if (!this.subject.id) {
95
+ throw new Error("expecting agent id");
96
+ }
97
+ if (!this.id) {
98
+ throw new Error("expecting task id");
99
+ }
100
+ const url = `/agents/${this.subject.id}/tasks/${this.id}/view`;
101
+ const res = await this.client.fetch(url, {
102
+ method: "POST",
103
+ body: JSON.stringify({
104
+ cursor: {
105
+ after: from.toISOString(),
106
+ },
107
+ }),
108
+ });
109
+ // message should be in ascending order
110
+ return res.results.reverse().map((data) => new TaskMessage(data));
111
+ }
112
+ }
package/esm/agent.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { AgentTaskState } from "./agent-task.js";
2
+ import { Client } from "./client.js";
3
+ export declare class Agent {
4
+ #private;
5
+ private readonly client;
6
+ static fetch(agentId: string, cli?: Client): Promise<Agent>;
7
+ private constructor();
8
+ get id(): string;
9
+ get name(): string | undefined;
10
+ get description(): string | undefined;
11
+ get avatar(): string | undefined;
12
+ isPublic(): boolean;
13
+ trigger(message: string, taskId?: string): Promise<{
14
+ id: string;
15
+ state: AgentTaskState;
16
+ }>;
17
+ }
package/esm/agent.js ADDED
@@ -0,0 +1,52 @@
1
+ import { Client } from "./client.js";
2
+ import { randomUUID } from "./utils.js";
3
+ const taskPrefixDelimiter = "_-_";
4
+ export class Agent {
5
+ #config;
6
+ client;
7
+ static async fetch(agentId, cli = Client.default()) {
8
+ const config = await cli.fetch(`/agents/${agentId}/get`);
9
+ return new Agent(config.agent, cli);
10
+ }
11
+ constructor(config, client) {
12
+ this.#config = config;
13
+ this.client = client;
14
+ }
15
+ get id() {
16
+ return this.#config.agent_id;
17
+ }
18
+ get name() {
19
+ return this.#config.name;
20
+ }
21
+ get description() {
22
+ return this.#config.description;
23
+ }
24
+ get avatar() {
25
+ return this.#config.emoji;
26
+ }
27
+ isPublic() {
28
+ return this.#config.public;
29
+ }
30
+ async trigger(message, taskId) {
31
+ // embed keys require a task prefixing for new tasks
32
+ if (!taskId && this.client.isEmbedKey()) {
33
+ taskId = [this.client.key.taskPrefix, await randomUUID()].join(taskPrefixDelimiter);
34
+ }
35
+ const res = await this.client.fetch("/agents/trigger", {
36
+ method: "POST",
37
+ body: JSON.stringify({
38
+ agent_id: this.#config.agent_id,
39
+ conversation_id: taskId,
40
+ message: {
41
+ role: "user",
42
+ content: message,
43
+ attachments: [], // @todo
44
+ },
45
+ }),
46
+ });
47
+ return {
48
+ id: res.conversation_id,
49
+ state: res.state,
50
+ };
51
+ }
52
+ }