Add function handling for OpenAI model
for now it's querying only time, but in the future there will be more commands
This commit is contained in:
parent
bebef021fb
commit
0df05e2f06
4 changed files with 169 additions and 33 deletions
83
src/funcitonManager.ts
Normal file
83
src/funcitonManager.ts
Normal file
|
@ -0,0 +1,83 @@
|
|||
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)}`;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue