forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
111 lines (101 loc) · 3.07 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
import { type UUID, type Character } from "@elizaos/core";
const BASE_URL = `http://localhost:${import.meta.env.VITE_SERVER_PORT}`;
const fetcher = async ({
url,
method,
body,
headers,
}: {
url: string;
method?: "GET" | "POST";
body?: object | FormData;
headers?: HeadersInit;
}) => {
const options: RequestInit = {
method: method ?? "GET",
headers: headers
? headers
: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
if (method === "POST") {
if (body instanceof FormData) {
// @ts-expect-error - Suppressing potentially undefined options header
delete options.headers["Content-Type"];
options.body = body;
} else {
options.body = JSON.stringify(body);
}
}
return fetch(`${BASE_URL}${url}`, options).then(async (resp) => {
if (resp.ok) {
const contentType = resp.headers.get("Content-Type");
if (contentType === "audio/mpeg") {
return await resp.blob();
}
return resp.json();
}
const errorText = await resp.text();
console.error("Error: ", errorText);
let errorMessage = "An error occurred.";
try {
const errorObj = JSON.parse(errorText);
errorMessage = errorObj.message || errorMessage;
} catch {
errorMessage = errorText || errorMessage;
}
throw new Error(errorMessage);
});
};
export const apiClient = {
sendMessage: (
agentId: string,
message: string,
selectedFile?: File | null
) => {
const formData = new FormData();
formData.append("text", message);
formData.append("user", "user");
if (selectedFile) {
formData.append("file", selectedFile);
}
return fetcher({
url: `/${agentId}/message`,
method: "POST",
body: formData,
});
},
getAgents: () => fetcher({ url: "/agents" }),
getAgent: (agentId: string): Promise<{ id: UUID; character: Character }> =>
fetcher({ url: `/agents/${agentId}` }),
tts: (agentId: string, text: string) =>
fetcher({
url: `/${agentId}/tts`,
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: `/${agentId}/whisper`,
method: "POST",
body: formData,
});
},
applyArchetype: (agentId: string, archetype: Character) =>
fetcher({
url: `/agents/${agentId}/set`,
method: "POST",
body: archetype,
}),
};