forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapi.ts
529 lines (481 loc) · 15.5 KB
/
api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import type { Agent, Character, UUID, Memory } from '@elizaos/core';
import { WorldManager } from './world-manager';
import { deepMerge } from './utils';
const API_PREFIX = '/api';
/**
* A function that handles fetching data from a specified URL with various options.
*
* @param url - The URL to fetch data from.
* @param method - The HTTP method to use for the request. Defaults to "GET" if not provided.
* @param body - The data to be sent in the request body. Can be either an object or FormData.
* @param headers - The headers to include in the request.
* @returns A Promise that resolves to the response data based on the Content-Type of the response.
*/
const fetcher = async ({
url,
method,
body,
headers,
}: {
url: string;
method?: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';
body?: object | FormData;
headers?: HeadersInit;
}) => {
// Ensure URL starts with a slash if it's a relative path
const normalizedUrl = API_PREFIX + (url.startsWith('/') ? url : `/${url}`);
console.log('API Request:', method || 'GET', normalizedUrl);
const options: RequestInit = {
method: method ?? 'GET',
headers: headers
? headers
: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
};
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
if (body instanceof FormData) {
if (options.headers && typeof options.headers === 'object') {
// Create new headers object without Content-Type
options.headers = Object.fromEntries(
Object.entries(options.headers as Record<string, string>).filter(
([key]) => key !== 'Content-Type'
)
);
}
options.body = body;
} else {
options.body = JSON.stringify(body);
}
}
try {
const response = await fetch(normalizedUrl, options);
const contentType = response.headers.get('Content-Type');
if (contentType === 'audio/mpeg') {
return await response.blob();
}
if (!response.ok) {
const errorText = await response.text();
console.error('API Error:', response.status, response.statusText);
console.error('Response:', errorText);
let errorMessage = `Error ${response.status}: ${response.statusText}`;
try {
const errorObj = JSON.parse(errorText);
errorMessage = errorObj.message || errorMessage;
} catch {
// If we can't parse as JSON, use the raw text
if (errorText.includes('<!DOCTYPE html>')) {
errorMessage = 'Received HTML instead of JSON. API endpoint may be incorrect.';
} else {
errorMessage = errorText || errorMessage;
}
}
throw new Error(errorMessage);
}
// For successful responses, try to parse as JSON
if (contentType?.includes('application/json')) {
try {
return await response.json();
} catch (error) {
console.error('JSON Parse Error:', error);
const text = await response.text();
console.error('Response text:', text.substring(0, 500) + (text.length > 500 ? '...' : ''));
throw new Error('Failed to parse JSON response');
}
} else {
// For non-JSON responses, return text
return await response.text();
}
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
};
// Add these interfaces near the top with other types
/**
* Interface representing a log entry.
* @property {number} level - The log level.
* @property {number} time - The timestamp of the log entry.
* @property {string} msg - The log message.
* @property {string | number | boolean | null | undefined} [key] - Additional properties for the log entry.
*/
interface LogEntry {
level: number;
time: number;
msg: string;
[key: string]: string | number | boolean | null | undefined;
}
/**
* Interface representing a log response.
* @typedef {Object} LogResponse
* @property {LogEntry[]} logs - Array of log entries.
* @property {number} count - Number of log entries in the response.
* @property {number} total - Total number of log entries available.
* @property {string} level - Log level of the response.
* @property {string[]} levels - Array of available log levels.
*/
interface LogResponse {
logs: LogEntry[];
count: number;
total: number;
level: string;
levels: string[];
}
interface AgentLog {
id?: string;
type?: string;
timestamp?: number;
message?: string;
details?: string;
roomId?: string;
[key: string]: any;
}
/**
* Library for interacting with the API to perform various actions related to agents, messages, rooms, logs, etc.
* @type {{
* apiClient: {
* sendMessage: (agentId: string, message: string, selectedFile?: File | null, roomId?: UUID) => Promise<any>;
* getAgents: () => Promise<any>;
* getAgent: (agentId: string) => Promise<{ data: Agent }>;
* tts: (agentId: string, text: string) => Promise<any>;
* whisper: (agentId: string, audioBlob: Blob) => Promise<any>;
* sendAudioMessage: (agentId: string, audioBlob: Blob, options?: { roomId?: string; entityId?: string; userName?: string; name?: string; }) => Promise<any>;
* speechConversation: (agentId: string, text: string, options?: { roomId?: string; entityId?: string; userName?: string; name?: string; }) => Promise<any>;
* deleteAgent: (agentId: string) => Promise<{ success: boolean }>;
* updateAgent: (agentId: string, agent: Agent) => Promise<any>;
* createAgent: (params: { characterPath?: string; characterJson?: Character; }) => Promise<any>;
* startAgent: (agentId: UUID) => Promise<any>;
* stopAgent: (agentId: string) => Promise<any>;
* getMemories: (agentId: string, roomId: string, options?: { limit?: number; before?: number; }) => Promise<any>;
* getRooms: (agentId: string) => Promise<any>;
* createRoom: (agentId: string, roomName: string) => Promise<any>;
* getRoom: (agentId: string, roomId: string) => Promise<any>;
* updateRoom: (agentId: string, roomId: string, updates: { name?: string; worldId?: string; }) => Promise<any>;
* deleteRoom: (agentId: string, roomId: string) => Promise<any>;
* getLogs: (level: string) => Promise<LogResponse>;
* getAgentLogs: (agentId: string, options?: { roomId?: UUID; type?: string; count?: number; offset?: number }) => Promise<{ success: boolean; data: AgentLog[] }>;
* deleteLog: (agentId: string, logId: string) => Promise<void>;
* getAgentMemories: (agentId: UUID, roomId?: UUID, tableName?: string) => Promise<any>;
* deleteAgentMemory: (agentId: UUID, memoryId: string) => Promise<any>;
* updateAgentMemory: (agentId: UUID, memoryId: string, memoryData: Partial<Memory>) => Promise<any>;
* }
* }}
*/
export const apiClient = {
getAgents: () => fetcher({ url: '/agents' }),
getAgent: (agentId: string): Promise<{ data: Agent }> => fetcher({ url: `/agents/${agentId}` }),
ping: (): Promise<{ pong: boolean; timestamp: number }> => fetcher({ url: '/ping' }),
tts: (agentId: string, text: string) =>
fetcher({
url: `/agents/${agentId}/speech/generate`,
method: 'POST',
body: {
text,
},
headers: {
'Content-Type': 'application/json',
Accept: 'audio/mpeg',
'Transfer-Encoding': 'chunked',
},
}),
whisper: async (agentId: string, audioBlob: Blob) => {
const formData = new FormData();
formData.append('file', audioBlob, 'recording.wav');
return fetcher({
url: `/agents/${agentId}/transcriptions`,
method: 'POST',
body: formData,
});
},
sendAudioMessage: async (
agentId: string,
audioBlob: Blob,
options?: {
roomId?: string;
entityId?: string;
userName?: string;
name?: string;
}
) => {
const formData = new FormData();
formData.append('file', audioBlob, 'recording.wav');
// Add optional parameters if provided
if (options) {
for (const [key, value] of Object.entries(options)) {
if (value) formData.append(key, value);
}
}
return fetcher({
url: `/agents/${agentId}/audio-messages`,
method: 'POST',
body: formData,
});
},
speechConversation: async (
agentId: string,
text: string,
options?: {
roomId?: string;
entityId?: string;
userName?: string;
name?: string;
}
) => {
return fetcher({
url: `/agents/${agentId}/speech/conversation`,
method: 'POST',
body: {
text,
...options,
},
headers: {
'Content-Type': 'application/json',
Accept: 'audio/mpeg',
'Transfer-Encoding': 'chunked',
},
});
},
deleteAgent: (agentId: string): Promise<{ success: boolean }> =>
fetcher({ url: `/agents/${agentId}`, method: 'DELETE' }),
updateAgent: async (agentId: string, agent: Agent) => {
// First get the current agent to ensure we have complete data
try {
const currentAgentResponse = await fetcher({ url: `/agents/${agentId}` });
const currentAgent = currentAgentResponse.data;
// If we have the current agent, merge the updates with it
// This ensures all JSONb fields are properly handled
const mergedAgent = currentAgent ? deepMerge(currentAgent, agent) : agent;
return fetcher({
url: `/agents/${agentId}`,
method: 'PATCH',
body: mergedAgent,
});
} catch (error) {
// If we can't get the current agent for some reason, just send the update
console.warn('Could not fetch current agent data before update:', error);
return fetcher({
url: `/agents/${agentId}`,
method: 'PATCH',
body: agent,
});
}
},
createAgent: (params: { characterPath?: string; characterJson?: Character }) =>
fetcher({
url: '/agents/',
method: 'POST',
body: params,
}),
startAgent: (agentId: UUID) =>
fetcher({
url: `/agents/${agentId}`,
method: 'POST',
body: { start: true },
}),
stopAgent: (agentId: string) => {
return fetcher({
url: `/agents/${agentId}`,
method: 'PUT',
});
},
getMemories: (agentId: string, roomId: string, options?: { limit?: number; before?: number }) => {
const worldId = WorldManager.getWorldId();
const params: Record<string, string | number> = { worldId };
if (options?.limit) {
params.limit = options.limit;
}
if (options?.before) {
params.end = options.before;
}
return fetcher({
url: `/agents/${agentId}/rooms/${roomId}/memories`,
method: 'GET',
body: params,
});
},
// Room-related routes
getRooms: () => {
const worldId = WorldManager.getWorldId();
return fetcher({
url: `/world/${worldId}/rooms`,
method: 'GET',
});
},
getRoomsForParticipant: (agentId: string) => {
const worldId = WorldManager.getWorldId();
return fetcher({
url: `/agents/${agentId}/rooms`,
method: 'GET',
body: { worldId },
});
},
createRoom: (agentId: string, roomName: string) => {
const worldId = WorldManager.getWorldId();
return fetcher({
url: `/agents/${agentId}/rooms`,
method: 'POST',
body: {
name: roomName,
worldId,
},
});
},
// Room management functions
getRoom: (agentId: string, roomId: string) => {
return fetcher({
url: `/agents/${agentId}/rooms/${roomId}`,
method: 'GET',
});
},
updateRoom: (agentId: string, roomId: string, updates: { name?: string; worldId?: string }) => {
return fetcher({
url: `/agents/${agentId}/rooms/${roomId}`,
method: 'PATCH',
body: updates,
});
},
deleteRoom: (agentId: string, roomId: string) => {
return fetcher({
url: `/agents/${agentId}/rooms/${roomId}`,
method: 'DELETE',
});
},
// Add this new method
getLogs: ({
level,
agentName,
agentId,
}: {
level?: string;
agentName?: string;
agentId?: string;
}): Promise<LogResponse> => {
const params = new URLSearchParams();
if (level) params.append('level', level);
if (agentName) params.append('agentName', agentName);
if (agentId) params.append('agentId', agentId);
const url = `/logs${params.toString() ? `?${params.toString()}` : ''}`;
return fetcher({
url,
method: 'GET',
});
},
// Method to clear logs
deleteLogs: (): Promise<{ status: string; message: string }> => {
return fetcher({
url: '/logs',
method: 'DELETE',
});
},
getAgentCompletion: (
agentId: string,
senderId: string,
message: string,
roomId: UUID,
source: string
) => {
return fetcher({
url: `/agents/${agentId}/message`,
method: 'POST',
body: {
text: message,
roomId: roomId,
senderId,
source,
},
});
},
// Agent Log/Action endpoints
getAgentLogs: (
agentId: string,
options?: { roomId?: UUID; type?: string; count?: number; offset?: number }
): Promise<{ success: boolean; data: AgentLog[] }> => {
const params = new URLSearchParams();
if (options?.roomId) params.append('roomId', options.roomId);
if (options?.type) params.append('type', options.type);
if (options?.count) params.append('count', options.count.toString());
if (options?.offset) params.append('offset', options.offset.toString());
return fetcher({
url: `/agents/${agentId}/logs${params.toString() ? `?${params.toString()}` : ''}`,
method: 'GET',
});
},
deleteLog: (agentId: string, logId: string): Promise<void> => {
return fetcher({
url: `/agents/${agentId}/logs/${logId}`,
method: 'DELETE',
});
},
// Method to get all memories for an agent, optionally filtered by room
getAgentMemories: (agentId: UUID, roomId?: UUID, tableName?: string) => {
const params = new URLSearchParams();
if (tableName) params.append('tableName', tableName);
const url = roomId
? `/agents/${agentId}/rooms/${roomId}/memories`
: `/agents/${agentId}/memories${params.toString() ? `?${params.toString()}` : ''}`;
return fetcher({
url,
method: 'GET',
});
},
// Method to delete a specific memory for an agent
deleteAgentMemory: (agentId: UUID, memoryId: string) => {
return fetcher({
url: `/agents/${agentId}/memories/${memoryId}`,
method: 'DELETE',
});
},
updateAgentMemory: (agentId: UUID, memoryId: string, memoryData: Partial<Memory>) => {
return fetcher({
url: `/agents/${agentId}/memories/${memoryId}`,
method: 'PATCH',
body: memoryData,
});
},
// Method to upload knowledge for an agent
uploadKnowledge: async (agentId: string, files: File[]): Promise<any> => {
const formData = new FormData();
for (const file of files) {
formData.append('files', file);
}
return fetcher({
url: `/agents/${agentId}/memories/upload-knowledge`,
method: 'POST',
body: formData,
});
},
getGroupMemories: (serverId: UUID) => {
const worldId = WorldManager.getWorldId();
return fetcher({
url: `/world/${worldId}/memories/${serverId}`,
method: 'GET',
});
},
createGroupChat: (
agentIds: string[],
roomName: string,
serverId: string,
source: string,
metadata?: any
) => {
const worldId = WorldManager.getWorldId();
return fetcher({
url: `/agents/groups/${serverId}`,
method: 'POST',
body: {
agentIds,
name: roomName,
worldId,
source,
metadata,
},
});
},
deleteGroupChat: (serverId: string) => {
return fetcher({
url: `/agents/groups/${serverId}`,
method: 'DELETE',
});
},
};