Skip to content

Commit

Permalink
feat: add context
Browse files Browse the repository at this point in the history
  • Loading branch information
thezanke committed Jul 7, 2023
1 parent cc2d7ac commit 07da858
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 19 deletions.
72 changes: 53 additions & 19 deletions src/commands/chitchatCommand.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { ConfigService } from '@nestjs/config';
import { OnEvent } from '@nestjs/event-emitter';
import { stripIndent } from 'common-tags';
import { Message } from 'discord.js';
import { concat } from 'rxjs';

import { EnvironmentVariables } from '../config/validate';
import { DISCORD_EVENTS } from '../discord/constants';
Expand All @@ -13,6 +12,19 @@ import { OpenAIModerationService } from '../openai/openai-moderation.service';
import { CommandsService } from './commands.service';
import { CommandService } from './types/CommandService';

const pick = <T extends Record<string, unknown>, K extends keyof T>(
obj: T,
keys: K[],
) => {
const ret = {} as Pick<T, K>;

keys.forEach((key) => {
ret[key] = obj[key];
});

return ret;
};

@Injectable()
export class ChitchatCommandService implements CommandService {
constructor(
Expand Down Expand Up @@ -60,7 +72,7 @@ export class ChitchatCommandService implements CommandService {
}
}

private buildReplyChainMessageHistory(replyChain: Message[]) {
public buildReplyChainMessageHistory(replyChain: Message[]) {
return replyChain.reverse().map((m) => {
const memberId = m.member?.id;

Expand All @@ -86,12 +98,6 @@ export class ChitchatCommandService implements CommandService {
return message.split('\n===\n');
}

private async getPromptMessageContext(message: Message) {
const replyChain = await this.discordService.fetchReplyChain(message);

return this.buildReplyChainMessageHistory(replyChain);
}

private async handleChitchatMessage(message: Message) {
if (this.isGptEnabled) {
return this.handleGptChitchat(message);
Expand Down Expand Up @@ -126,8 +132,10 @@ export class ChitchatCommandService implements CommandService {
const chatRequestMessage =
this.createUserChatMessageFromDiscordMessage(message);

const replyChainMessageHistory = await this.getPromptMessageContext(
message,
const replyChain = await this.discordService.fetchReplyChain(message);

const replyChainMessageHistory = await this.buildReplyChainMessageHistory(
replyChain,
);

const userCompletionContent = replyChainMessageHistory
Expand All @@ -146,13 +154,39 @@ export class ChitchatCommandService implements CommandService {

const channel = await message.channel.fetch();

const participantDetails = [
...new Set([
...replyChain.map((m) => m.member || m.author),
message.member || message.author,
]),
].map((author) =>
pick(author as unknown as Record<string, unknown>, [
'id',
'username',
'displayName',
]),
);

const messageChain = [
this.aiCompletionService.createSystemMessage(this.preamble),
stripIndent`
NAME: ${this.discordService.username}
ID: ${this.discordService.userId}
CHANNEL INFO: ${channel.toJSON()}
`,
this.aiCompletionService.createSystemMessage(
stripIndent`
ASSISTANT USER DETAILS: ${JSON.stringify(
pick(
this.discordService.user as unknown as Record<string, unknown>,
['id', 'name'],
),
)}
CHANNEL DETAILS: ${JSON.stringify(
pick(channel as unknown as Record<string, unknown>, [
'id',
'name',
'type',
]),
)}
PARTICIPANT DETAILS: ${JSON.stringify(participantDetails)}
`,
),
...replyChainMessageHistory,
chatRequestMessage,
this.aiCompletionService.createSystemMessage(
Expand All @@ -166,13 +200,13 @@ export class ChitchatCommandService implements CommandService {

const responseMessages = this.getCompletionResponseMessages(response);

return this.handleResponseMessages(message, responseMessages);
await this.handleResponseMessages(message, responseMessages);
} catch (e) {
if (e.response?.status === HttpStatus.TOO_MANY_REQUESTS) {
return message.reply('Out of credits... Please insert token.');
await message.reply('Out of credits... Please insert token.');
} else {
await message.reply('That one hurt my brain..');
}

return message.reply('That one hurt my brain..');
}
}
}
4 changes: 4 additions & 0 deletions src/discord/discord.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export class DiscordService {
return this.discordClient.user?.username ?? 'ph8';
}

public get user() {
return this.discordClient.user;
}

public async fetchReplyChain(message: Message): Promise<Message[]> {
const replyChain: Message[] = [];
let m = message;
Expand Down

0 comments on commit 07da858

Please sign in to comment.