-
Notifications
You must be signed in to change notification settings - Fork 164
/
bot.ts
504 lines (441 loc) · 16.5 KB
/
bot.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {
AI,
Application,
ConversationHistory,
DefaultConversationState,
DefaultPromptManager,
DefaultTempState,
DefaultTurnState,
DefaultUserState,
OpenAIPlanner,
ResponseParser
} from '@microsoft/teams-ai';
import { ActivityTypes, TurnContext } from 'botbuilder';
import * as path from 'path';
import * as responses from './responses';
import { IItemList } from './interfaces';
import { map } from './ShadowFalls';
import { addActions } from './actions';
import { LastWriterWinsStore } from './LastWriterWinsStore';
import { describeConditions, describeSeason, generateTemperature, generateWeather } from './conditions';
// Strongly type the applications turn state
export interface ConversationState extends DefaultConversationState {
version: number;
greeted: boolean;
turn: number;
location: ILocation;
locationTurn: number;
campaign: ICampaign;
quests: { [title: string]: IQuest };
players: string[];
time: number;
day: number;
temperature: string;
weather: string;
story: string;
nextEncounterTurn: number;
}
export interface UserState extends DefaultUserState {
name: string;
backstory: string;
equipped: string;
inventory: IItemList;
}
export interface TempState extends DefaultTempState {
playerAnswered: boolean;
prompt: string;
promptInstructions: string;
listItems: IItemList;
listType: string;
backstoryChange: string;
equippedChange: string;
originalText: string;
newText: string;
objectiveTitle: string;
}
export interface IDataEntities {
operation: string;
description: string;
items: string;
title: string;
name: string;
backstory: string;
equipped: string;
until: string;
days: string;
}
export interface ICampaign {
title: string;
playerIntro: string;
objectives: ICampaignObjective[];
}
export interface ICampaignObjective {
title: string;
description: string;
completed: boolean;
}
export interface IQuest {
title: string;
description: string;
}
export interface ILocation {
title: string;
description: string;
encounterChance: number;
}
export type ApplicationTurnState = DefaultTurnState<ConversationState, UserState, TempState>;
if (!process.env.OpenAIKey || !process.env.StorageConnectionString || !process.env.StorageContainer) {
throw new Error(
'Missing environment variables - please check that OpenAIKey, StorageConnectionString and StorageContainer are set.'
);
}
// Create AI components
const planner = new OpenAIPlanner<ApplicationTurnState>({
apiKey: process.env.OpenAIKey,
defaultModel: 'gpt-3.5-turbo',
logRequests: true
});
const promptManager = new DefaultPromptManager<ApplicationTurnState>(path.join(__dirname, '../src/prompts'));
// Define storage and application
// - Note that we're not passing a prompt in our AI options as we manually ask for hints.
const storage = new LastWriterWinsStore(process.env.StorageConnectionString, process.env.StorageContainer);
const app = new Application<ApplicationTurnState>({
storage,
ai: {
planner,
promptManager,
prompt: async (context: TurnContext, state: ApplicationTurnState) => state.temp.value.prompt,
history: {
userPrefix: 'Player:',
assistantPrefix: 'DM:',
maxTurns: 3,
maxTokens: 600
}
}
});
// Export bots run() function
export const run = (context: TurnContext) => app.run(context);
export const DEFAULT_BACKSTORY = `Lives in Shadow Falls.`;
export const DEFAULT_EQUIPPED = `Wearing clothes.`;
export const CONVERSATION_STATE_VERSION = 1;
app.turn('beforeTurn', async (context: TurnContext, state: ApplicationTurnState) => {
if (context.activity.type == ActivityTypes.Message) {
let conversation = state.conversation.value;
const player = state.user.value;
const temp = state.temp.value;
// Clear conversation state on version change
if (conversation.version !== CONVERSATION_STATE_VERSION) {
state.conversation.delete();
conversation = state.conversation.value;
conversation.version = CONVERSATION_STATE_VERSION;
}
// Initialize player state
if (!player.name) {
player.name = (context.activity.from?.name ?? '').split(' ')[0];
if (player.name.length == 0) {
player.name = 'Adventurer';
}
}
if (!player.backstory) {
player.backstory = DEFAULT_BACKSTORY;
}
if (!player.equipped) {
player.equipped = DEFAULT_EQUIPPED;
}
if (player.inventory == undefined) {
player.inventory = { map: 1, sword: 1, hatchet: 1, gold: 50 };
}
// Add player to session
if (Array.isArray(conversation.players)) {
if (conversation.players.indexOf(player.name) < 0) {
conversation.players.push(player.name);
}
} else {
conversation.players = [player.name];
}
// Update message text to include players name
// - This ensures their name is in the chat history
const useHelpPrompt = context.activity.text.trim().toLowerCase() == 'help';
context.activity.text = `[${player.name}] ${context.activity.text}`;
// Are we just starting?
let newDay = false;
let campaign: ICampaign;
let location: ILocation;
if (!conversation.greeted) {
newDay = true;
conversation.greeted = true;
temp.prompt = 'intro';
// Create starting location
const village = map.locations['village'];
location = {
title: village.name,
description: village.details,
encounterChance: village.encounterChance
};
// Initialize conversation state
conversation.turn = 1;
conversation.location = location;
conversation.locationTurn = 1;
conversation.quests = {};
conversation.story = `The story begins.`;
conversation.day = Math.floor(Math.random() * 365) + 1;
conversation.time = Math.floor(Math.random() * 14) + 6; // Between 6am and 8pm
conversation.nextEncounterTurn = 5 + Math.floor(Math.random() * 15);
// Create campaign
const response = await app.ai.completePrompt(context, state, 'createCampaign');
if (!response) {
throw new Error('Failed to create campaign');
}
campaign = ResponseParser.parseJSON(response || '') as ICampaign;
if (campaign && campaign.title && Array.isArray(campaign.objectives)) {
// Send campaign title as a message
conversation.campaign = campaign;
await context.sendActivity(`🧙 <strong>${campaign.title}</b>`);
app.startTypingTimer(context);
} else {
state.conversation.delete();
await context.sendActivity(responses.dataError());
return false;
}
} else {
campaign = conversation.campaign;
location = conversation.location;
temp.prompt = 'prompt';
// Increment game turn
conversation.turn++;
conversation.locationTurn++;
// Pass time
conversation.time += 0.25;
if (conversation.time >= 24) {
newDay = true;
conversation.time -= 24;
conversation.day += 1;
if (conversation.day > 365) {
conversation.day = 1;
}
}
}
// Find next campaign objective
let campaignFinished = false;
let nextObjective: ICampaignObjective = {} as ICampaignObjective;
if (Object.entries(campaign).length > 0) {
campaignFinished = true;
for (let i = 0; i < campaign.objectives.length; i++) {
const objective = campaign.objectives[i];
if (!objective.completed) {
// Ignore if the objective is already a quest
if (!conversation.quests.hasOwnProperty(objective.title.toLowerCase())) {
nextObjective = objective;
}
campaignFinished = false;
break;
}
}
}
// Is user asking for help
let objectiveAdded = false;
if (useHelpPrompt && !campaignFinished) {
temp.prompt = 'help';
} else if (nextObjective && Math.random() < 0.2) {
// Add campaign objective as a quest
conversation.quests[nextObjective.title.toLowerCase()] = {
title: nextObjective.title,
description: nextObjective.description
};
// Notify user of new quest
objectiveAdded = true;
await context.sendActivity(
`✨ <strong>${nextObjective.title}</strong><br>${nextObjective.description
.trim()
.split('\n')
.join('<br>')}`
);
app.startTypingTimer(context);
}
// Has a new day passed?
if (newDay) {
const season = describeSeason(conversation.day);
conversation.temperature = generateTemperature(season);
conversation.weather = generateWeather(season);
}
// Load temp variables for prompt use
temp.playerAnswered = false;
temp.promptInstructions = 'Answer the players query.';
if (campaignFinished) {
temp.promptInstructions =
'The players have completed the campaign. Congratulate them and tell them they can continue adventuring or use "/reset" to start over with a new campaign.';
conversation.campaign = {} as ICampaign;
} else if (objectiveAdded) {
temp.prompt = 'newObjective.txt';
temp.objectiveTitle = nextObjective.title;
} else if (conversation.turn >= conversation.nextEncounterTurn && Math.random() <= location.encounterChance) {
// Generate a random encounter
temp.promptInstructions = 'An encounter occurred! Describe to the player the encounter.';
conversation.nextEncounterTurn = conversation.turn + (5 + Math.floor(Math.random() * 15));
}
}
return true;
});
app.turn('afterTurn', async (context: TurnContext, state) => {
const lastSay = ConversationHistory.getLastSay(state);
if (!lastSay) {
// We have a dangling `DM: ` so remove it
ConversationHistory.removeLastLine(state);
// Reply with the current story if we haven't answered player
if (!state.temp.value.playerAnswered) {
const story = state.conversation.value.story;
if (story) {
await context.sendActivity(story);
}
}
}
return true;
});
app.message('/state', async (context: TurnContext, state) => {
await context.sendActivity(JSON.stringify(state));
});
app.message(['/reset-profile', '/reset-user'], async (context: TurnContext, state) => {
state.user.delete();
state.conversation.value.players = [];
await context.sendActivity(`I've reset your profile.`);
});
app.message('/reset', async (context: TurnContext, state: ApplicationTurnState) => {
state.conversation.delete();
await context.sendActivity(`Ok lets start this over.`);
});
app.message('/forget', async (context: TurnContext, state: ApplicationTurnState) => {
ConversationHistory.clear(state);
await context.sendActivity(`Ok forgot all conversation history.`);
});
app.message('/history', async (context: TurnContext, state: ApplicationTurnState) => {
const history = ConversationHistory.toString(state, 4000, `\n\n`);
await context.sendActivity(`<strong>Chat history:</strong><br>${history}`);
});
app.message('/story', async (context: TurnContext, state: ApplicationTurnState) => {
await context.sendActivity(`<strong>The story so far:</strong><br>${state.conversation.value.story ?? ''}`);
});
app.message('/profile', async (context: TurnContext, state: ApplicationTurnState) => {
const player = state.user.value;
const backstory = player.backstory.split('\n').join('<br>');
const equipped = player.equipped.split('\n').join('<br>');
await context.sendActivity(
`🤴 <strong>${player.name}</strong><br><strong>Backstory:</strong> ${backstory}<br><strong>Equipped:</strong> ${equipped}`
);
});
app.ai.action(
AI.UnknownActionName,
async (context: TurnContext, state: ApplicationTurnState, data: Record<string, any>, action: string = ' ') => {
await context.sendActivity(`<strong>${action}</strong> action missing`);
return true;
}
);
addActions(app);
// Register prompt functions
app.ai.prompts.addFunction('describeGameState', async (context: TurnContext, state: ApplicationTurnState) => {
const conversation = state.conversation.value;
return `\tTotalTurns: ${conversation.turn - 1}\n\tLocationTurns: ${conversation.locationTurn - 1}`;
});
app.ai.prompts.addFunction('describeCampaign', async (context: TurnContext, state: ApplicationTurnState) => {
const conversation = state.conversation.value;
if (conversation.campaign) {
return `"${conversation.campaign.title}" - ${conversation.campaign.playerIntro}`;
} else {
return '';
}
});
app.ai.prompts.addFunction('describeQuests', async (context: TurnContext, state: ApplicationTurnState) => {
const conversation = state.conversation.value;
let text = '';
let connector = '';
for (const key in conversation.quests) {
const quest = conversation.quests[key];
text += `${connector}"${quest.title}" - ${quest.description}`;
connector = '\n\n';
}
return text.length > 0 ? text : 'none';
});
app.ai.prompts.addFunction('describePlayerInfo', async (context: TurnContext, state: ApplicationTurnState) => {
const player = state.user.value;
let text = `\tName: ${player.name}\n\tBackstory: ${player.backstory}\n\tEquipped: ${player.equipped}\n\tInventory:\n`;
text += describeItemList(player.inventory, `\t\t`);
return text;
});
app.ai.prompts.addFunction('describeLocation', async (context: TurnContext, state: ApplicationTurnState) => {
const conversation = state.conversation.value;
if (conversation.location) {
return `"${conversation.location.title}" - ${conversation.location.description}`;
} else {
return '';
}
});
app.ai.prompts.addFunction('describeConditions', async (context: TurnContext, state: ApplicationTurnState) => {
const conversation = state.conversation.value;
return describeConditions(conversation.time, conversation.day, conversation.temperature, conversation.weather);
});
/**
* @param items
* @param indent
*/
export function describeItemList(items: IItemList, indent = '\t'): string {
let text = '';
let delim = '';
for (const key in items) {
text += `${delim}\t\t${key}: ${items[key]}`;
delim = '\n';
}
return text;
}
/**
* @param context
* @param state
* @param newResponse
*/
export async function updateDMResponse(
context: TurnContext,
state: ApplicationTurnState,
newResponse: string
): Promise<void> {
if (ConversationHistory.getLastLine(state).startsWith('DM:')) {
ConversationHistory.replaceLastLine(state, `DM: ${newResponse}`);
} else {
ConversationHistory.addLine(state, `DM: ${newResponse}`);
}
await context.sendActivity(newResponse);
}
/**
* @param text
* @param minValue
*/
export function parseNumber(text: string | undefined, minValue?: number): number {
try {
const count = parseInt(text ?? `${minValue ?? 0}`);
if (typeof minValue == 'number') {
return count >= minValue ? count : minValue;
} else {
return count;
}
} catch (err) {
return minValue ?? 0;
}
}
/**
* @param response
*/
export function trimPromptResponse(response: string): string {
// Remove common junk that gets returned by the model.
return response.replace('DM: ', '').replace('```', '');
}
/**
* @param text
*/
export function titleCase(text: string): string {
return text
.toLowerCase()
.split(' ')
.map(function (word) {
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(' ');
}