@axiom-lattice/client-sdk 1.0.43 → 1.0.44

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,279 @@
1
+ /**
2
+ * Abstract client class for interacting with the Axiom Lattice Agent Service API
3
+ * Provides common functionality for different client implementations
4
+ */
5
+ export class AbstractClient {
6
+ /**
7
+ * Creates a new AbstractClient instance
8
+ * @param config - Configuration options for the client
9
+ */
10
+ constructor(config) {
11
+ this.tenantId = "";
12
+ this.registeredTools = new Map();
13
+ /**
14
+ * Chat namespace for sending messages and streaming responses
15
+ */
16
+ this.chat = {
17
+ /**
18
+ * Sends a message to a thread and receives a response
19
+ * @param options - Options for sending a message
20
+ * @returns A promise that resolves to the chat response
21
+ */
22
+ send: async (options) => {
23
+ try {
24
+ // Extract the message from the messages array (assuming the last message is the one to send)
25
+ const message = options.messages[options.messages.length - 1];
26
+ const { command, threadId, files, ...rest } = options;
27
+ // Use the run method to send the message
28
+ const result = await this.run({
29
+ threadId: threadId,
30
+ message: typeof message.content === "string"
31
+ ? message.content
32
+ : JSON.stringify(message.content),
33
+ streaming: false,
34
+ command: command,
35
+ files: files,
36
+ ...rest,
37
+ });
38
+ return result;
39
+ }
40
+ catch (error) {
41
+ throw error;
42
+ }
43
+ },
44
+ /**
45
+ * Sends a message to a thread and streams the response
46
+ * @param options - Options for streaming a message
47
+ * @param onEvent - Callback function that receives stream events
48
+ * @param onComplete - Optional callback function called when streaming completes
49
+ * @param onError - Optional callback function called when an error occurs
50
+ * @returns A function that can be called to stop the stream
51
+ */
52
+ stream: (options, onEvent, onComplete, onError) => {
53
+ // Extract the message from the messages array (assuming the last message is the one to send)
54
+ const message = options.messages[options.messages.length - 1];
55
+ // Use the streamRequest method to stream the response
56
+ return this.streamRequest({
57
+ threadId: options.threadId,
58
+ message: typeof message.content === "string"
59
+ ? message.content
60
+ : JSON.stringify(message.content),
61
+ streaming: true,
62
+ command: options.command,
63
+ background: options.background,
64
+ enableReturnStateWhenSteamCompleted: options.enableReturnStateWhenSteamCompleted,
65
+ }, onEvent, onComplete, onError);
66
+ },
67
+ };
68
+ /**
69
+ * Tools namespace for registering and unregistering client-side tools
70
+ */
71
+ this.tools = {
72
+ /**
73
+ * Registers a client-side tool
74
+ * @param options - Options for registering a tool
75
+ */
76
+ register: (options) => {
77
+ if (this.config.transport !== "ws") {
78
+ throw new Error("Client-side tools are only supported with WebSocket transport");
79
+ }
80
+ this.registeredTools.set(options.name, options);
81
+ },
82
+ /**
83
+ * Unregisters a client-side tool
84
+ * @param name - Tool name
85
+ */
86
+ unregister: (name) => {
87
+ this.registeredTools.delete(name);
88
+ },
89
+ };
90
+ this.config = {
91
+ timeout: 300000, // Default timeout
92
+ ...config,
93
+ };
94
+ this.assistantId = config.assistantId;
95
+ }
96
+ /**
97
+ * Abstract method for streaming API requests
98
+ * To be implemented by concrete client classes
99
+ */
100
+ /**
101
+ * Helper method to build stream request parameters
102
+ * @param options - Options for running the agent
103
+ * @returns The formatted request parameters
104
+ */
105
+ buildStreamRequestParams(options) {
106
+ const { command, threadId, message, files, background, ...rest } = options;
107
+ return {
108
+ url: "/api/runs",
109
+ method: "POST",
110
+ body: {
111
+ assistant_id: this.assistantId,
112
+ thread_id: threadId,
113
+ message: message,
114
+ files: files,
115
+ command: command,
116
+ streaming: true,
117
+ background: background || false,
118
+ ...rest,
119
+ },
120
+ };
121
+ }
122
+ /**
123
+ * Creates a new thread
124
+ * @param options - Options for creating a thread
125
+ * @returns A promise that resolves to the thread ID
126
+ */
127
+ async createThread(options) {
128
+ try {
129
+ const data = await this.makeRequest("/threads", {
130
+ method: "POST",
131
+ body: {
132
+ ...options,
133
+ assistantId: this.assistantId,
134
+ },
135
+ });
136
+ return data.id;
137
+ }
138
+ catch (error) {
139
+ throw error;
140
+ }
141
+ }
142
+ /**
143
+ * Retrieves thread information
144
+ * @param threadId - Thread identifier
145
+ * @returns A promise that resolves to the thread information
146
+ */
147
+ async getThread(threadId) {
148
+ try {
149
+ const url = `/threads/${threadId}?assistantId=${this.assistantId}`;
150
+ return await this.makeRequest(url);
151
+ }
152
+ catch (error) {
153
+ throw error;
154
+ }
155
+ }
156
+ /**
157
+ * Lists all threads
158
+ * @param options - Options for listing threads
159
+ * @returns A promise that resolves to an array of threads
160
+ */
161
+ async listThreads(options) {
162
+ try {
163
+ let url = `/threads?assistantId=${this.assistantId}`;
164
+ if (options?.limit) {
165
+ url += `&limit=${options.limit}`;
166
+ }
167
+ if (options?.offset !== undefined) {
168
+ url += `&offset=${options.offset}`;
169
+ }
170
+ const data = await this.makeRequest(url);
171
+ return data.threads;
172
+ }
173
+ catch (error) {
174
+ throw error;
175
+ }
176
+ }
177
+ /**
178
+ * Deletes a thread
179
+ * @param threadId - Thread identifier
180
+ * @returns A promise that resolves when the thread is deleted
181
+ */
182
+ async deleteThread(threadId) {
183
+ try {
184
+ const url = `/threads/${threadId}?assistantId=${this.assistantId}`;
185
+ await this.makeRequest(url, { method: "DELETE" });
186
+ }
187
+ catch (error) {
188
+ throw error;
189
+ }
190
+ }
191
+ /**
192
+ * Retrieves messages from a thread
193
+ * @param options - Options for retrieving messages
194
+ * @returns A promise that resolves to an array of messages
195
+ */
196
+ async getMessages(options) {
197
+ try {
198
+ let url = `/api/assistants/${this.assistantId}/${options.threadId}/memory`;
199
+ if (options.limit) {
200
+ url += `?limit=${options.limit}`;
201
+ }
202
+ if (options.after) {
203
+ url += url.includes("?")
204
+ ? `&after=${options.after}`
205
+ : `?after=${options.after}`;
206
+ }
207
+ if (options.reverse !== undefined) {
208
+ url += url.includes("?")
209
+ ? `&reverse=${options.reverse}`
210
+ : `?reverse=${options.reverse}`;
211
+ }
212
+ url += url.includes("?")
213
+ ? `&assistantId=${this.assistantId}`
214
+ : `?assistantId=${this.assistantId}`;
215
+ return await this.makeRequest(url);
216
+ }
217
+ catch (error) {
218
+ throw error;
219
+ }
220
+ }
221
+ /**
222
+ * Retrieves agent state
223
+ * @param threadId - Thread identifier
224
+ * @returns A promise that resolves to the agent state
225
+ */
226
+ async getAgentState(threadId) {
227
+ try {
228
+ return await this.makeRequest(`/api/assistants/${this.assistantId}/${threadId}/state`);
229
+ }
230
+ catch (error) {
231
+ throw error;
232
+ }
233
+ }
234
+ /**
235
+ * Gets agent graph visualization
236
+ * @returns A promise that resolves to the graph visualization data
237
+ */
238
+ async getAgentGraph() {
239
+ try {
240
+ const data = await this.makeRequest(`/api/assistants/${this.assistantId}/graph`);
241
+ return data.image;
242
+ }
243
+ catch (error) {
244
+ throw error;
245
+ }
246
+ }
247
+ /**
248
+ * Run agent with options
249
+ * @param options - Options for running the agent
250
+ * @returns A promise that resolves to the run result
251
+ */
252
+ async run(options) {
253
+ try {
254
+ const { command, threadId, message, files, background, ...rest } = options;
255
+ if (options.streaming) {
256
+ throw new Error("Streaming without callbacks is not supported. Use chat.stream with callbacks instead.");
257
+ }
258
+ else {
259
+ return await this.makeRequest("/api/runs", {
260
+ method: "POST",
261
+ body: {
262
+ assistant_id: this.assistantId,
263
+ thread_id: threadId,
264
+ message: message,
265
+ files: files,
266
+ command: command,
267
+ streaming: false,
268
+ background: background || false,
269
+ ...rest,
270
+ },
271
+ });
272
+ }
273
+ }
274
+ catch (error) {
275
+ throw error;
276
+ }
277
+ }
278
+ }
279
+ //# sourceMappingURL=abstract-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstract-client.js","sourceRoot":"","sources":["../src/abstract-client.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AACH,MAAM,OAAgB,cAAc;IAMlC;;;OAGG;IACH,YAAY,MAAoB;QAPtB,aAAQ,GAAW,EAAE,CAAC;QACtB,oBAAe,GAAqC,IAAI,GAAG,EAAE,CAAC;QAoPxE;;WAEG;QACH,SAAI,GAAG;YACL;;;;eAIG;YACH,IAAI,EAAE,KAAK,EAAE,OAAwB,EAAyB,EAAE;gBAC9D,IAAI,CAAC;oBACH,6FAA6F;oBAC7F,MAAM,OAAO,GAAG,OAAO,CAAC,Q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AAU,IAAI,KAAK;wBAC/B,GAAG,IAAI;qBACR;iBACF,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CAmGF"}
@@ -0,0 +1,54 @@
1
+ import { MessageChunk } from "@axiom-lattice/protocols";
2
+ import { AgentState, ClientConfig, RunOptions } from "./types";
3
+ import { AbstractClient } from "./abstract-client";
4
+ /**
5
+ * Web client class for interacting with the Axiom Lattice Agent Service API
6
+ */
7
+ export declare class Client extends AbstractClient {
8
+ private headers;
9
+ /**
10
+ * Creates a new Client instance
11
+ * @param config - Configuration options for the client
12
+ */
13
+ constructor(config: ClientConfig);
14
+ /**
15
+ * Helper method to handle fetch responses and errors
16
+ * @private
17
+ */
18
+ private handleResponse;
19
+ /**
20
+ * Helper method to make fetch requests
21
+ * @private
22
+ */
23
+ private fetchWithTimeout;
24
+ /**
25
+ * Set tenant ID for multi-tenant environments
26
+ * @param tenantId - Tenant identifier
27
+ */
28
+ setTenantId(tenantId: string): void;
29
+ /**
30
+ * Implementation of the abstract makeRequest method for web clients
31
+ * @param url - The URL to make the request to
32
+ * @param options - Request options
33
+ * @returns A promise that resolves to the response data
34
+ */
35
+ protected makeRequest<T>(url: string, options?: {
36
+ method?: string;
37
+ body?: any;
38
+ headers?: Record<string, string>;
39
+ }): Promise<T>;
40
+ /**
41
+ * Implementation of the abstract streamRequest method for web clients
42
+ */
43
+ protected streamRequest(options: RunOptions, onEvent: (event: MessageChunk) => void, onComplete?: (state?: AgentState) => void, onError?: (error: Error) => void): () => void;
44
+ /**
45
+ * Stream run results
46
+ * @param options - Options for streaming run results
47
+ * @param onEvent - Callback function that receives stream events
48
+ * @param onComplete - Optional callback function called when streaming completes
49
+ * @param onError - Optional callback function called when an error occurs
50
+ * @returns A function that can be called to stop the stream
51
+ */
52
+ private streamRun;
53
+ }
54
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,UAAU,EAMV,YAAY,EAMZ,UAAU,EAEX,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;GAEG;AACH,qBAAa,MAAO,SAAQ,cAAc;IACxC,OAAO,CAAC,OAAO,CAAyB;IAExC;;;OAGG;gBACS,MAAM,EAAE,YAAY;IAUhC;;;OAGG;YACW,cAAc;IA4B5B;;;OAGG;YACW,gBAAgB;IAqC9B;;;OAGG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAKnC;;;;;OAKG;cACa,WAAW,CAAC,CAAC,EAC3B,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,IAAI,CAAC,EAAE,GAAG,CAAC;QACX,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KAClC,GACA,OAAO,CAAC,CAAC,CAAC;IAmBb;;OAEG;IACH,SAAS,CAAC,aAAa,CACrB,OAAO,EAAE,UAAU,EACnB,OAAO,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,EACtC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,UAAU,KAAK,IAAI,EACzC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAC/B,MAAM,IAAI;IAIb;;;;;;;OAOG;IACH,OAAO,CAAC,SAAS;CAuHlB"}
package/dist/client.js ADDED
@@ -0,0 +1,224 @@
1
+ import { ApiError, AuthenticationError, NetworkError, } from "./types";
2
+ import { AbstractClient } from "./abstract-client";
3
+ /**
4
+ * Web client class for interacting with the Axiom Lattice Agent Service API
5
+ */
6
+ export class Client extends AbstractClient {
7
+ /**
8
+ * Creates a new Client instance
9
+ * @param config - Configuration options for the client
10
+ */
11
+ constructor(config) {
12
+ super(config);
13
+ this.headers = {
14
+ "Content-Type": "application/json",
15
+ Authorization: `Bearer ${this.config.apiKey}`,
16
+ ...this.config.headers,
17
+ };
18
+ }
19
+ /**
20
+ * Helper method to handle fetch responses and errors
21
+ * @private
22
+ */
23
+ async handleResponse(response) {
24
+ if (!response.ok) {
25
+ if (response.status === 401) {
26
+ throw new AuthenticationError("Authentication failed");
27
+ }
28
+ else {
29
+ const errorData = (await response.json().catch(() => ({})));
30
+ throw new ApiError(errorData.message || "API Error", response.status, errorData);
31
+ }
32
+ }
33
+ // For 204 No Content responses
34
+ if (response.status === 204) {
35
+ return {};
36
+ }
37
+ try {
38
+ return (await response.json());
39
+ }
40
+ catch (error) {
41
+ throw new Error(`Failed to parse response: ${error}`);
42
+ }
43
+ }
44
+ /**
45
+ * Helper method to make fetch requests
46
+ * @private
47
+ */
48
+ async fetchWithTimeout(url, options = {}) {
49
+ const controller = new AbortController();
50
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
51
+ try {
52
+ const fullUrl = url.startsWith("http")
53
+ ? url
54
+ : `${this.config.baseURL}${url}`;
55
+ const response = await fetch(fullUrl, {
56
+ ...options,
57
+ headers: {
58
+ ...this.headers,
59
+ ...(options.headers || {}),
60
+ },
61
+ signal: controller.signal,
62
+ });
63
+ return await this.handleResponse(response);
64
+ }
65
+ catch (error) {
66
+ if (error instanceof DOMException && error.name === "AbortError") {
67
+ throw new NetworkError("Request timed out");
68
+ }
69
+ else if (error instanceof TypeError &&
70
+ error.message.includes("fetch")) {
71
+ throw new NetworkError("Network request failed");
72
+ }
73
+ throw error;
74
+ }
75
+ finally {
76
+ clearTimeout(timeoutId);
77
+ }
78
+ }
79
+ /**
80
+ * Set tenant ID for multi-tenant environments
81
+ * @param tenantId - Tenant identifier
82
+ */
83
+ setTenantId(tenantId) {
84
+ this.tenantId = tenantId;
85
+ this.headers["x-tenant-id"] = tenantId;
86
+ }
87
+ /**
88
+ * Implementation of the abstract makeRequest method for web clients
89
+ * @param url - The URL to make the request to
90
+ * @param options - Request options
91
+ * @returns A promise that resolves to the response data
92
+ */
93
+ async makeRequest(url, options) {
94
+ const method = options?.method || "GET";
95
+ const requestHeaders = {
96
+ ...this.headers,
97
+ ...(options?.headers || {}),
98
+ };
99
+ const requestOptions = {
100
+ method,
101
+ headers: requestHeaders,
102
+ };
103
+ if (options?.body) {
104
+ requestOptions.body = JSON.stringify(options.body);
105
+ }
106
+ return this.fetchWithTimeout(url, requestOptions);
107
+ }
108
+ /**
109
+ * Implementation of the abstract streamRequest method for web clients
110
+ */
111
+ streamRequest(options, onEvent, onComplete, onError) {
112
+ return this.streamRun(options, onEvent, onComplete, onError);
113
+ }
114
+ /**
115
+ * Stream run results
116
+ * @param options - Options for streaming run results
117
+ * @param onEvent - Callback function that receives stream events
118
+ * @param onComplete - Optional callback function called when streaming completes
119
+ * @param onError - Optional callback function called when an error occurs
120
+ * @returns A function that can be called to stop the stream
121
+ */
122
+ streamRun(options, onEvent, onComplete, onError) {
123
+ const headers = {
124
+ "Content-Type": "application/json",
125
+ Accept: "text/event-stream",
126
+ ...this.headers,
127
+ };
128
+ if (this.tenantId) {
129
+ headers["x-tenant-id"] = this.tenantId;
130
+ }
131
+ // Create abort controller for cancellation
132
+ const controller = new AbortController();
133
+ const { signal } = controller;
134
+ // Start the streaming request
135
+ (async () => {
136
+ try {
137
+ // Get request parameters from the abstract method
138
+ const requestParams = this.buildStreamRequestParams(options);
139
+ const response = await fetch(`${this.config.baseURL}${requestParams.url}`, {
140
+ method: requestParams.method,
141
+ headers,
142
+ body: JSON.stringify(requestParams.body),
143
+ signal,
144
+ });
145
+ if (!response.ok) {
146
+ throw new Error(`HTTP error! Status: ${response.status}`);
147
+ }
148
+ if (!response.body) {
149
+ throw new Error("Response body is null");
150
+ }
151
+ const reader = response.body.getReader();
152
+ const decoder = new TextDecoder();
153
+ let buffer = "";
154
+ while (true) {
155
+ const { done, value } = await reader.read();
156
+ if (done)
157
+ break;
158
+ // Decode the chunk and append to buffer
159
+ const chunk = decoder.decode(value, { stream: true });
160
+ buffer += chunk;
161
+ // Process complete lines
162
+ const lines = buffer.split("\n");
163
+ // Keep the last potentially incomplete line in the buffer
164
+ buffer = lines.pop() || "";
165
+ for (const line of lines) {
166
+ if (line.trim().startsWith("data: ")) {
167
+ try {
168
+ const eventData = JSON.parse(line.trim().slice(6));
169
+ onEvent(eventData);
170
+ }
171
+ catch (error) {
172
+ console.error("Error parsing SSE data:", line, error);
173
+ if (onError) {
174
+ onError(error instanceof Error ? error : new Error(String(error)));
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ // Process any remaining data in the buffer
181
+ if (buffer && buffer.trim().startsWith("data: ")) {
182
+ try {
183
+ const eventData = JSON.parse(buffer.trim().slice(6));
184
+ onEvent(eventData);
185
+ }
186
+ catch (error) {
187
+ console.error("Error parsing SSE data:", buffer, error);
188
+ }
189
+ }
190
+ if (onComplete) {
191
+ // Fetch agent state before calling onComplete if enabled
192
+ if (options.enableReturnStateWhenSteamCompleted) {
193
+ try {
194
+ const state = await this.getAgentState(options.threadId);
195
+ onComplete(state);
196
+ }
197
+ catch (error) {
198
+ // If getting state fails, still call onComplete without state
199
+ onComplete();
200
+ }
201
+ }
202
+ else {
203
+ // Just call onComplete without state if not enabled
204
+ onComplete();
205
+ }
206
+ }
207
+ }
208
+ catch (error) {
209
+ if (error instanceof DOMException && error.name === "AbortError") {
210
+ // Request was cancelled, no need to call onError
211
+ return;
212
+ }
213
+ if (onError) {
214
+ onError(error instanceof Error ? error : new Error(String(error)));
215
+ }
216
+ }
217
+ })();
218
+ // Return a function to cancel the fetch request
219
+ return () => {
220
+ controller.abort();
221
+ };
222
+ }
223
+ }
224
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,QAAQ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