GPTcord/src/funcitonManager.ts

84 lines
2.1 KiB
TypeScript
Raw Normal View History

import { ChatCompletionFunctions, ChatCompletionRequestMessageFunctionCall } from "openai";
import config from "./config";
type parameterMap = {
string: string,
number: number,
};
type nameTypeMap = {[name: string]: keyof parameterMap} | Record<string, never>;
type OpenAIFunctionRequestData<T extends nameTypeMap> = {
[name in keyof T]: T[name];
};
/**
* Represents the function that can be ran by the OpenAI model
*/
export interface OpenAIFunction<T extends nameTypeMap = nameTypeMap> {
name: string,
description?: string,
parameters: {
type: "object",
properties: T extends Record<string, never> ? Record<string, never> : {
[name in T[string]]: {
type: T[name],
description?: string,
}
},
required?: Array<keyof T>,
},
}
export abstract class OpenAIFunction<T extends nameTypeMap = nameTypeMap> {
getSettings(): ChatCompletionFunctions {
return {
name: this.name,
description: this.description,
parameters: this.parameters,
};
}
abstract execute(data: OpenAIFunctionRequestData<T>): string;
}
/*
* Manages functions for the OpenAI
**/
export default class FunctionManager {
store = new Map<string, OpenAIFunction>();
constructor() {
this.store.set("getTime", new GetTime());
}
public getFunctions(): ChatCompletionFunctions[] {
const rvalue: ChatCompletionFunctions[] = [];
for (const [, value] of this.store) {
rvalue.push(value.getSettings());
}
return rvalue;
}
public handleFunction(request: ChatCompletionRequestMessageFunctionCall) {
const parsedArguments = JSON.parse(request.arguments ?? "");
return this.store.get(request.name ?? "")?.execute(parsedArguments);
}
}
// buildins
class GetTime extends OpenAIFunction<Record<string, never>> {
name = "getTime";
description = "Gets current date and time with a timezone attached";
parameters = {
type: "object" as const,
properties: {} as Record<string, never>,
};
execute(): string {
return `${Intl.DateTimeFormat().resolvedOptions().timeZone}): ${new Date().toLocaleString("en-US", config.calendarConfig)}`;
}
}