-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
546 lines (481 loc) · 15 KB
/
main.js
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
// for mistral:
const INSTRUCTION_PREFIX = "[INST] "
const RESPONSE_PREFIX = " [\\INST]\n"
/**
// for others:
const INSTRUCTION_PREFIX = "### Instruction:\n"
const RESPONSE_PREFIX = "### Response:\n"
*/
/**
* @returns {Promise<String>}
*/
async function requestText(details) {
if (details.cache_prompt == undefined) details.cache_prompt = true;
let response = await fetch("http://127.0.0.1:8080/completion", {
method: 'POST',
body: JSON.stringify(details)
})
let out = (await response.json()).content
console.trace("LLM returned: \n" + out);
return out
}
/**
* @typedef {Object} Ability
* @property {String} name
* @property {String} effect
*/
/**
* @typedef {Object} Enemy
* @property {String} name
* @property {String} description
* @property {[Ability]} abilities
*/
/**
* @typedef {Object} PlayerWeapon
* @property {String} name
* @property {String} description
* @property {[Ability]} abilities
*/
/** @type {[Enemy]} */
let enemyExamples = [
{
"name": "Goblin",
"description": "This short creature smiles at you with evil in its eyes.",
"abilities": [
{
"name": "swipe",
"effect": "small amount of damage"
},
]
},
{
"name": "Another Adventurer",
"description": "This guy appears to have some cool weapons. He refuses to hand them over.",
"abilities": [
{
"name": "swing",
"effect": "moderate amount of damage"
},
]
},
{
"name": "Superwizard of the Seven Seas",
"description": "A man with a large, flowing, grey beard. He sports a shirt with a large 'W' printed on it, and eyepatches on both eyes.",
"abilities": [
{
"name": "hook",
"effect": "reduces player attack"
},
{
"name": "summon storm",
"effect": "makes everything wet"
},
{
"name": "lazer",
"effect": "moderate amount of damage"
},
]
},
];
/**
* @param {Enemy} str
* @returns {String}
*/
function enemyToString(enemy) {
let out = "";
out += enemy.name + '\n';
out += enemy.description + '\n';
for (ability of enemy.abilities) {
out += "* " + ability.name + ": " + ability.effect + '\n';
}
return out;
}
/**
* @param {string} str
* @returns {?Enemy}
*/
function enemyFromString(str) {
/** @type {Enemy} */
let out = {}
let lines = str.split('\n');
if (lines.length < 3) return null;
out.name = lines[0].trim();
out.description = lines[1].trim();
out.abilities = [];
for (let i = 2; i < lines.length; i++) {
if (lines[i].trim().length == 0) break;
if (!lines[i].startsWith("* ")) {
console.warn("llm likely not following format: \n"+str);
continue;
}
let abilityLine = lines[i].substring(2).split(":");
if (abilityLine.length != 2) {
console.warn("llm likely not following format: \n"+str);
continue;
}
out.abilities.push({
"name": abilityLine[0].trim(),
"effect": abilityLine[1].trim()
});
}
if (out.abilities.length == 0) return null;
return out;
}
/**
* @returns {Promise<Enemy>}
*/
async function generateEnemy() {
let prompt = "";
prompt += INSTRUCTION_PREFIX;
prompt += "The following are several examples of enemies in a dungeon crawler:\n";
prompt += enemyExamples.map(enemyToString).join('\n');
prompt += "\nPlease generate another enemy similar to the above";
prompt += RESPONSE_PREFIX;
let enemyStr = "";
try {
enemyStr += await requestText({
prompt: prompt+enemyStr,
n_predict: 20,
grammar: "root ::= [0-9a-zA-Z ]+\"\\n\"",
temperature: 1.1,
});
console.log("Generating " + enemyStr);
enemyStr += await requestText({
prompt: prompt+enemyStr,
n_predict: 100,
grammar: "root ::= [0-9a-zA-Z ,.]+\"\\n\"",
temperature: 0.6,
});
enemyStr += await requestText({
prompt: prompt+enemyStr,
n_predict: 100,
grammar: "root ::= (\"* \"[0-9a-zA-Z ]+\": \"[0-9a-zA-Z ]+\"\\n\")+\"\\n\"",
});
return enemyFromString(enemyStr) || enemyExamples[0];
} catch {
return enemyExamples[0];
}
}
/** @type {[PlayerWeapon]} */
let playerWeaponExamples = [
{
"name": "Dagger",
"description": "Short blade that gets the job done.",
"abilities": [
{
"name": "Jab",
"effect": "does a small amount of damage",
},
{
"name": "Backstab",
"effect": "does a large amount of damage, misses if enemy is aware",
},
]
},
{
"name": "Flintlock",
"description": "Somewhat clumsy but powerful gunpowder weapon.",
"abilities": [
{
"name": "Shoot",
"effect": "does a lot of damage, must be loaded",
},
{
"name": "Reload",
"effect": "load the flintlock",
},
]
},
{
"name": "Alder's Razor",
"description": "Win debates with this one-of-a-kind weapon. Sharper and much more deadly than the traditional Occam's Razor",
"abilities": [
{
"name": "Argue",
"effect": "does a lot of damage to enemies of medium intelligence, almost none to low or high. deals fire damage",
},
{
"name": "Shave",
"effect": "weakens enemy to elemental damage",
},
{
"name": "Cut",
"effect": "does a little bit of damage",
},
]
}
];
/**
* @returns {Promise<PlayerWeapon>}
*/
async function generatePlayerWeapon() {
// player weapons happen to basically follow the same format as enemies
// so I'm going to call a lot of that code instead of copying&renaming
let prompt = "";
prompt += INSTRUCTION_PREFIX;
prompt += "The following are several examples of player weapons in a dungeon crawler:\n";
prompt += playerWeaponExamples.map(enemyToString).join('\n');
prompt += "\nPlease generate another weapon similar to the above";
prompt += RESPONSE_PREFIX;
let playerWeaponStr = "";
try {
playerWeaponStr += await requestText({
prompt: prompt+playerWeaponStr,
n_predict: 20,
grammar: "root ::= [0-9a-zA-Z ']+\"\\n\"",
temperature: 1.4,
});
console.log("Generating " + playerWeaponStr);
playerWeaponStr += await requestText({
prompt: prompt+playerWeaponStr,
n_predict: 100,
grammar: "root ::= [0-9a-zA-Z ,.']+\"\\n\"",
temperature: 0.6,
});
playerWeaponStr += await requestText({
prompt: prompt+playerWeaponStr,
n_predict: 100,
grammar: "root ::= (\"* \"[0-9a-zA-Z ]+\": \"[0-9a-zA-Z ]+\"\\n\")+\"\\n\"",
});
return enemyFromString(playerWeaponStr) || playerWeaponExamples[0];
} catch {
return playerWeaponExamples[0];
}
}
/**
* @typedef {Object} Player
* @property {PlayerWeapon} weapon
* @property {Number} health
*/
/**
* @typedef {Object} EnemyInstance
* @property {Enemy} what
* @property {Number} health
*/
/**
* @typedef {Object} Damage
* @typedef {String} who
* @typedef {Number} amount
*/
/**
* @typedef {Object} CombatEvent
* @property {String} who
* @property {String} what
* @property {String} outcome
* @property {[Damage]} damages
*/
/**
* @typedef {Object} GameState
* @property {Player} player
* @property {EnemyInstance} enemy
* @property {[CombatEvent]} combatHistory
*/
/** @type {GameState} */
let gamestate = {
"player": {
"weapon": playerWeaponExamples[0],
"health": 10,
},
"enemy": {
"what": enemyExamples[0],
"health": 5,
},
"combatHistory": []
}
let exampleCombatHistory = `
Player used Rejuvenate!
You feel refreshed, ready to continue fighting.
Player healed 3 damage
Example Enemy used Sneak!
The enemy slithers about, into the bushes. You have a hard time seeing it.
Player used Air Blast!
The example enemy was unable to avoid the large area of the attack, and is knocked back.
Enemy took 4 damage
Player Health: 13
Player Equipment:
Staff of Nature
This magical staff combines the powers of life and death into one.
* Rejuvenate: refill some health
* Poison Flames: moderate damage, more sensitive to elemental resistance/weakness
* Air Blast: moderate damage in a large area
Enemy Health: 1
Enemy info:
Example Enemy
This creature hisses at you, trying to get you to leave.
* Sneak: become harder to hit until next attack
* Venomous Bite: moderate damage
`;
/**
* @returns {String}
*/
function getCommandLog() {
let out = "";
for (item of gamestate.combatHistory) {
out += item.who + " used " + item.what + "!\n";
out += item.outcome + '\n';
for (damage of item.damages) {
out += damage.who + " took " + damage.amount + " damage\n";
}
}
return out;
}
/**
* @returns {String}
*/
function gamestateToString() {
let out = "";
for (item of gamestate.combatHistory) {
out += item.who + " used " + item.what + "!\n";
out += item.outcome + '\n';
for (damage of item.damages) {
out += damage.who + " took " + damage.amount + " damage\n";
}
}
out += '\n';
out += "Player health: " + gamestate.player.health;
out += "Player equipment: \n" + gamestate.player.weapon;
out += '\n';
out += "Enemy health: " + gamestate.enemy.health;
out += "Enemy info: \n" + gamestate.enemy.what;
out += '\n';
}
/**
* @param {String} str
* @returns {CombatEvent}
*/
function combatEventFromString(str) {
let lines = str.trim().split('\n');
if (lines.length < 2) {
console.warn("LLM likely generated incorrect format\n" + str);
return null;
}
/** @type {CombatEvent} */
out = {};
if (!lines[0].match(" used ")) {
console.warn("LLM likely generated incorrect format\n" + str);
return null;
}
out.who = lines[0].split("used")[0].trim();
out.what = lines[0].split("used")[1].trim();
out.what = out.what.substring(0, out.what.indexOf("!"));
out.outcome = lines[1].trim();
out.damages = [];
for (let i = 2; i < lines.length; i++) {
/** @type {Damage} */
damage = {};
damage.who = lines[i].split(" ")[0];
damage.amount = Number(lines[i].match(/[0-9]+/)[0]);
if (lines[i].match("heal")) damage.amount *= -1;
out.damages.push(damage);
}
return out;
}
/** @type {CombatEvent} */
const defaultEnemyAttack = {
"who": "Enemy",
"what": "Unknown Attack",
"outcome": "Some issue with the LLM probably",
"damages": [{
"who": "Player",
"amount": 1,
}],
}
/**
* @returns {CombatEvent}
*/
async function generateEnemyAttack() {
let prompt = "";
prompt += INSTRUCTION_PREFIX;
prompt += "The following is an example of a combat log:\n";
prompt += exampleCombatHistory;
prompt += "Here is a log of our current game:\n"
prompt += gamestateToString();
prompt += "Please generate a possible move for the enemy to make, in the same format as above (move name, description, damage/heal amounts, each on their own line).";
prompt += RESPONSE_PREFIX;
let attackStr = ""
try {
attackStr += gamestate.enemy.what.name + " used";
possibleAttacksGrammar = '(' + gamestate.enemy.what.abilities.map(
(ability) => '"' + ability.name + '"'
).join("|") + ')';
attackStr += await requestText({
prompt: prompt+attackStr,
n_predict: 20,
grammar: "root ::= \" \" " + possibleAttacksGrammar + " \"!\\n\"",
})
attackStr += await requestText({
prompt: prompt+attackStr,
n_predict: 100,
grammar: "root ::= [a-zA-Z ,.']+\"\\n\"",
temperature: 0.9,
});
let optionalDamageNumbers = (
attackStr.match(/[Dd]amage/) || attackStr.match(/[Hh]it/) || attackStr.match(/[Ss]lic/) || attackStr.match(/[Ss]trik/) || attackStr.match(/[Bb]low/) || attackStr.match(/[Ss]wing/)
)? "":"?";
attackStr += await requestText({
prompt: prompt+attackStr,
grammar: "root ::= (\"Player \" (\"took \"|\"healed \") [0-9][0-9]? \" damage\\n\")" + optionalDamageNumbers + "(\"Enemy \" (\"took \"|\"healed \") [0-9][0-9]? \" damage\\n\")?\"\\n\"",
temperature: 0.2,
});
console.log(attackStr);
return combatEventFromString(attackStr) || defaultEnemyAttack;
} catch {
return defaultEnemyAttack;
}
}
const defaultPlayerAttack = {
"who": "Player",
"what": "Unknown Attack",
"outcome": "Some issue with the LLM probably",
"damages": [{
"who": "Enemy",
"amount": 1,
}],
}
/**
* @param {String} what
* @returns {CombatEvent}
*/
async function generatePlayerAttack(what) {
let isValidAbility = false
for (const ability of gamestate.player.weapon.abilities) {
if (ability.name.toLowerCase() == what.toLowerCase()) {
isValidAbility = true;
break;
}
}
if (!isValidAbility) {
console.warn(what + " is not an action the player can take");
return null;
}
let prompt = "";
prompt += INSTRUCTION_PREFIX;
prompt += "The following is an example of a combat log:\n";
prompt += exampleCombatHistory;
prompt += "Here is a log of our current game:\n"
prompt += gamestateToString();
prompt += "Please generate a possible move for the enemy to make, in the same format as above (move name, description, damage/heal amounts, each on their own line).";
prompt += RESPONSE_PREFIX;
let attackStr = ""
attackStr += "Player used " + what + "!\n";
try {
attackStr += await requestText({
prompt: prompt+attackStr,
n_predict: 100,
grammar: "root ::= [a-zA-Z ,.']+\"\\n\"",
temperature: 0.9,
});
let optionalDamageNumbers = (
attackStr.match(/[Dd]amage/) || attackStr.match(/[Hh]it/) || attackStr.match(/[Ss]lic/) || attackStr.match(/[Ss]trik/) || attackStr.match(/[Bb]low/) || attackStr.match(/[Ss]wing/)
)? "":"?";
attackStr += await requestText({
prompt: prompt+attackStr,
grammar: "root ::= (\"Enemy \" (\"took \"|\"healed \") [0-9][0-9]? \" damage\\n\")" + optionalDamageNumbers + "(\"Player \" (\"took \"|\"healed \") [0-9][0-9]? \" damage\\n\")?\"\\n\"",
temperature: 0.2,
});
console.log(attackStr);
return combatEventFromString(attackStr) || defaultPlayerAttack;
} catch {
return defaultPlayerAttack;
}
}