Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small code quality improvements #17

Merged
merged 1 commit into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gptitor",
"version": "1.3.1",
"version": "1.3.3",
"description": "",
"main": "src/index.ts",
"scripts": {
Expand Down
12 changes: 6 additions & 6 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ export default class Bot extends Telegraf<BotContext> {
};

await Datastore.init();
await Midjourney.init({
ServerId: DISCORD_SERVER_ID!,
ChannelId: DISCORD_CHANNEL_ID!,
SalaiToken: DISCORD_SALAI_TOKEN!,
Debug: isDev
});
// await Midjourney.init({
// ServerId: DISCORD_SERVER_ID!,
// ChannelId: DISCORD_CHANNEL_ID!,
// SalaiToken: DISCORD_SALAI_TOKEN!,
// Debug: isDev
// });

for (const lang of this.botServices.translation.supportedLangs) {
const $t = this.botServices.translation.getTranslator(lang);
Expand Down
44 changes: 22 additions & 22 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,28 @@ const config = {
maxTokens: 4096
},
functions: [
{
name: "generateImage",
description: "Generate an image from a user's prompt. Can be called only when user explicitly asks for an image",
parameters: {
type: "object",
properties: {
prompt: {
type: "string",
description: "Clear and concise prompt string in English language without verbs that describes the image to be generated"
}
},
required: ["prompt"]
},
},
{
name: "describeImage",
description: "Describe in human readable format what is depicted on provided image",
parameters: {
type: "object",
properties: {}
}
}
// {
// name: "generateImage",
// description: "Generate an image from a user's prompt. Can be called only when user explicitly asks for an image",
// parameters: {
// type: "object",
// properties: {
// prompt: {
// type: "string",
// description: "Clear and concise prompt string in English language without verbs that describes the image to be generated"
// }
// },
// required: ["prompt"]
// },
// },
// {
// name: "describeImage",
// description: "Describe in human readable format what is depicted on provided image",
// parameters: {
// type: "object",
// properties: {}
// }
// }
],
userQuota: {
startTokens: 10000,
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import "dotenv/config";
import * as fs from "fs";
import express from "express";
import { type AxiosError } from 'axios';
import d from "debug";

import Bot from "./bot";
Expand Down Expand Up @@ -29,7 +30,7 @@ app.post("/bot", async (request, response, next) => {
(error as Error).message,
(error as Error).stack,
request.body,
(error as any).response?.data
(error as AxiosError).response?.data
);
log.write(`Error: ${JSON.stringify(error, null, 2)}\nRequest: ${request.body}`, "utf-8");
}
Expand Down
9 changes: 3 additions & 6 deletions src/scenes/dialog/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const debug = d("bot:dialog");
export async function onPhoto(ctx: BotContext, next: () => Promise<void>) {
const message = ctx.message as Message.PhotoMessage & Message.TextMessage;

message.photo = [message.photo.sort((photoA, photoB) => photoB.file_size! - photoA.file_size!)[0]];
message.photo = message.photo.sort((photoA, photoB) => photoB.file_size! - photoA.file_size!).slice(0, 0);
message.text = message.caption ?? "";

return next();
Expand Down Expand Up @@ -90,11 +90,8 @@ async function answer(ctx: BotContext, conversation: ChatCompletionRequestMessag

if (content) {
for (const answer of format(content)) {
const reply = await ctx.replyWithMarkdownV2(answer, {
reply_to_message_id: msg.reply_to_message ? msg.message_id : undefined
});

ctx.conversation.save(msg, reply, conversation[conversation.length - 1].content!, answer);
const reply = await ctx.replyWithMarkdownV2(answer, { reply_to_message_id: msg.message_id });
ctx.conversation.save(msg, reply, conversation[conversation.length - 1].content!, content);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/scenes/settings/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default {
async model(ctx: BotContext) {
const models = await ctx.openai.getModels();

return ctx.editMessageReplyMarkup(Markup.inlineKeyboard(
await ctx.editMessageReplyMarkup(Markup.inlineKeyboard(
models.map(model => Markup.button.callback(model, `selectModel:${model}`)),
{ columns: 3 }
).reply_markup);
Expand All @@ -30,7 +30,7 @@ export default {
.sort((a, b) => parseFloat(a[0]) - parseFloat(b[0]))
.map(([id, label]) => Markup.button.callback(label, `setTemperature:${id}`));

return ctx.editMessageReplyMarkup(Markup.inlineKeyboard(buttons, { columns: 2 }).reply_markup);
await ctx.editMessageReplyMarkup(Markup.inlineKeyboard(buttons, { columns: 2 }).reply_markup);
},

async setTemperature(ctx: BotContext, selectedLevel: string) {
Expand All @@ -57,4 +57,4 @@ export default {

// return ctx.scene.reenter();
// }
} as const;
} as Record<string, (ctx: BotContext, param?: string) => Promise<void>>;
5 changes: 3 additions & 2 deletions src/scenes/settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,11 @@ scene.enter(async (ctx) => {

scene.action(/^(\w+)(?::(.+))?$/, async (ctx) => {
const [, action, param] = ctx.match;
const actionHandler = actions[action as keyof typeof actions];

await ctx.answerCbQuery();
if (actions[action as keyof typeof actions]) {
await actions[action as keyof typeof actions](ctx, param as any);
if (actionHandler) {
await actionHandler(ctx, param);
}
});

Expand Down
7 changes: 2 additions & 5 deletions src/services/Translation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { default as en } from "../lang/en";
import { default as ru } from "../lang/ru";
import config from "../config";

export type LangName = keyof typeof langs;
export type LangStringKey = keyof typeof en;
Expand All @@ -13,11 +12,9 @@ export default class Translation {
return Object.keys(langs) as LangName[];
}

getTranslator(lang: string): Translator {
const strings = langs[lang as LangName] ?? langs[config.defaultLang];
// return new Translation(strings);
getTranslator(lang: LangName): Translator {
return (key, tokens) => {
const text = strings[key];
const text = langs[lang][key];
if (typeof text === "function") {
return text(tokens as any);
}
Expand Down
6 changes: 4 additions & 2 deletions src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import Bot, { type BotContext } from "../bot";
import config from "../config";

import Datastore from "./Datastore";
import OpenAI from "./OpenAI";
import Quota from "./Quota";
import Settings from "./Settings";
import Midjourney from "./Midjourney";
import { type LangName } from "./Translation";

export { default as Datastore } from "./Datastore";
export { default as OpenAI } from "./OpenAI";
export { default as Quota, type UserQuota } from "./Quota";
export { default as Settings, type ChatSettings } from "./Settings";
export { default as Conversation } from "./Conversation";
export { default as Midjourney, type Generation, type GeneratedImage } from "./Midjourney";
export { default as Translation, type Translator } from "./Translation";
export { default as Translation, type Translator, type LangName } from "./Translation";

export function services(bot: Bot) {
const { OPENAI_KEY } = process.env;
Expand All @@ -29,7 +31,7 @@ export function services(bot: Bot) {
ctx.settings = new Settings(ctx.session);
ctx.timestamp = Date.now();
ctx.host = bot.host!;
ctx.$t = translation.getTranslator(ctx.from?.language_code!);
ctx.$t = translation.getTranslator(ctx.from?.language_code as LangName || config.defaultLang);

await next();
}
Expand Down
12 changes: 9 additions & 3 deletions src/services/openai.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { Configuration, OpenAIApi, ChatCompletionRequestMessage, CreateChatCompletionResponseChoicesInner } from "openai";
import {
Configuration,
OpenAIApi,
ChatCompletionRequestMessage,
CreateChatCompletionResponseChoicesInner
} from "openai";
import { type AxiosError } from 'axios';
import { Readable } from "stream";
import d from "debug";

Expand Down Expand Up @@ -39,9 +45,9 @@ export default class OpenAI {

return data.choices;
} catch (error) {
debug("createChatCompletion error", (error as any).response?.data ?? (error as Error).message);
debug("createChatCompletion error", (error as AxiosError).response?.data ?? (error as Error).message);

const message = (error as any).response?.data?.error?.message;
const message = (error as AxiosError).response?.data?.error?.message;
return message
? [{ message: { content: message, role: "system" }, finish_reason: "error" }]
: [];
Expand Down