From 23ceca5cd3b686508c091e95c492da76bdce797b Mon Sep 17 00:00:00 2001 From: Wroclaw Date: Wed, 27 Sep 2023 17:14:17 +0200 Subject: [PATCH] Update OpenAI dependency --- package-lock.json | 236 +++++++++++++++++++++++++++++++++------- package.json | 2 +- src/configDefault.ts | 6 +- src/execution.ts | 68 +++++++----- src/funcitonManager.ts | 7 +- src/index.ts | 6 +- src/moderation.ts | 4 +- src/toOpenAIMessages.ts | 2 +- 8 files changed, 250 insertions(+), 81 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9197f43..b20e096 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,8 +13,9 @@ "discord.js": "^14.8.0", "fold-to-ascii": "^5.0.1", "gpt-3-encoder": "^1.1.4", - "openai": "^3.2.1", - "require-directory": "^2.1.1" + "openai": "^4.10.0", + "require-directory": "^2.1.1", + "typescript": "^5.1.6" }, "devDependencies": { "@types/fold-to-ascii": "^5.0.0", @@ -22,8 +23,7 @@ "@typescript-eslint/eslint-plugin": "^6.2.0", "@typescript-eslint/parser": "^6.2.0", "eslint": "^8.46.0", - "prisma": "^5.0.0", - "typescript": "^5.1.6" + "prisma": "^5.0.0" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -321,6 +321,15 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.7.0.tgz", "integrity": "sha512-zI22/pJW2wUZOVyguFaUL1HABdmSVxpXrzIqkjsHmyUjNhPoWM1CKfvVuXfetHhIok4RY573cqS0mZ1SJEnoTg==" }, + "node_modules/@types/node-fetch": { + "version": "2.6.6", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.6.tgz", + "integrity": "sha512-95X8guJYhfqiuVVhRFxVQcf4hW/2bCuoPwDasMf/531STFoNoWTT7YDnWdXHEZKqAGUigmpG31r2FE70LwnzJw==", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + } + }, "node_modules/@types/require-directory": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/@types/require-directory/-/require-directory-2.1.3.tgz", @@ -542,6 +551,17 @@ "npm": ">=7.0.0" } }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, "node_modules/acorn": { "version": "8.10.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", @@ -563,6 +583,17 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/agentkeepalive": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz", + "integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, "node_modules/ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", @@ -623,20 +654,17 @@ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, - "node_modules/axios": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", - "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", - "dependencies": { - "follow-redirects": "^1.14.8" - } - }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, + "node_modules/base-64": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", + "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==" + }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -695,6 +723,14 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "engines": { + "node": "*" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -744,6 +780,14 @@ "node": ">= 8" } }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "engines": { + "node": "*" + } + }, "node_modules/debug": { "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", @@ -775,6 +819,15 @@ "node": ">=0.4.0" } }, + "node_modules/digest-fetch": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz", + "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==", + "dependencies": { + "base-64": "^0.1.0", + "md5": "^2.3.0" + } + }, "node_modules/dir-glob": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", @@ -981,6 +1034,14 @@ "node": ">=0.10.0" } }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "engines": { + "node": ">=6" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -1103,25 +1164,6 @@ "node": ">= 6.3.1" } }, - "node_modules/follow-redirects": { - "version": "1.15.3", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", - "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, "node_modules/form-data": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", @@ -1135,6 +1177,23 @@ "node": ">= 6" } }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -1228,6 +1287,14 @@ "node": ">=8" } }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "dependencies": { + "ms": "^2.0.0" + } + }, "node_modules/ignore": { "version": "5.2.4", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", @@ -1278,6 +1345,11 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -1423,6 +1495,16 @@ "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.2.0.tgz", "integrity": "sha512-NFrX8tqiYYrIiMQ3f0UkqG8INKzF8Lz7Jo2c5Ut6b5/Bzp/sr2z6dQoXPSLVDaioM2N6/k+3sDnD/y4Xpx6lSQ==" }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -1479,8 +1561,7 @@ "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/natural-compare": { "version": "1.4.0", @@ -1488,6 +1569,43 @@ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -1498,14 +1616,28 @@ } }, "node_modules/openai": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/openai/-/openai-3.3.0.tgz", - "integrity": "sha512-uqxI/Au+aPRnsaQRe8CojU0eCR7I0mBiKjD3sNMzY6DaC1ZVrc85u98mtJW6voDug8fgGN+DIZmTDxTthxb7dQ==", + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.10.0.tgz", + "integrity": "sha512-II4b5/7qzwYkqA9MSjgqdofCc798EW+dtF2h6qNaVLet+qO7FShAJTWnoyzb50J4ZH1rPxRFAsmDLIhY3PT6DQ==", "dependencies": { - "axios": "^0.26.0", - "form-data": "^4.0.0" + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "digest-fetch": "^1.3.0", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7" + }, + "bin": { + "openai": "bin/cli" } }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.18.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.18.0.tgz", + "integrity": "sha512-3xA4X31gHT1F1l38ATDIL9GpRLdwVhnEFC8Uikv5ZLlXATwrCYyPq7ZWHxzxc3J/30SUiwiYT+bQe0/XvKlWbw==" + }, "node_modules/optionator": { "version": "0.9.3", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", @@ -1839,6 +1971,11 @@ "node": ">=8.0" } }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, "node_modules/ts-api-utils": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.3.tgz", @@ -1889,7 +2026,6 @@ "version": "5.2.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", - "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -1918,6 +2054,28 @@ "punycode": "^2.1.0" } }, + "node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index 2d3203c..feb71a3 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "discord.js": "^14.8.0", "fold-to-ascii": "^5.0.1", "gpt-3-encoder": "^1.1.4", - "openai": "^3.2.1", + "openai": "^4.10.0", "require-directory": "^2.1.1", "typescript": "^5.1.6" }, diff --git a/src/configDefault.ts b/src/configDefault.ts index 608806b..65785a9 100644 --- a/src/configDefault.ts +++ b/src/configDefault.ts @@ -1,8 +1,8 @@ import { Message } from "discord.js"; import { - ChatCompletionRequestMessage as OpenAIMessage, - CreateChatCompletionRequest as ChatCompletionRequestData, -} from "openai"; + ChatCompletionMessageParam as OpenAIMessage, + ChatCompletionCreateParamsNonStreaming as ChatCompletionRequestData, +} from "openai/resources/chat"; import IQuota from "./IQuota"; import MessageCount from "./quota/messageCount"; diff --git a/src/execution.ts b/src/execution.ts index 0fbe1d2..7575118 100644 --- a/src/execution.ts +++ b/src/execution.ts @@ -1,11 +1,11 @@ import DiscordApi, { GuildTextBasedChannel, TextBasedChannel } from "discord.js"; -import { ChatCompletionRequestMessage, ChatCompletionResponseMessage } from "openai"; -import Axios from "axios"; +import {APIError as OpenAIError} from "openai"; import { database, openai, config } from "./index"; import Moderation from "./moderation"; import toOpenAIMessages from "./toOpenAIMessages"; import FunctionManager from "./funcitonManager"; +import { ChatCompletion, ChatCompletionMessage, ChatCompletionMessageParam } from "openai/resources/chat"; type NonNullableInObject = { [k in keyof T]: k extends V ? NonNullable : T[k] }; export type apiRequest = DiscordApi.Message | DiscordApi.RepliableInteraction; @@ -171,12 +171,12 @@ export async function queueRequest(request: apiRequest) { * @param functionRan counter of how many function have been ran */ function logUsedTokens( - answer: Awaited>, + answer: ChatCompletion, message: RequestMessage, functionRan: number, ) { - const usage = answer.data.usage; - const functionName = answer.data.choices[0].message?.function_call?.name; + const usage = answer.usage; + const functionName = answer.choices[0].message?.function_call?.name; if (usage !== undefined) { const channelName: string = !message.channel.isDMBased() ? `${message.channel.name} (${message.guild?.name})` : `@${getAuthor(message).tag}`; console.log(`Used ${usage.total_tokens} (${usage.prompt_tokens} + ${usage.completion_tokens}) tokens for ${getAuthor(message).tag} (${getAuthor(message).id}) in #${channelName}${functionName ? " [Function: " + functionName + "]" : ""}`); @@ -207,7 +207,7 @@ async function executeFromQueue(channel: string) { const channelQueue = channelsRunning.get(channel) as ChannelsRunningValue; const message = channelQueue.at(0) as RequestMessage; let functionRanCounter = 0; - let OpenAImessages: ChatCompletionRequestMessage[] = []; + let OpenAImessages: ChatCompletionMessageParam[] = []; // ignore if we can't even send anything to reply if (!canReplyToRequest(message)) return; @@ -234,11 +234,11 @@ async function executeFromQueue(channel: string) { }); OpenAImessages = toOpenAIMessages(messages.values()); - let generatedMessage: ChatCompletionResponseMessage | undefined = undefined; - let answer: Awaited>; + let generatedMessage: ChatCompletionMessage | undefined = undefined; + let answer: Awaited>; do { - answer = await openai.createChatCompletion({ + answer = await openai.chat.completions.create({ ...config.chatCompletionParams, messages: OpenAImessages, // FIXME: don't use new instance of FunctionManager @@ -247,7 +247,7 @@ async function executeFromQueue(channel: string) { logUsedTokens(answer, message, ++functionRanCounter); - generatedMessage = answer.data.choices[0].message; + generatedMessage = answer.choices[0].message; if (!generatedMessage) throw new Error("Empty message received"); // handle function calls @@ -262,9 +262,9 @@ async function executeFromQueue(channel: string) { channelQueue.stopTyping(); - const answerContent = answer.data.choices[0].message?.content; + const answerContent = answer.choices[0].message?.content; - if (answerContent === undefined || answerContent === "") { + if (answerContent === null || answerContent === "") { if (message instanceof DiscordApi.Message) message.react("😶").catch(() => {/* GRACEFAIL: It's okay if the bot won't reply */}); } else { @@ -285,29 +285,37 @@ async function executeFromQueue(channel: string) { } } } catch (e) { + let errorText: string = ""; channelQueue.stopTyping(); - console.error(`Error ocurred while handling chat completion request (${(e as object).constructor.name}):`); - if (Axios.isAxiosError(e)) { - console.error(JSON.stringify(e.response?.data)); - } - else { + if (typeof e !== "object") { + console.error(`Error ocurred while handling chat completion request (${typeof e}):`); console.error(e); } - if (OpenAImessages.length !== 0) { - console.error("Messages:"); - console.error(OpenAImessages); + else if (e === null) { + console.error ("Error ocurred while handling chat completion request: null"); } + else { + console.error(`Error ocurred while handling chat completion request (${e.constructor.name}):`); + if (e instanceof OpenAIError) { + console.error(JSON.stringify(e)); + } + else { + console.error(e); + } + if (OpenAImessages.length !== 0) { + console.error("Messages:"); + console.error(OpenAImessages); + } - let errorText = "\n"; - - if (e instanceof Error) { - errorText += e.message; - } - else errorText = ""; - if (Axios.isAxiosError(e) && e.code?.match(/^5..$/) && channelQueue.tries < 3) { - channelQueue.tries++; - await new Promise(r => setTimeout(r, 2000)); // pause for 2 seconds before retrying - return executeFromQueue(channel); + if (e instanceof Error) { + errorText = e.message; + } + else errorText = ""; + if (e instanceof OpenAIError && e.code?.match(/^5..$/) && channelQueue.tries < 3) { + channelQueue.tries++; + await new Promise(r => setTimeout(r, 2000)); // pause for 2 seconds before retrying + return executeFromQueue(channel); + } } requestReply( diff --git a/src/funcitonManager.ts b/src/funcitonManager.ts index 27d3a91..9bcb0ec 100644 --- a/src/funcitonManager.ts +++ b/src/funcitonManager.ts @@ -1,4 +1,4 @@ -import { ChatCompletionFunctions, ChatCompletionRequestMessage, ChatCompletionRequestMessageFunctionCall } from "openai"; +import { ChatCompletionCreateParams, ChatCompletionMessage, ChatCompletionMessageParam } from "openai/resources/chat"; import { config } from "./index"; @@ -13,6 +13,9 @@ type OpenAIFunctionRequestData = { [name in keyof T]: T[name]; }; +type ChatCompletionFunctions = ChatCompletionCreateParams.Function; +type ChatCompletionFunctionCall = ChatCompletionMessage.FunctionCall; + /** * Represents the function that can be ran by the OpenAI model */ @@ -61,7 +64,7 @@ export default class FunctionManager { return rvalue; } - public handleFunction(request: ChatCompletionRequestMessageFunctionCall): ChatCompletionRequestMessage { + public handleFunction(request: ChatCompletionFunctionCall): ChatCompletionMessageParam { // eslint-disable-next-line @typescript-eslint/no-explicit-any let parsedArguments: any; diff --git a/src/index.ts b/src/index.ts index 66a2ceb..27e5c45 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import DiscordApi from "discord.js"; -import { Configuration as OpenAIApiConfiguration, OpenAIApi } from "openai"; +import OpenAIApi from "openai"; import { PrismaClient } from "@prisma/client"; import Typescript from "typescript"; import fs from "node:fs"; @@ -43,9 +43,9 @@ function getConfig() { export const config: IConfigRequired = getConfig(); -export const openai = new OpenAIApi(new OpenAIApiConfiguration({ +export const openai = new OpenAIApi({ apiKey: config.tokens.OpenAI -})); +}); export const database = new PrismaClient(); diff --git a/src/moderation.ts b/src/moderation.ts index 9a7439b..cafaeab 100644 --- a/src/moderation.ts +++ b/src/moderation.ts @@ -28,11 +28,11 @@ export default class Moderation { } } - const answer = await openai.createModeration({ + const answer = await openai.moderations.create({ input: await formatRequestOrResponse(message), }); - const flagged = answer.data.results[0].flagged; + const flagged = answer.results[0].flagged; this.cache.set(message.id, flagged); // FIXME: These next 7 lines does not belong there and should be refactored out. if (flagged) if (message instanceof Message) { diff --git a/src/toOpenAIMessages.ts b/src/toOpenAIMessages.ts index f7ed362..3ee9ee8 100644 --- a/src/toOpenAIMessages.ts +++ b/src/toOpenAIMessages.ts @@ -1,4 +1,4 @@ -import { ChatCompletionRequestMessage as OpenAIMessage } from "openai"; +import { ChatCompletionMessageParam as OpenAIMessage } from "openai/resources/chat"; import { Collection, Message as DiscordMessage, InteractionResponse } from "discord.js"; import FoldToAscii from "fold-to-ascii";