-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.ts
3346 lines (2983 loc) · 124 KB
/
index.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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import SuperMap from "@thunder04/supermap"
/*
* https://github.com/db0/AI-Horde/blob/main/CHANGELOG.md
*/
export const ErrorMessages = Object.freeze({
"MissingPrompt": "The generation prompt was not given",
"CorruptPrompt": "The prompts was rejected as unethical",
"KudosValidationError": "Something went wrong when transferring kudos. This is a base rc, so you should never typically see it.",
"NoValidActions": "Something went wrong when modifying an entity on the horde. This is a base rc, so you should never typically see it.",
"InvalidSize": "Requested image size is not a multiple of 64",
"InvalidPromptSize": "Prompt is too large",
"TooManySteps": "Too many steps requested for image generation",
"Profanity": "Profanity Detected. This is a base rc, so you should never typically see i",
"ProfaneWorkerName": "Profanity detected in worker name",
"ProfaneBridgeAgent": "Profanity detected in bridge agent",
"ProfaneWorkerInfo": "Profanity detected in worker info",
"ProfaneUserName": "Profanity detected in username",
"ProfaneUserContact": "Profanity detected in user contact details",
"ProfaneAdminComment": "Profanity detected in admin comment",
"ProfaneTeamName": "Profanity detected in team name",
"ProfaneTeamInfo": "Profanity detected in team info",
"TooLong": "Provided string was too long. This is a base rc, so you should never typically see it.",
"TooLongWorkerName": "The provided worker name is too long",
"TooLongUserName": "The provided username is too long",
"NameAlreadyExists": "The provided name already exists. This is a base rc, so you should never typically see it.",
"WorkerNameAlreadyExists": "The provided worker name already exists",
"TeamNameAlreadyExists": "The provided team name already exists",
"PolymorphicNameConflict": "The provided worker name already exists for a different worker type (e.g. Dreamer VS Scribe)",
"ImageValidationFailed": "Source image validation failed unexpectedly",
"SourceImageResolutionExceeded": "Source image resolution larger than the max allowed by the AI Horde",
"SourceImageSizeExceeded": "Source image file size larger than the max allowed by the AI Horde",
"SourceImageUrlInvalid": "Source image url does not contain an image",
"SourceImageUnreadable": "Source image could not be parsed",
"InpaintingMissingMask": "Missing mask or alpha channel for inpainting",
"SourceMaskUnnecessary": "Source mask sent without a source image",
"UnsupportedSampler": "Selected sampler unsupported with selected model",
"UnsupportedModel": "The required model name is unsupported with this payload. This is a base rc, so you should never typically see it.",
"ControlNetUnsupported": "ControlNet is unsupported in combination with this model",
"ControlNetSourceMissing": "Missing source image for ControlNet workflow",
"ControlNetInvalidPayload": "sent CN source and requested CN source at the same time",
"SourceImageRequiredForModel": "Source image is required for using this model",
"UnexpectedModelName": "Model name sent is not a Stable Diffusion checkpoint",
"TooManyUpscalers": "Tried to use more than 1 upscaler at a time",
"ProcGenNotFound": "The used generation for aesthetic ratings doesn't exist",
"InvalidAestheticAttempt": "Aesthetics rating attempt failed",
"AestheticsNotCompleted": "Attempted to rate non-completed request",
"AestheticsNotPublic": "Attempted to rate non-shared request",
"AestheticsDuplicate": "Sent duplicate images in an aesthetics set",
"AestheticsMissing": "Aesthetic ratings missing",
"AestheticsSolo": "Aesthetic ratings best-of contain a single image",
"AestheticsConfused": "The best image is not the one with the highest aesthetic rating",
"AestheticsAlreadyExist": "Aesthetic rating already submitted",
"AestheticsServerRejected": "Aesthetic server rejected submission",
"AestheticsServerError": "Aesthetic server returned error (provided)",
"AestheticsServerDown": "Aesthetic server is down",
"AestheticsServerTimeout": "Aesthetic server timed out during submission",
"InvalidAPIKey": "Invalid AI Horde API key provided",
"WrongCredentials": "Provided user does not own this worker",
"NotAdmin": "Request needs AI Horded admin credentials",
"NotModerator": "Request needs AI Horded moderator credentials",
"NotOwner": "Request needs worker owner credentials",
"NotPrivileged": "This user is not hardcoded to perform this operation",
"AnonForbidden": "Anonymous is not allowed to perform this operation",
"AnonForbiddenWorker": "Anonymous tried to run a worker",
"AnonForbiddenUserMod": "Anonymous tried to modify their user account",
"NotTrusted": "Untrusted users are not allowed to perform this operation",
"UntrustedTeamCreation": "Untrusted user tried to create a team",
"UntrustedUnsafeIP": "Untrusted user tried to use a VPN for a worker",
"WorkerMaintenance": "Worker has been put into maintenance and cannot pop new jobs",
"WorkerFlaggedMaintenance": "Worker owner has been flagged and worker has been put into permanent maintenance",
"TooManySameIPs": "Same IP attempted to spawn too many workers",
"WorkerInviteOnly": "AI Horde is in worker invite-only mode and worker owner needs to request permission",
"UnsafeIP": "Worker attempted to connect from VPN",
"TimeoutIP": "Operation rejected because user IP in timeout",
"TooManyNewIPs": "Too many workers from new IPs currently",
"KudosUpfront": "This request requires upfront kudos to accept",
"SharedKeyEmpty": "Shared Key used in the request does not have any more kudos",
"InvalidJobID": "Job not found when trying to submit. This probably means its request was delected for inactivity",
"RequestNotFound": "Request not found. This probably means it was delected for inactivity",
"WorkerNotFound": "Worker ID not found",
"TeamNotFound": "Team ID not found",
"FilterNotFound": "Regex filter not found",
"UserNotFound": "User not found",
"DuplicateGen": "Job has already been submitted",
"AbortedGen": "Request aborted because too many jobs have failed",
"RequestExpired": "Request expired",
"TooManyPrompts": "User has requested too many generations concurrently",
"NoValidWorkers": "No workers online which can pick up this request",
"MaintenanceMode": "Request aborted because horde is in maintenance mode",
"TargetAccountFlagged": "Action rejected because target user has been flagged for violating Horde ToS",
"SourceAccountFlagged": "Action rejected because source user has been flagged for violating Horde ToS",
"FaultWhenKudosReceiving": "Unexpected error when receiving kudos",
"FaultWhenKudosSending": "Unexpected error when sending kudos",
"TooFastKudosTransfers": "User tried to send kudos too fast after receiving them from the same user",
"KudosTransferToAnon": "User tried to transfer kudos to Anon",
"KudosTransferToSelf": "User tried to transfer kudos to themselves",
"KudosTransferNotEnough": "User tried to transfer more kudos than they have",
"NegativeKudosTransfer": "User tried to transfer negative kudos",
"KudosTransferFromAnon": "User tried to transfer kudos using the Anon API key",
"InvalidAwardUsername": "Tried to award kudos to non-existing user",
"KudosAwardToAnon": "Tried to award kudos to Anonymous user",
"NotAllowedAwards": "This user is not allowed to Award Kudos",
"NoWorkerModSelected": "No valid worker modification selected",
"NoUserModSelected": "No valid user modification selected",
"NoHordeModSelected": "No valid horde modification selected",
"NoTeamModSelected": "No valid team modification selected",
"NoFilterModSelected": "No valid regex filter modification selected",
"NoSharedKeyModSelected": "No valid shared key modification selected",
"BadRequest": "Generic HTTP 400 code. You should typically never see this",
"Forbidden": "Generic HTTP 401 code. You should typically never see this",
"Locked": "Generic HTTP code. You should typically never see this",
"Unknown": "Unknown rc code"
} as const)
export const ModelGenerationInputStableSamplers = Object.freeze({
"lcm": "lcm",
"k_lms": "k_lms",
"k_heun": "k_heun",
"k_euler_a": "k_euler_a",
"k_euler": "k_euler",
"k_dpm_2": "k_dpm_2",
"k_dpm_2_a": "k_dpm_2_a",
"DDIM": "DDIM",
"PLMS": "PLMS",
"k_dpm_fast": "k_dpm_fast",
"k_dpm_adaptive": "k_dpm_adaptive",
"k_dpmpp_2s_a": "k_dpmpp_2s_a",
"k_dpmpp_2m": "k_dpmpp_2m",
"dpmsolver": "dpmsolver",
"k_dpmpp_sde": "k_dpmpp_sde"
} as const)
export const SourceImageProcessingTypes = Object.freeze({
"img2img": "img2img",
"inpainting": "inpainting",
"outpainting": "outpainting",
"remix": "remix"
} as const)
export const ModelGenerationInputPostProcessingTypes = Object.freeze({
"GFPGAN": "GFPGAN",
"RealESRGAN_x4plus": "RealESRGAN_x4plus",
"RealESRGAN_x2plus": "RealESRGAN_x2plus",
"RealESRGAN_x4plus_anime_6B": "RealESRGAN_x4plus_anime_6B",
"NMKD_Siax": "NMKD_Siax",
"4x_AnimeSharp": "4x_AnimeSharp",
"strip_background": "strip_background",
"CodeFormers": "CodeFormers"
} as const)
export const ModelInterrogationFormTypes = Object.freeze({
"caption": "caption",
"interrogation": "interrogation",
"nsfw": "nsfw",
"GFPGAN": "GFPGAN",
"RealESRGAN_x4plus": "RealESRGAN_x4plus",
"RealESRGAN_x4plus_anime_6B": "RealESRGAN_x4plus_anime_6B",
"NMKD_Siax": "NMKD_Siax",
"4x_AnimeSharp": "4x_AnimeSharp",
"CodeFormers": "CodeFormers",
"strip_background": "strip_background"
} as const)
export const HordeAsyncRequestStates = Object.freeze({
"waiting": "waiting",
"processing": "processing",
"done": "done",
"faulted": "faulted",
"partial": "partial",
"cancelled": "cancelled"
} as const)
export const ModelGenerationInputControlTypes = Object.freeze({
"canny": "canny",
"hed": "hed",
"depth": "depth",
"normal": "normal",
"openpose": "openpose",
"seg": "seg",
"scribble": "scribble",
"fakescribbles": "fakescribbles",
"hough": "hough"
} as const)
export const ModelPayloadTextInversionsStable = Object.freeze({
prompt: "prompt",
negrpompt: "negprompt"
} as const)
export const ModelGenerationInputWorkflows = Object.freeze({
"qr_code": "qr_code",
} as const)
export const RequestSingleWarningCodes = Object.freeze({
"NoAvailableWorker": "NoAvailableWorker",
"ClipSkipMismatch": "ClipSkipMismatch",
"StepsTooFew": "StepsTooFew",
"StepsTooMany": "StepsTooMany",
"CfgScaleMismatch": "CfgScaleMismatch",
"CfgScaleTooSmall": "CfgScaleTooSmall",
"CfgScaleTooLarge": "CfgScaleTooLarge",
"SamplerMismatch": "SamplerMismatch",
"SchedulerMismatch": "SchedulerMismatch",
} as const)
export const GenerationMetadataStableTypes = Object.freeze({
"lora": "lora",
"ti": "ti",
"censorship": "censorship",
"source_image": "source_image",
"source_mask": "source_mask",
"extra_source_images": "extra_source_images",
"batch_index": "batch_index",
"information": "information"
} as const)
export const GenerationMetadataStableValues = Object.freeze({
"download_failed": "download_failed",
"parse_failed": "parse_failed",
"baseline_mismatch": "baseline_mismatch",
"csam": "csam",
"nsfw": "nsfw",
"see_ref": "see_ref"
} as const)
export class APIError extends Error {
rawError: RequestError;
status: number;
method: string;
url: string;
requestBody: any;
errors: Record<string, string>
error_code: string
constructor(rawError: RequestError | ValidationError, core_res: Response, method: string = "GET", requestBody?: any) {
super()
this.rawError = rawError
this.status = core_res.status ?? 0
this.method = method
this.url = core_res.url ?? ""
this.requestBody = requestBody
this.errors = "errors" in rawError ? rawError.errors : {}
this.message = ErrorMessages[rawError.rc as "Unknown"] ?? rawError.message
this.error_code = rawError.rc
}
get name() {
return this.rawError.rc || this.rawError.message
}
}
export class AIHorde {
#default_token?: string
#cache_config: AIHordeCacheConfiguration
#cache: AIHordeCache
#api_route: string
VERSION: string
#client_agent: string
ratings: AIHordeRatings
constructor(options?: AIHordeInitOptions) {
this.#default_token = options?.default_token
this.#api_route = options?.api_route ?? "https://aihorde.net/api/v2"
this.#cache_config = {
users: options?.cache?.users ?? 0,
generations_check: options?.cache?.generations_check ?? 0,
generations_status: options?.cache?.generations_status ?? 0,
interrogations_status: options?.cache?.interrogations_status ?? 0,
models: options?.cache?.models ?? 0,
modes: options?.cache?.modes ?? 0,
news: options?.cache?.news ?? 0,
performance: options?.cache?.performance ?? 0,
workers: options?.cache?.workers ?? 0,
teams: options?.cache?.teams ?? 0,
sharedkeys: options?.cache?.sharedkeys ?? 0
}
if (Object.values(this.#cache_config).some(v => !Number.isSafeInteger(v) || v < 0)) throw new TypeError("Every cache duration must be a positive safe integer")
this.#cache = {
users: this.#cache_config.users ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.users }) : undefined,
generations_check: this.#cache_config.generations_check ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.generations_check }) : undefined,
generations_status: this.#cache_config.generations_status ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.generations_status }) : undefined,
interrogations_status: this.#cache_config.interrogations_status ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.interrogations_status }) : undefined,
models: this.#cache_config.models ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.models }) : undefined,
modes: this.#cache_config.modes ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.modes }) : undefined,
news: this.#cache_config.news ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.news }) : undefined,
performance: this.#cache_config.performance ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.performance }) : undefined,
workers: this.#cache_config.workers ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.workers }) : undefined,
teams: this.#cache_config.teams ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.teams }) : undefined,
sharedkeys: this.#cache_config.sharedkeys ? new SuperMap({ intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.sharedkeys }) : undefined,
}
this.VERSION = "Unknown"
this.#client_agent = options?.client_agent ?? "@zeldafan0225/ai_horde:Version_Unknown:github.com/ZeldaFan0225/ai_horde/issues";
(async () => {
let fs = await import("fs")
let path = await import("path")
try{
let pckg = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json")).toString())
this.VERSION = pckg.version
this.#client_agent = options?.client_agent ?? `${pckg.name}:${pckg.version}:${pckg.bugs?.slice(8)}`
}catch(_){
// This catch unexpect errors, like the JSON Parse failing
}
})().catch(_ => {})
this.ratings = new AIHordeRatings({
api_route: options?.ratings_api_route ?? "https://ratings.aihorde.net/api/v1",
default_token: options?.default_token,
client_agent: this.#client_agent
})
}
/* GENERAL */
#getToken(token?: string): string {
return token || this.#default_token || "0000000000"
}
clearCache() {
Object.values(this.#cache).forEach(m => m.clear())
}
get cache() {
return this.#cache
}
parseAgent(agent: string) {
const [name, version, link] = agent.split(":")
return {
name,
version,
link
}
}
generateFieldsString(fields?: string[]) {
return fields?.join(',')
}
async #request(route: string, method: string, options?: { token?: string, fields?: string[], fields_string?: string, body?: any }): Promise<{ result: Response, fields_string: string }> {
const fields_string = options?.fields?.join(',') || options?.fields_string || ''
const t = this.#getToken(options?.token)
const headers: HeadersInit = {
"Client-Agent": this.#client_agent,
"Content-Type": "application/json"
}
if (options?.token) headers["apikey"] = t;
if (fields_string) headers["X-Fields"] = fields_string
const res = await fetch(`${this.#api_route}${route}`, {
method,
headers,
body: options?.body ? JSON.stringify(options.body) : undefined
})
if (!res.status.toString().startsWith("2")) throw new APIError(await res.json(), res, method, options?.body)
return { result: res, fields_string }
}
/* GET REQUESTS */
/**
* Lookup user details based on their API key.
* This can be used to verify a user exists
* @param options.token - The token of the user; If none given the default from the contructor is used
* @param options.fields - Array of fields that will be included in the returned data
* @returns UserDetails - The user data of the requested user
*/
async findUser<
T extends keyof UserDetails
>(options?: { token?: string, fields?: T[] }): Promise<Pick<UserDetails, T>> {
const { result, fields_string } = await this.#request("/find_user", "GET", options)
const data = await result.json() as Pick<UserDetails, T>
if (this.#cache_config.users) {
const data_with_id = data as Pick<UserDetails, 'id'>
if ('id' in data_with_id) this.#cache.users?.set(data_with_id.id + fields_string!, data)
}
return data
}
/**
* Details and statistics about a specific user
* @param id - The user ids to get
* @param options.token - The token of the requesting user; Has to be Moderator, Admin or Reuqested users token
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns UserDetails - The user data of the requested user
*/
async getUserDetails<
T extends keyof UserDetails
>(id: number, options?: { token?: string, force?: boolean, fields?: T[] }): Promise<Pick<UserDetails, T>> {
const fields_string = this.generateFieldsString(options?.fields)
const token = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.users?.get(id.toString() + fields_string)
if (temp) return temp
const { result } = await this.#request(`/users/${id}`, "GET", { fields_string, token })
const data = await result.json() as Pick<UserDetails, T>
if (this.#cache_config.users) {
const data_with_id = data as Pick<UserDetails, 'id'>
if ('id' in data_with_id) this.#cache.users?.set(data_with_id.id + fields_string!, data)
}
return data
}
/**
* Details of a worker Team
* @param id - The teams id to get
* @param options.token - The token of the requesting user
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns TeamDetailsStable - The team data
*/
async getTeam<
T extends keyof TeamDetailsStable
>(id: string, options?: { token?: string, force?: boolean, fields?: T[] }): Promise<Pick<TeamDetailsStable, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const token = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.teams?.get(id + fields_string)
if (temp) return temp as Pick<TeamDetailsStable, T>
const { result } = await this.#request(`/teams/${id}`, "GET", { token, fields_string })
const data = await result.json() as Pick<TeamDetailsStable, T>
if (this.#cache_config.teams) {
const data_with_id = data as Pick<TeamDetailsStable, 'id'>
if ('id' in data_with_id) this.#cache.teams?.set(data_with_id.id + fields_string, data)
}
return data
}
/**
* Details of a registered worker.
* This can be used to verify a user exists
* @param id - The id of the worker
* @param options.token - Moderator or API key of workers owner (gives more information if requesting user is owner or moderator)
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns worker details for the requested worker
*/
async getWorkerDetails<
T extends keyof WorkerDetailsStable
>(id: string, options?: { token?: string, force?: boolean, fields?: T[] }): Promise<Pick<WorkerDetailsStable, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const token = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.workers?.get(id + fields_string)
if (temp) return temp as Pick<WorkerDetailsStable, T>
const { result } = await this.#request(`/workers/${id}`, "GET", { token, fields_string })
const data = await result.json() as Pick<WorkerDetailsStable, T>
if (this.#cache_config.workers) {
const data_with_id = data as Pick<WorkerDetailsStable, 'id'>
if ('id' in data_with_id) this.#cache.workers?.set(data_with_id.id + fields_string, data)
}
return data
}
/**
* Retrieve the status of an Asynchronous generation request without images
* Use this method to check the status of a currently running asynchronous request without consuming bandwidth.
* @param id - The id of the generation
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns RequestStatusCheck - The Check data of the Generation
*/
async getImageGenerationCheck<
T extends keyof RequestStatusCheck
>(id: string, options?: { force?: boolean, fields?: T[] }): Promise<Pick<RequestStatusCheck, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.generations_check?.get(id + fields_string)
if (temp) return temp as Pick<RequestStatusCheck, T>
const { result } = await this.#request(`/generate/check/${id}`, "GET", { fields_string })
const data = await result.json() as Pick<RequestStatusCheck, T>
if (this.#cache_config.generations_check) this.#cache.generations_check?.set(id + fields_string, data)
return data
}
/**
* Retrieve the full status of an Asynchronous generation request
* This method will include all already generated images in base64 encoded .webp files.
* As such, you are requested to not retrieve this data often. Instead use the getGenerationCheck method first
* This method is limited to 1 request per minute
* @param id - The id of the generation
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns RequestStatusStable - The Status of the Generation
*/
async getImageGenerationStatus<
T extends keyof RequestStatusStable
>(id: string, options?: { force?: boolean, fields?: T[] }): Promise<Pick<RequestStatusStable, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.generations_status?.get(id + fields_string)
if (temp) return temp as Pick<RequestStatusStable, T>
const { result } = await this.#request(`/generate/status/${id}`, "GET", { fields_string })
const data = await result.json() as Pick<RequestStatusStable, T>
if (this.#cache_config.generations_status) this.#cache.generations_status?.set(id + fields_string, data)
return data
}
/**
* This request will include all already generated texts.
* @param id - The id of the generation
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns RequestStatusStable - The Status of the Generation
*/
async getTextGenerationStatus<
T extends keyof RequestStatusKobold
>(id: string, options?: { force?: boolean, fields?: T[] }): Promise<Pick<RequestStatusKobold, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.generations_status?.get(id + fields_string)
if (temp) return temp as Pick<RequestStatusKobold, T>
const { result } = await this.#request(`/generate/text/status/${id}`, "GET", { fields_string })
const data = await result.json() as Pick<RequestStatusKobold, T>
if (this.#cache_config.generations_status) this.#cache.generations_status?.set(id + fields_string, data)
return data
}
/**
* This request will include all already generated images.
* As such, you are requested to not retrieve this endpoint often. Instead use the /check/ endpoint first
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns InterrogationStatus - The Status data of the Interrogation
*/
async getInterrogationStatus<
T extends keyof InterrogationStatus
>(id: string, options?: { force?: boolean, fields?: T[] }): Promise<Pick<InterrogationStatus, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.interrogations_status?.get(id + fields_string)
if (temp) return temp as Pick<InterrogationStatus, T>
const { result } = await this.#request(`/interrogate/status/${id}`, "GET", { fields_string })
const data = await result.json() as Pick<InterrogationStatus, T>
if (this.#cache_config.interrogations_status) this.#cache.interrogations_status?.set(id + fields_string, data)
return data
}
/**
* If this loads, this node is available
* @returns true - If request was successful, if not throws error
*/
async getHeartbeat(): Promise<true> {
await this.#request(`/status/heartbeat`, "GET")
return true
}
/**
* Returns a list of models active currently in this horde
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns ActiveModel[] - Array of Active Models
*/
async getModels<
T extends keyof ActiveModel
>(options?: { force?: boolean, fields?: T[] }): Promise<Pick<ActiveModel, T>[]> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.models?.get("CACHE-MODELS" + fields_string)
if (temp) return temp as Pick<ActiveModel, T>[]
const { result } = await this.#request(`/status/models`, "GET", { fields_string })
const data = await result.json() as Pick<ActiveModel, T>[]
if (this.#cache_config.models) this.#cache.models?.set("CACHE-MODELS" + fields_string, data)
return data
}
/**
* Returns the statistics of a specific model in this horde
* @param model_name - The name of the model to fetch
* @param options.fields - Array of fields that will be included in the returned data
* @returns ActiveModel - The active model
*/
async getModel<
T extends keyof ActiveModel
>(model_name: string, options?: { fields?: T[] }): Promise<Pick<ActiveModel, T>[]> {
const { result } = await this.#request(`/status/models/${model_name}`, "GET", { fields: options?.fields })
const data = await result.json() as Pick<ActiveModel, T>[]
return data
}
/**
* Horde Maintenance Mode Status
* Use this method to quicky determine if this horde is in maintenance, invite_only or raid mode
* @param options.token - Requires Admin or Owner API key
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns HordeModes - The current modes of the horde
*/
async getModes<
T extends keyof HordeModes
>(options?: { token?: string, force?: boolean, fields?: T[] }): Promise<Pick<HordeModes, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const token = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.modes?.get("CACHE-MODES" + fields_string)
if (temp) return temp as Pick<HordeModes, T>
const { result } = await this.#request(`/status/modes`, "GET", { token, fields_string })
const data = await result.json() as Pick<HordeModes, T>
if (this.#cache_config.modes) this.#cache.modes?.set("CACHE-MODES" + fields_string, data)
return data
}
/**
* Read the latest happenings on the horde
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns Newspiece[] - Array of all news articles
*/
async getNews<
T extends keyof Newspiece
>(options?: { force?: boolean, fields?: T[] }): Promise<Pick<Newspiece, T>[]> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.news?.get("CACHE-NEWS" + fields_string)
if (temp) return temp as Pick<Newspiece, T>[]
const { result } = await this.#request(`/status/news`, "GET", { fields_string })
const data = await result.json() as Pick<Newspiece, T>[]
if (this.#cache_config.news) this.#cache.news?.set("CACHE-NEWS" + fields_string, data)
return data
}
/**
* Details about the current performance of this Horde
* @param options.force - Set to true to skip cache
* @param options.fields - Array of fields that will be included in the returned data
* @returns HordePerformanceStable - The hordes current performance
*/
async getPerformance<
T extends keyof HordePerformanceStable
>(options?: { force?: boolean, fields?: T[] }): Promise<Pick<HordePerformanceStable, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const temp = !options?.force && this.#cache.performance?.get("CACHE-PERFORMANCE" + fields_string)
if (temp) return temp as Pick<HordePerformanceStable, T>
const { result } = await this.#request(`/status/performance`, "GET", { fields_string })
const data = await result.json() as Pick<HordePerformanceStable, T>
if (this.#cache_config.performance) this.#cache.performance?.set("CACHE-PERFORMANCE" + fields_string, data)
return data
}
/**
* A List with the details and statistic of all registered users
* @param options.fields - Array of fields that will be included in the returned data
* @returns UserDetails[] - An array of all users data
*/
async getUsers<
T extends keyof UserDetails
>(options?: { force?: boolean, fields?: T[] }): Promise<Pick<UserDetails, T>[]> {
const { result, fields_string } = await this.#request(`/users`, "GET", { fields: options?.fields })
const data = await result.json() as Pick<UserDetails, T>[]
if (this.#cache_config.users) data.forEach(d => {
const data_with_id = d as Pick<UserDetails, 'id'>
if ('id' in data_with_id) this.#cache.users?.set(data_with_id.id! + fields_string, d)
})
return data
}
/**
* A List with the details of all registered and active workers
* @param options.fields - Array of fields that will be included in the returned data
* @returns An array of all workers data
*/
async getWorkers<
T extends keyof WorkerDetailsStable
>(options?: { fields?: T[] }): Promise<Pick<WorkerDetailsStable, T>[]> {
const { result, fields_string } = await this.#request(`/workers`, "GET", { fields: options?.fields })
const data = await result.json() as Pick<WorkerDetailsStable, T>[]
if (this.#cache_config.workers) data.forEach(d => {
const data_with_id = data as Pick<WorkerDetailsStable, 'id'>
if ('id' in data_with_id) this.#cache.workers?.set(data_with_id.id + fields_string, d)
})
return data
}
/**
* Details how many images were generated per model for the past day, month and total
* @param options.fields - Array of fields that will be included in the returned data
* @returns ImageModelStats - The stats
*/
async getImageModelStats<
T extends keyof ImageModelStats
>(options?: { fields?: T[] }): Promise<Pick<ImageModelStats, T>> {
const { result } = await this.#request("/stats/img/models", "GET", { fields: options?.fields })
const data = await result.json() as Pick<ImageModelStats, T>
return data
}
/**
* Details how many images have been generated in the past minux,hour,day,month and total
* @param options.fields - Array of fields that will be included in the returned data
* @returns ImageTotalStats - The stats
*/
async getImageTotalStats<
T extends keyof ImageModelStats
>(options?: { fields?: T[] }): Promise<Pick<ImageTotalStats, T>> {
const { result } = await this.#request("/stats/img/totals", "GET", { fields: options?.fields })
const data = await result.json() as Pick<ImageTotalStats, T>
return data
}
/**
* Details how many texts were generated per model for the past day, month and total
* @param options.fields - Array of fields that will be included in the returned data
* @returns TextModelStats - The stats
*/
async getTextModelStats<
T extends keyof ImageModelStats
>(options?: { fields?: T[] }): Promise<Pick<TextModelStats, T>> {
const { result } = await this.#request("/stats/text/models", "GET", { fields: options?.fields })
const data = await result.json() as Pick<TextModelStats, T>
return data
}
/**
* Details how many images have been generated in the past minux,hour,day,month and total
* @param options.fields - Array of fields that will be included in the returned data
* @returns TextTotalStats - The stats
*/
async getTextTotalStats<
T extends keyof ImageModelStats
>(options?: { fields?: T[] }): Promise<Pick<TextTotalStats, T>> {
const { result } = await this.#request("/stats/text/totals", "GET", { fields: options?.fields })
const data = await result.json() as Pick<TextTotalStats, T>
return data
}
/**
* A List with the details of all teams
* @param options.fields - Array of fields that will be included in the returned data
* @returns TeamDetailsStable[] - Array of Team Details
*/
async getTeams<
T extends keyof TeamDetailsStable
>(options?: { fields?: T[] }): Promise<Pick<TeamDetailsStable, T>[]> {
const { result, fields_string } = await this.#request(`/teams`, "GET", { fields: options?.fields })
const data = await result.json() as Pick<TeamDetailsStable, T>[]
if (this.#cache_config.teams) data.forEach(d => {
const data_with_id = d as Pick<TeamDetailsStable, 'id'>
if ('id' in data_with_id) this.#cache.teams?.set(data_with_id.id + fields_string, d)
})
return data
}
/**
* A List of filters
* @param query.filter_type - The type of filter to show
* @param query.contains - Only return filter containing this word
* @param options.token - The sending users API key; User must be a moderator
* @param options.fields - Array of fields that will be included in the returned data
* @returns FilterDetails[] - Array of Filter Details
*/
async getFilters<
T extends keyof FilterDetails
>(query?: { filter_type?: string, contains?: string }, options?: { token?: string, fields?: T[] }): Promise<Pick<FilterDetails, T>[]> {
const token = this.#getToken(options?.token)
const params = new URLSearchParams()
if (query?.filter_type) params.set("filter_type", query?.filter_type)
if (query?.contains) params.set("contains", query?.contains)
const { result } = await this.#request(`/filters${params.toString() ? `?${params.toString()}` : ""}`, "GET", { token, fields: options?.fields })
const data = await result.json() as Pick<FilterDetails, T>[]
return data
}
/**
* Gets Details for a specific filter
* @param filter_id - The filter to show
* @param options.token - The sending users API key; User must be a moderator
* @param options.fields - Array of fields that will be included in the returned data
* @returns FilterDetails - Filter Details
*/
async getFilter<
T extends keyof FilterDetails
>(filter_id?: string, options?: { token?: string, fields?: T[] }): Promise<Pick<FilterDetails, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/filters/${filter_id}`, "GET", { token, fields: options?.fields })
const data = await result.json() as Pick<FilterDetails, T>
return data
}
/**
* Gets Details about an existing Shared Key for this user
* @param sharedkey_id - The shared key to show
* @param options.token - The sending users API key; User must be a moderator
* @param options.fields - Array of fields that will be included in the returned data
* @returns FilterDetails - Filter Details
*/
async getSharedKey<
T extends keyof SharedKeyDetails
>(sharedkey_id?: string, options?: { token?: string, fields?: T[] }): Promise<Pick<SharedKeyDetails, T>> {
const { result } = await this.#request(`/sharedkeys/${sharedkey_id}`, "GET", { fields: options?.fields })
const data = await result.json() as Pick<SharedKeyDetails, T>
return data
}
/* POST REQUESTS */
/**
* Transfer Kudos to a registered user
* @param check_data - The prompt to check
* @param options.token - The sending users API key; User must be a moderator
* @param options.fields - Array of fields that will be included in the returned data
* @returns FilterPromptSuspicion
*/
async postFilters<
T extends keyof FilterPromptSuspicion
>(check_data: FilterCheckPayload, options?: { token?: string, fields?: T[] }): Promise<Pick<FilterPromptSuspicion, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/filters`, "POST", { token, fields: options?.fields, body: check_data })
return await result.json() as Pick<FilterPromptSuspicion, T>
}
/**
* Initiate an Asynchronous request to generate images
* This method will immediately return with the UUID of the request for generation.
* This method will always be accepted, even if there are no workers available currently to fulfill this request.
* Perhaps some will appear in the next 10 minutes.
* Asynchronous requests live for 10 minutes before being considered stale and being deleted.
* @param generation_data - The data to generate the image
* @param options.token - The token of the requesting user
* @param options.fields - Array of fields that will be included in the returned data
* @returns RequestAsync - The id and message for the async generation request
*/
async postAsyncImageGenerate<
T extends keyof RequestAsync
>(generation_data: ImageGenerationInput, options?: { token?: string, fields?: T[] }): Promise<Pick<RequestAsync, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/async`, "POST", { token, fields: options?.fields, body: generation_data })
return await result.json() as Pick<RequestAsync, T>
}
/**
* Initiate an Asynchronous request to generate text
* This endpoint will immediately return with the UUID of the request for generation.
* This endpoint will always be accepted, even if there are no workers available currently to fulfill this request.
* Perhaps some will appear in the next 20 minutes.
* Asynchronous requests live for 20 minutes before being considered stale and being deleted.
* @param generation_data - The data to generate the text
* @param options.token - The token of the requesting user
* @param options.fields - Array of fields that will be included in the returned data
* @returns RequestAsync - The id and message for the async generation request
*/
async postAsyncTextGenerate<
T extends keyof RequestAsync
>(generation_data: GenerationInputKobold, options?: { token?: string, fields?: T[] }): Promise<Pick<RequestAsync, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/text/async`, "POST", { token, fields: options?.fields, body: generation_data })
return await result.json() as Pick<RequestAsync, T>
}
/**
* Submit aesthetic ratings for generated images to be used by LAION
* The request has to have been sent as shared: true.
* You can select the best image in the set, and/or provide a rating for each or some images in the set.
* If you select best-of image, you will gain 4 kudos. Each rating is 5 kudos. Best-of will be ignored when ratings conflict with it.
* You can never gain more kudos than you spent for this generation. Your reward at max will be your kudos consumption - 1.
* @param generation_id - The ID of the generation to rate
* @param rating - The data to rating data
* @param options.token - The token of the requesting user
* @param options.fields - Array of fields that will be included in the returned data
* @returns GenerationSubmitted - The kudos awarded for the rating
*/
async postRating<
T extends keyof GenerationSubmitted
>(generation_id: string, rating: AestheticsPayload, options?: { token?: string, fields?: T[] }): Promise<Pick<GenerationSubmitted, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/rate/${generation_id}`, "POST", { token, fields: options?.fields, body: rating })
return await result.json() as Pick<GenerationSubmitted, T>
}
/**
* Check if there are generation requests queued for fulfillment
* This endpoint is used by registered workers only
* @param pop_input
* @param options.token - The token of the registered user
* @param options.fields - Array of fields that will be included in the returned data
* @returns GenerationPayloadStable
*/
async postImageGenerationPop<
T extends keyof GenerationPayloadStable
>(pop_input: PopInputStable, options?: { token?: string, fields?: T[] }): Promise<Pick<GenerationPayloadStable, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/pop`, "POST", { token, fields: options?.fields, body: pop_input })
return await result.json() as Pick<GenerationPayloadStable, T>
}
/**
* Check if there are generation requests queued for fulfillment
* This endpoint is used by registered workers only
* @param pop_input
* @param options.token - The token of the registered user
* @param options.fields - Array of fields that will be included in the returned data
* @returns GenerationPayloadKobold
*/
async postTextGenerationPop<
T extends keyof GenerationPayloadKobold
>(pop_input: PopInputKobold, options?: { token?: string, fields?: T[] }): Promise<Pick<GenerationPayloadKobold, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/text/pop`, "POST", { token, fields: options?.fields, body: pop_input })
return await result.json() as Pick<GenerationPayloadKobold, T>
}
/**
* Submit a generated image
* This endpoint is used by registered workers only
* @param generation_submit
* @param options.token - The workers owner API key
* @param options.fields - Array of fields that will be included in the returned data
* @returns GenerationSubmitted
*/
async postImageGenerationSubmit<
T extends keyof GenerationSubmitted
>(generation_submit: { id: string, generation: string, seed: string }, options?: { token?: string, fields?: T[] }): Promise<Pick<GenerationSubmitted, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/submit`, "POST", { token, fields: options?.fields, body: generation_submit })
return await result.json() as Pick<GenerationSubmitted, T>
}
/**
* Submit generated text
* This endpoint is used by registered workers only
* @param generation_submit
* @param options.token - The workers owner API key
* @param options.fields - Array of fields that will be included in the returned data
* @returns GenerationSubmitted
*/
async postTextGenerationSubmit<
T extends keyof GenerationSubmitted
>(generation_submit: { id: string, generation: string, state: "ok" | "censored" | "faulted" }, options?: { token?: string, fields?: T[] }): Promise<Pick<GenerationSubmitted, T>> {
const token = this.#getToken(options?.token)
const { result } = await this.#request(`/generate/text/submit`, "POST", { token, fields: options?.fields, body: generation_submit })
return await result.json() as Pick<GenerationSubmitted, T>
}
/**
* Initiate an Asynchronous request to interrogate an image.
* This endpoint will immediately return with the UUID of the request for interrogation.