-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathclient.ts
442 lines (362 loc) · 17.3 KB
/
client.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
import Parser from './parser';
import { PrivateProfile } from './profile/privateProfile';
import { PublicProfile } from './profile/publicProfile';
import Requester from './requester';
import { CAIWebsocket, CAIWebsocketConnectionType, ICAIWebsocketCommand, ICAIWebsocketMessage } from './websocket';
import DMConversation from './chat/dmConversation';
import { Character } from './character/character';
import { v4 as uuidv4 } from 'uuid';
import { GroupChats } from './groupchat/groupChats';
import { RecentCharacter } from './character/recentCharacter';
import { CAICall, ICharacterCallOptions } from './character/call';
import { CAIVoice } from './voice';
import { GroupChatConversation } from './groupchat/groupChatConversation';
import { SearchCharacter } from './character/searchCharacter';
import { Specable } from './utils/specable';
import { Persona } from './profile/persona';
export enum CheckAndThrow {
RequiresAuthentication = 0,
RequiresNoAuthentication,
RequiresToBeInCall,
RequiresToNotBeInCall
}
export class CharacterAI {
private token: string = "";
public get authenticated() { return this.token != ""; }
public myProfile: PrivateProfile;
public requester: Requester;
public groupChats: GroupChats;
private dmChatWebsocket: CAIWebsocket | null = null;
async sendDMWebsocketAsync(options: ICAIWebsocketMessage) {
return await this.dmChatWebsocket?.sendAsync(options);
}
async sendDMWebsocketCommandAsync(options: ICAIWebsocketCommand) {
const requestId = uuidv4();
return await this.sendDMWebsocketAsync({
parseJSON: true,
expectedReturnCommand: options.expectedReturnCommand,
messageType: CAIWebsocketConnectionType.DM,
waitForAIResponse: options.waitForAIResponse ?? true,
expectedRequestId: requestId,
streaming: options.streaming,
data: Parser.stringify({
command: options.command,
origin_id: options.originId,
payload: options.payload,
request_id: requestId
})
});
}
private groupChatWebsocket: CAIWebsocket | null = null;
async sendGroupChatWebsocketAsync(options: ICAIWebsocketMessage) { this.groupChatWebsocket?.sendAsync(options); }
async sendGroupChatWebsocketCommandAsync(options: ICAIWebsocketCommand) {
const requestId = uuidv4();
return await this.sendDMWebsocketAsync({
parseJSON: true,
expectedReturnCommand: options.expectedReturnCommand,
messageType: CAIWebsocketConnectionType.DM,
waitForAIResponse: true,
expectedRequestId: requestId,
streaming: options.streaming,
data: Parser.stringify({
command: options.command,
origin_id: options.originId,
payload: options.payload,
request_id: requestId
})
});
}
private async openWebsockets() {
try {
const request = await this.requester.request("https://character.ai/", {
method: "GET",
includeAuthorization: false
});
const { headers } = request;
const edgeRollout = headers.get("set-cookie")?.match(/edge_rollout=(\d+)/)?.at(1);
if (!edgeRollout) throw Error("Could not get edge rollout");
this.groupChatWebsocket = await new CAIWebsocket({
url: "wss://neo.character.ai/connection/websocket",
authorization: this.token,
edgeRollout,
userId: this.myProfile.userId
}).open(true);
this.dmChatWebsocket = await new CAIWebsocket({
url: "wss://neo.character.ai/ws/",
authorization: this.token,
edgeRollout,
userId: this.myProfile.userId
}).open(false);
} catch (error) {
throw Error("Failed opening websocket. Error:" + error);
}
}
private closeWebsockets() {
this.dmChatWebsocket?.close();
this.groupChatWebsocket?.close();
}
public currentCall?: CAICall = undefined;
async connectToCall(call: CAICall, options: ICharacterCallOptions): Promise<CAICall> {
this.checkAndThrow(CheckAndThrow.RequiresToNotBeInCall);
this.currentCall = call;
await call.connectToSession(options, this.token, this.myProfile.username);
return call;
}
async disconnectFromCall() {
this.checkAndThrow(CheckAndThrow.RequiresToBeInCall);
return await this.currentCall?.hangUp();
}
// profile fetching
async fetchProfileByUsername(username: string) {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const profile = new PublicProfile(this, { username });
await profile.refreshProfile();
return profile;
}
// character fetching
async searchCharacter(query: string): Promise<SearchCharacter[]> {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
if (query.trim() == "") throw new Error("The query must not be empty");
const encodedQuery = encodeURIComponent(query);
const request = await this.requester.request(`https://beta.character.ai/chat/characters/search/?query=${encodedQuery}`, {
method: 'GET',
includeAuthorization: true,
contentType: 'application/json'
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(response);
let characters: SearchCharacter[] = [];
const { characters: rawCharacters } = response;
for (let i = 0; i < rawCharacters.length; i++)
characters.push(new SearchCharacter(this, rawCharacters[i]));
return characters;
}
async fetchCharacter(characterId: string) {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const request = await this.requester.request("https://plus.character.ai/chat/character/info/", {
method: 'POST',
body: Parser.stringify({ external_id: characterId }),
includeAuthorization: true,
contentType: 'application/json'
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error("Failed to fetch character");
return new Character(this, response.character);
}
// voice
private async internalFetchCharacterVoices(endpoint: string, query?: string) {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const encodedQuery = encodeURIComponent(query ?? "");
const request = await this.requester.request(`https://neo.character.ai/multimodal/api/v1/voices/${endpoint}${encodedQuery}`, {
method: 'GET',
includeAuthorization: true
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(String(response));
const { voices: responseVoices } = response;
let voices: CAIVoice[] = [];
for (let i = 0; i < responseVoices.length; i++)
voices.push(new CAIVoice(this, responseVoices[i]));
return voices;
}
// v1/voices/search?characterName=
async searchCharacterVoices(query: string) { return await this.internalFetchCharacterVoices("search?characterName=", query); }
// v1/voices/system
async fetchSystemVoices() { return await this.internalFetchCharacterVoices("system"); }
// v1/voices/user
async fetchMyVoices() { return await this.internalFetchCharacterVoices("user"); }
// v1/voices/search?creatorInfo.username=
async fetchVoicesFromUser(username: string) { return await this.internalFetchCharacterVoices("search?creatorInfo.username=", username); }
// v1/voices/voiceId
async fetchVoice(voiceId: string): Promise<CAIVoice> {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const request = await this.requester.request(`https://neo.character.ai/multimodal/api/v1/voices/${voiceId}`, {
method: 'GET',
includeAuthorization: true
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(String(response));
return new CAIVoice(this, response.voice);
}
// https://neo.character.ai/recommendation/v1/
private async automateCharactersRecommendation<T extends Character>(
endpoint: string,
CharacterClass: new (...args: any[]) => T,
key: string = "characters",
baseEndpoint: string = "https://neo.character.ai/recommendation/v1/"
): Promise<T[]> {
const request = await this.requester.request(`${baseEndpoint}${endpoint}`, {
method: 'GET',
includeAuthorization: true,
contentType: 'application/json'
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(response);
const characters = response[key];
let targetCharacters: T[] = [];
for (let id = 0; id < characters.length; id++)
targetCharacters.push(new CharacterClass(this, characters[id]))
return targetCharacters;
}
// suggestions/discover
// /featured
async getFeaturedCharacters() { return await this.automateCharactersRecommendation("featured", Character); }
// /user
async getRecommendedCharactersForYou() { return await this.automateCharactersRecommendation("user", Character); }
// https://neo.character.ai/chats/recent/
async getRecentCharacters() { return await this.automateCharactersRecommendation("https://neo.character.ai/chats/recent/", RecentCharacter, "chats", ""); }
// /category
async getCharacterCategories(): Promise<string[]> {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const request = await this.requester.request("https://neo.character.ai/recommendation/v1/category", {
method: 'GET',
includeAuthorization: true
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(String(response));
return response.categories;
}
async getSimilarCharactersTo(characterId: string) { return await this.automateCharactersRecommendation(`character/${characterId}`, Character); }
// https://plus.character.ai/chat/user/characters/upvoted/
async getLikedCharacters() { return await this.automateCharactersRecommendation("", Character, "characters", "https://plus.character.ai/chat/user/characters/upvoted/"); }
// conversations
// raw is the raw output else the convo instance
async fetchRawConversation(chatId: string) {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const request = await this.requester.request(`https://neo.character.ai/chat/${chatId}/`, {
method: 'GET',
includeAuthorization: true
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(response.comment ?? String(response));
return response.chat;
}
async fetchDMConversation(chatId: string): Promise<DMConversation> {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const conversation = new DMConversation(this, await this.fetchRawConversation(chatId));
await conversation.refreshMessages();
return conversation;
}
async fetchGroupChatConversation(): Promise<any> {
// todo, placeholder rn
return new GroupChatConversation(this, {});
}
async fetchLatestDMConversationWith(characterId: string) {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const request = await this.requester.request(`https://neo.character.ai/chats/recent/${characterId}`, {
method: 'GET',
includeAuthorization: true
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(response);
const chatObject = response.chats[0];
const conversation = new DMConversation(this, chatObject);
await conversation.refreshMessages();
return conversation;
}
private async automateOverrideFetching<T extends Specable>(
baseDictionary: Record<string, string>,
fetchingMethod: Function
) {
let record: Record<string, T> = {};
for (const [characterId, valueId] of Object.entries(baseDictionary)) {
const object = await fetchingMethod(valueId);
if (!object) continue;
(record as any)[characterId as string] = object;
}
return record;
}
async fetchSettings() {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const request = await this.requester.request("https://plus.character.ai/chat/user/settings/", {
method: 'GET',
includeAuthorization: true
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(response);
const { voiceOverrides: voiceOverridesIds, default_persona_id: defaultPersonaId, personaOverrides: personaOverridesIds } = response;
const fetchVoiceOverrides = async () => this.automateOverrideFetching<CAIVoice>(voiceOverridesIds, this.fetchVoice);
const fetchPersonaOverrides = async () => this.automateOverrideFetching<Persona>(personaOverridesIds, this.myProfile.fetchPersona);
return {
defaultPersonaId,
personaOverridesIds,
voiceOverridesIds,
fetchDefaultPersona: async () => await this.myProfile.fetchPersona(defaultPersonaId),
fetchVoiceOverrides,
fetchPersonaOverrides
}
}
// persona (linked to settings)
async setPersonaOverrideFor(characterId: string, personaId: string) {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const settings = await this.fetchSettings();
let personasOverrides = settings.personaOverridesIds;
personasOverrides[characterId] = personaId;
const request = await this.requester.request("https://plus.character.ai/chat/user/settings/", {
method: 'POST',
includeAuthorization: true,
contentType: 'application/json',
body: Parser.stringify({ personasOverrides })
});
const response = await Parser.parseJSON(request);
if (!request.ok) throw new Error(response);
}
async getPersonaOverrideFor(characterId: string): Promise<Persona | undefined> {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
const settings = await this.fetchSettings();
const personaOverrides = await settings.fetchPersonaOverrides();
return personaOverrides[characterId];
}
// authentication
async authenticate(sessionToken: string) {
this.checkAndThrow(CheckAndThrow.RequiresNoAuthentication);
if (sessionToken.startsWith("Token "))
sessionToken = sessionToken.substring("Token ".length, sessionToken.length);
if (sessionToken.length != 40) console.warn(
`===============================================================================
WARNING: CharacterAI has changed its authentication methods again.
For easier development purposes, usage of session tokens will be used.
See: https://github.com/realcoloride/node_characterai/issues/146
===============================================================================`);
this.requester.updateToken(sessionToken);
const request = await this.requester.request("https://plus.character.ai/chat/user/settings/", {
method: "GET",
includeAuthorization: true
});
if (!request.ok) throw Error("Invaild authentication token.");
this.token = sessionToken;
// reload info
await this.myProfile.refreshProfile();
// connect to endpoints
await this.openWebsockets();
}
unauthenticate() {
this.checkAndThrow(CheckAndThrow.RequiresAuthentication);
this.disconnectFromCall();
this.closeWebsockets();
this.token = "";
}
throwBecauseNotAvailableYet(additionalDetails: string) {
throw Error("This feature is not available yet due to some restrictions from CharacterAI. Sorry!\nDetails: " + additionalDetails);
}
// allows for quick auth errors
checkAndThrow(
argument: CheckAndThrow,
requiresAuthenticatedMessage: string = "You must be authenticated to do this."
) {
if ((argument == CheckAndThrow.RequiresAuthentication ||
argument >= CheckAndThrow.RequiresToBeInCall) && !this.authenticated)
throw Error(requiresAuthenticatedMessage);
if (argument == CheckAndThrow.RequiresNoAuthentication && this.authenticated)
throw Error("Already authenticated");
if (argument == CheckAndThrow.RequiresToNotBeInCall && this.currentCall)
throw Error("You are already in a call. CharacterAI currently limits to 1 call per account.");
if (argument == CheckAndThrow.RequiresToBeInCall && !this.currentCall)
throw Error("You need to be in a call.");
}
constructor() {
this.myProfile = new PrivateProfile(this);
this.requester = new Requester();
this.groupChats = new GroupChats(this);
}
}