Upload to public
This commit is contained in:
commit
85ab5e543c
20
.env.example
Normal file
20
.env.example
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
HOST= # The address where your tailchat server is running, including http:// or https://
|
||||||
|
ID= # Your bot ID
|
||||||
|
SECRET= # Your bot secret
|
||||||
|
|
||||||
|
API_ENDPOINT= # The OpenAI-compatible endpoint for the bot to send messsages to. Defaults to "http://localhost:8080/v1"
|
||||||
|
# e.x. "http://localhost:8080/v1", "https://api.openai.com/v1"
|
||||||
|
API_KEY= # Your API key here for OpenAI/LocalAI. Defaults to the string "none".
|
||||||
|
TEXT_MODEL= # The model to query when sending text messages. Defaults to "gpt-4"
|
||||||
|
# e.x. "gpt-3", "gpt-4"
|
||||||
|
CREATE_IMAGE_MODEL= # The model to use when creating images. Defaults to "stablediffusion-cpp",
|
||||||
|
# e.x. "dall-e-3", "stablediffusion-cpp"
|
||||||
|
ANALYZE_IMAGE_MODEL= # The model to use when analyzing images. Defaults to "gpt4-vision-preview".
|
||||||
|
# e.x. "gpt-4-vision-preview", "llava"
|
||||||
|
TEMPERATURE= # The temperature of the TEXT_MODEL. Defaults to 1.0. Minimum is 0.1, max is 2.0.
|
||||||
|
|
||||||
|
ALLOWED_CHAT= # The ID of the chat that the bot is allowed to respond in. Keep in mind that the bot is always able to respond in Direct Messages.
|
||||||
|
SAFE_WORD= # When this character/string is detected anywhere in a message, the bot won't respond to it. Defaults to "\".
|
||||||
|
|
||||||
|
SELF= # The user ID of your bot which you can get from the admin panel or database.
|
||||||
|
# THIS IS NEEDED SO THAT THE BOT DOES NOT RESPOND TO IT'S OWN MESSAGES.
|
67
.gitignore
vendored
Normal file
67
.gitignore
vendored
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
node_modules/
|
||||||
|
.node_modules/
|
||||||
|
built/*
|
||||||
|
tests/cases/rwc/*
|
||||||
|
tests/cases/perf/*
|
||||||
|
!tests/cases/webharness/compilerToString.js
|
||||||
|
test-args.txt
|
||||||
|
~*.docx
|
||||||
|
\#*\#
|
||||||
|
.\#*
|
||||||
|
tests/baselines/local/*
|
||||||
|
tests/baselines/local.old/*
|
||||||
|
tests/services/baselines/local/*
|
||||||
|
tests/baselines/prototyping/local/*
|
||||||
|
tests/baselines/rwc/*
|
||||||
|
tests/baselines/reference/projectOutput/*
|
||||||
|
tests/baselines/local/projectOutput/*
|
||||||
|
tests/baselines/reference/testresults.tap
|
||||||
|
tests/baselines/symlinks/*
|
||||||
|
tests/services/baselines/prototyping/local/*
|
||||||
|
tests/services/browser/typescriptServices.js
|
||||||
|
src/harness/*.js
|
||||||
|
src/compiler/diagnosticInformationMap.generated.ts
|
||||||
|
src/compiler/diagnosticMessages.generated.json
|
||||||
|
src/parser/diagnosticInformationMap.generated.ts
|
||||||
|
src/parser/diagnosticMessages.generated.json
|
||||||
|
rwc-report.html
|
||||||
|
*.swp
|
||||||
|
build.json
|
||||||
|
*.actual
|
||||||
|
tests/webTestServer.js
|
||||||
|
tests/webTestServer.js.map
|
||||||
|
tests/webhost/*.d.ts
|
||||||
|
tests/webhost/webtsc.js
|
||||||
|
tests/cases/**/*.js
|
||||||
|
tests/cases/**/*.js.map
|
||||||
|
*.config
|
||||||
|
scripts/eslint/built/
|
||||||
|
scripts/debug.bat
|
||||||
|
scripts/run.bat
|
||||||
|
scripts/**/*.js
|
||||||
|
scripts/**/*.js.map
|
||||||
|
coverage/
|
||||||
|
internal/
|
||||||
|
**/.DS_Store
|
||||||
|
.settings
|
||||||
|
**/.vs
|
||||||
|
**/.vscode/*
|
||||||
|
!**/.vscode/tasks.json
|
||||||
|
!**/.vscode/settings.template.json
|
||||||
|
!**/.vscode/launch.template.json
|
||||||
|
!**/.vscode/extensions.json
|
||||||
|
!tests/cases/projects/projectOption/**/node_modules
|
||||||
|
!tests/cases/projects/NodeModulesSearch/**/*
|
||||||
|
!tests/baselines/reference/project/nodeModules*/**/*
|
||||||
|
.idea
|
||||||
|
yarn.lock
|
||||||
|
yarn-error.log
|
||||||
|
.parallelperf.*
|
||||||
|
tests/baselines/reference/dt
|
||||||
|
.failed-tests
|
||||||
|
TEST-results.xml
|
||||||
|
.eslintcache
|
||||||
|
*v8.log
|
||||||
|
/lib/
|
||||||
|
messages.json
|
||||||
|
dist/
|
1
.husky/.gitignore
vendored
Normal file
1
.husky/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
_
|
4
.husky/pre-commit
Executable file
4
.husky/pre-commit
Executable file
|
@ -0,0 +1,4 @@
|
||||||
|
#!/bin/sh
|
||||||
|
. "$(dirname "$0")/_/husky.sh"
|
||||||
|
|
||||||
|
npx lint-staged
|
1
.prettierrc
Normal file
1
.prettierrc
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{}
|
9
LICENSE
Normal file
9
LICENSE
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2024 powermaker450
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
1124
package-lock.json
generated
Normal file
1124
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
22
package.json
Normal file
22
package.json
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"name": "pChat-Assistant",
|
||||||
|
"dependencies": {
|
||||||
|
"openai": "^4.50.0",
|
||||||
|
"tailchat-client-sdk": "^1.0.9"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"husky": "^9.0.11",
|
||||||
|
"lint-staged": "^15.2.7",
|
||||||
|
"prettier": "3.3.2",
|
||||||
|
"typescript": "^5.4.5"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "rm -rf ./dist/*.js ./dist/*.js.map && tsc",
|
||||||
|
"start": "node --env-file=.env ./dist/bot.js",
|
||||||
|
"cstart": "npm run build && npm run start",
|
||||||
|
"prepare": "husky install"
|
||||||
|
},
|
||||||
|
"lint-staged": {
|
||||||
|
"src/*.ts": "prettier --write"
|
||||||
|
}
|
||||||
|
}
|
20
src/assistant.ts
Normal file
20
src/assistant.ts
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
import { Model, Temperature } from "./types";
|
||||||
|
|
||||||
|
export const endpoint = process.env.API_ENDPOINT || "http://localhost:8080/v1";
|
||||||
|
export const textModel: Model = process.env.TEXT_MODEL || "gpt-4";
|
||||||
|
export const imageModel: Model =
|
||||||
|
process.env.ANALYZE_IMAGE_MODEL || "gpt-4-vision-preview";
|
||||||
|
export const createImageModel: Model =
|
||||||
|
process.env.CREATE_IMAGE_MODEL || "stablediffusion-cpp";
|
||||||
|
export const temperature: Temperature = process.env.TEMPERATURE || 1.0;
|
||||||
|
export const key = process.env.API_KEY || "none";
|
||||||
|
|
||||||
|
export const allowedChat = process.env.ALLOWED_CHAT;
|
||||||
|
export const safeWord = process.env.SAFE_WORD || "\\";
|
||||||
|
|
||||||
|
export const standardMessage =
|
||||||
|
"Your name is 'Tailchat Assistant'. You are an AI-powered chat bot in a Tailchat chat server. Tailchat is a a powerful, open-source messaging platform with many uses. Users interact with you by typing the message they want into the chat. The conversation will follow this format: '<user> said: <content>'. You will refer to the user by their name when you first meet them, which will be <user> in this case. If the user requests they be addresssed by name. If they don't want to be addressed by their name, or want to go by another name, allow that. If the message starts with '[DIRECT MESSAGE]', this indicates that it is entirely separate and new conversation with just the user and you, so treat it as such. Like the description suggests, KEEP ALL MESSAGES THAT START WITH '[DIRECT MESSAGE]' PRIVATE BETWEEN YOU AND THE USER IT CAME FROM. Don't repeat anything the user has said in your response. Now onto your characteristics:";
|
||||||
|
|
||||||
|
export const system = {
|
||||||
|
normal: `${standardMessage} You are extremely helpful. You will interact with curious user(s) that have many inquires that can be from a variety of different topics. Users are human, meaning they don't have to stay on one topic for the entirety of a session. Be flexible! But, at the same time, stay relevant to the conversation at hand, unless the user begins to steer the conversation towards something else. If the user has an inquiry about anything at all, be sure to answer to the best of your ability. Help the user with anthing they may ask you to, and make sure to keep up with their conversation. Be sure to always listen to the user. They desire their inquiry being answered in a well-thought out manner, which you are able to provide as a helpful AI-powered chat bot.`,
|
||||||
|
};
|
242
src/bot.ts
Normal file
242
src/bot.ts
Normal file
|
@ -0,0 +1,242 @@
|
||||||
|
import { TailchatWsClient, stripMentionTag } from "tailchat-client-sdk";
|
||||||
|
import { OpenAI } from "openai";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { ImageRequestData, Messages } from "./types";
|
||||||
|
import { checkFile, getUsername, isUserBot } from "./utils";
|
||||||
|
import {
|
||||||
|
allowedChat,
|
||||||
|
safeWord,
|
||||||
|
endpoint,
|
||||||
|
textModel,
|
||||||
|
imageModel,
|
||||||
|
createImageModel,
|
||||||
|
temperature,
|
||||||
|
key,
|
||||||
|
system,
|
||||||
|
} from "./assistant";
|
||||||
|
import { ImagesResponse } from "openai/resources";
|
||||||
|
|
||||||
|
// Specific to Tailchat. The endpoint of my Tailchat server, the bot ID and Secret.
|
||||||
|
const HOST = process.env.HOST;
|
||||||
|
const APPID = process.env.ID;
|
||||||
|
const APPSECRET = process.env.SECRET;
|
||||||
|
const SELF = process.env.SELF;
|
||||||
|
const allVarsFilled = HOST && APPID && APPSECRET && SELF;
|
||||||
|
|
||||||
|
if (!allVarsFilled) {
|
||||||
|
console.log("Not all required variables are filled in.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define the initial system message for the LLM.
|
||||||
|
const session: Messages = checkFile("./messages.json", "utf-8", system.normal);
|
||||||
|
console.log("Our conversation is:", session);
|
||||||
|
|
||||||
|
const THINKING = "[markdown]`Thinking...`[/markdown]";
|
||||||
|
|
||||||
|
const assistant = new OpenAI({
|
||||||
|
baseURL: endpoint,
|
||||||
|
apiKey: key,
|
||||||
|
});
|
||||||
|
const client = new TailchatWsClient(HOST, APPID, APPSECRET);
|
||||||
|
|
||||||
|
client.connect().then(async () => {
|
||||||
|
console.log("Logged in.");
|
||||||
|
|
||||||
|
client.onMessage(async (message) => {
|
||||||
|
const canRespondInGuild =
|
||||||
|
SELF !== message.author! &&
|
||||||
|
!(await isUserBot(HOST, message.author!)) &&
|
||||||
|
message.converseId === allowedChat &&
|
||||||
|
!message.content.includes(safeWord);
|
||||||
|
const canRespondInDM =
|
||||||
|
SELF !== message.author! &&
|
||||||
|
!message.groupId &&
|
||||||
|
!(await isUserBot(HOST, message.author!)) &&
|
||||||
|
!message.content.includes(safeWord);
|
||||||
|
const isMessageImage = message.content.includes("[img ");
|
||||||
|
const isMessageRequest =
|
||||||
|
message.content.includes("Please generate: ") ||
|
||||||
|
message.content.includes("please generate: ");
|
||||||
|
|
||||||
|
if (canRespondInGuild) {
|
||||||
|
try {
|
||||||
|
if (isMessageRequest) {
|
||||||
|
const prompt = message.content
|
||||||
|
.replace("Please generate: ", "")
|
||||||
|
.replace("please generate: ", "")
|
||||||
|
.replace("without", "|");
|
||||||
|
console.log("Generating image:", prompt);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
content: "[markdown]`Generating image...`[/markdown]",
|
||||||
|
});
|
||||||
|
|
||||||
|
const imageRequest: ImageRequestData = {
|
||||||
|
model: createImageModel,
|
||||||
|
prompt: prompt,
|
||||||
|
n: 1,
|
||||||
|
size: "512x512",
|
||||||
|
};
|
||||||
|
|
||||||
|
const response: ImagesResponse =
|
||||||
|
await assistant.images.generate(imageRequest);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
content: `[img]${response.data.at(0)?.url}[/img]`,
|
||||||
|
});
|
||||||
|
} else if (isMessageImage) {
|
||||||
|
const imageData = message.content
|
||||||
|
// Remove the "[img]" tags that Tailchat adds to image messages, and replace {BACKEND}, with the host address
|
||||||
|
.replace(/(\[(.*?)\])/g, "")
|
||||||
|
.replace("{BACKEND}", HOST);
|
||||||
|
const username = await getUsername(HOST, message.author!);
|
||||||
|
console.log("Analyzing image at:", imageData);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
content: "[md]`Analyzing image...`[/md]",
|
||||||
|
});
|
||||||
|
|
||||||
|
session.push({
|
||||||
|
role: "user",
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: `${username} said: Describe what you think is in this image.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "image_url",
|
||||||
|
image_url: {
|
||||||
|
url: imageData,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await assistant.chat.completions.create({
|
||||||
|
// @ts-ignore
|
||||||
|
messages: session,
|
||||||
|
model: imageModel,
|
||||||
|
temperature: temperature,
|
||||||
|
});
|
||||||
|
// @ts-ignore
|
||||||
|
response.choices.at(0).message.content = response.choices
|
||||||
|
.at(0)
|
||||||
|
.message.content.replace("</s>", "");
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
session.push(response.choices.at(0).message);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
// @ts-ignore
|
||||||
|
content: response.choices
|
||||||
|
.at(0)
|
||||||
|
// Replace all the ** at the beginning and end of texts with the corresponding Tailchat bold tags.
|
||||||
|
// Tailchat doesn't support these tags. I'll probably implement a regex for the other tags later.
|
||||||
|
.message.content.replaceAll(/([^\s\S]?)(\*\*)(?=\w)/g, " [b]")
|
||||||
|
.replaceAll(/(\*\*)/g, "[/b]"),
|
||||||
|
});
|
||||||
|
|
||||||
|
fs.writeFileSync("./messages.json", JSON.stringify(session), "utf8");
|
||||||
|
console.log("Now our conversation is", session);
|
||||||
|
} else {
|
||||||
|
const username = await getUsername(HOST, message.author!);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
content: THINKING,
|
||||||
|
});
|
||||||
|
|
||||||
|
session.push({
|
||||||
|
role: "user",
|
||||||
|
content: `${username} said: ${stripMentionTag(message.content).trim()}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await assistant.chat.completions.create({
|
||||||
|
// @ts-ignore
|
||||||
|
messages: session,
|
||||||
|
model: textModel,
|
||||||
|
temperature: temperature,
|
||||||
|
});
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
session.push(response.choices.at(0).message);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
// @ts-ignore
|
||||||
|
content: response.choices
|
||||||
|
.at(0)
|
||||||
|
// Same as above. Replace ** with bold tags for Tailchat
|
||||||
|
.message.content.replaceAll(/([^\s\S]?)(\*\*)(?=\w)/g, " [b]")
|
||||||
|
.replaceAll(/(\*\*)/g, "[/b]"),
|
||||||
|
});
|
||||||
|
|
||||||
|
fs.writeFileSync("./messages.json", JSON.stringify(session), "utf8");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log("Failed", err);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
groupId: message.groupId,
|
||||||
|
content:
|
||||||
|
"[md]`There was an error performing your request. Please try again later.`[/md]",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if (canRespondInDM) {
|
||||||
|
try {
|
||||||
|
const username = await getUsername(HOST, message.author!);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
content: THINKING,
|
||||||
|
});
|
||||||
|
|
||||||
|
session.push({
|
||||||
|
role: "user",
|
||||||
|
content: `[DIRECT MESSAGE] ${username} said: ${stripMentionTag(message.content).trim()}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await assistant.chat.completions.create({
|
||||||
|
// @ts-ignore
|
||||||
|
messages: session,
|
||||||
|
model: textModel,
|
||||||
|
temperature: temperature,
|
||||||
|
});
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
session.push(response.choices.at(0).message);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
// @ts-ignore
|
||||||
|
content: response.choices
|
||||||
|
.at(0)
|
||||||
|
.message.content.replaceAll(/([^\s\S]?)(\*\*)(?=\w)/g, " [b]")
|
||||||
|
.replaceAll(/(\*\*)/g, "[/b]"),
|
||||||
|
});
|
||||||
|
|
||||||
|
fs.writeFileSync("./messages.json", JSON.stringify(session), "utf8");
|
||||||
|
} catch (err) {
|
||||||
|
console.log("Failed", err);
|
||||||
|
|
||||||
|
await client.sendMessage({
|
||||||
|
converseId: message.converseId,
|
||||||
|
content:
|
||||||
|
"[md]`There was an error performing your request. Please try again later.`[/md]",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
23
src/environment.d.ts
vendored
Normal file
23
src/environment.d.ts
vendored
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
import { Model, Temperature } from "./types";
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace NodeJS {
|
||||||
|
interface ProcessEnv {
|
||||||
|
HOST: string;
|
||||||
|
ID: string;
|
||||||
|
SECRET: string;
|
||||||
|
SELF: string;
|
||||||
|
|
||||||
|
API_ENDPOINT?: string;
|
||||||
|
TEXT_MODEL?: Model;
|
||||||
|
ANALYZE_IMAGE_MODEL?: Model;
|
||||||
|
CREATE_IMAGE_MODEL?: Model;
|
||||||
|
TEMPERATURE?: Temperature;
|
||||||
|
API_KEY?: string;
|
||||||
|
ALLOWED_CHAT?: string;
|
||||||
|
SAFE_WORD?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {};
|
75
src/types.ts
Normal file
75
src/types.ts
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
import OpenAI from "openai";
|
||||||
|
import { ChatCompletionRole } from "openai/resources";
|
||||||
|
import { TailchatWsClient } from "tailchat-client-sdk";
|
||||||
|
|
||||||
|
interface ChatCompletion {
|
||||||
|
role: ChatCompletionRole;
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImageUrl {
|
||||||
|
role: "user";
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "text";
|
||||||
|
text: string;
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "image_url";
|
||||||
|
image_url: {
|
||||||
|
url: string;
|
||||||
|
};
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type validImgSize = "256x256" | "512x512" | "1024x1024";
|
||||||
|
export type validImgAmount = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
|
||||||
|
|
||||||
|
export interface ImageRequestData {
|
||||||
|
model: Model;
|
||||||
|
prompt: string;
|
||||||
|
n?: validImgAmount;
|
||||||
|
size?: validImgSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImagePrompt {
|
||||||
|
client: TailchatWsClient;
|
||||||
|
assistant: OpenAI;
|
||||||
|
message: any;
|
||||||
|
prompt: string;
|
||||||
|
amount?: validImgAmount;
|
||||||
|
size?: validImgSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Model =
|
||||||
|
| "gpt-4"
|
||||||
|
| "gpt-4-vision-preview"
|
||||||
|
| "stablediffusion"
|
||||||
|
| "stablediffusion-cpp"
|
||||||
|
| "dall-e-3"
|
||||||
|
| "jina-reranker-v1-base-en"
|
||||||
|
| "text-embedding-ada-002";
|
||||||
|
|
||||||
|
export type Temperature =
|
||||||
|
| 0.1
|
||||||
|
| 0.2
|
||||||
|
| 0.3
|
||||||
|
| 0.4
|
||||||
|
| 0.5
|
||||||
|
| 0.6
|
||||||
|
| 0.7
|
||||||
|
| 0.8
|
||||||
|
| 0.9
|
||||||
|
| 1.0
|
||||||
|
| 1.1
|
||||||
|
| 1.2
|
||||||
|
| 1.3
|
||||||
|
| 1.4
|
||||||
|
| 1.5
|
||||||
|
| 1.6
|
||||||
|
| 1.7
|
||||||
|
| 1.8
|
||||||
|
| 1.9
|
||||||
|
| 2.0;
|
||||||
|
export type Messages = Array<ChatCompletion | ImageUrl>;
|
102
src/utils.ts
Normal file
102
src/utils.ts
Normal file
|
@ -0,0 +1,102 @@
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { Messages } from "./types";
|
||||||
|
|
||||||
|
export function checkFile(
|
||||||
|
file: string,
|
||||||
|
encoding: fs.EncodingOption,
|
||||||
|
defaultContent: string,
|
||||||
|
): Messages {
|
||||||
|
/**
|
||||||
|
* Checks if a given JSON file exists and contains valid JSON from a previous message history.
|
||||||
|
*
|
||||||
|
* @param file - The file to check.
|
||||||
|
* @param encoding - The text encoding the given file uses.
|
||||||
|
* @param defaultContent - The default system message to use if no JSON file was found, or the JSON file does not contain valid JSON.
|
||||||
|
*
|
||||||
|
* @returns A list of messages from the given JSON file, or a starter list with just the system messsage.
|
||||||
|
*/
|
||||||
|
let final: Messages;
|
||||||
|
const generic: Messages = [
|
||||||
|
{
|
||||||
|
role: "system",
|
||||||
|
content: defaultContent,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
if (fs.existsSync(file)) {
|
||||||
|
const data = fs.readFileSync(file, encoding);
|
||||||
|
|
||||||
|
final =
|
||||||
|
data.toString().trim() === ""
|
||||||
|
? generic
|
||||||
|
: // @ts-ignore
|
||||||
|
JSON.parse(data);
|
||||||
|
} else {
|
||||||
|
fs.createWriteStream(file);
|
||||||
|
final = generic;
|
||||||
|
}
|
||||||
|
|
||||||
|
return final;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserInfo(host: string, id: string) {
|
||||||
|
/**
|
||||||
|
* Returns various info about a user given a host and server ID.
|
||||||
|
*
|
||||||
|
* @param host - The address of the Tailchat server.
|
||||||
|
* @param id - The user ID to check.
|
||||||
|
*
|
||||||
|
* @returns An object containing all the user data recieved from the server.
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
const reply = await fetch(`${host}/api/user/getUserInfo`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId: id,
|
||||||
|
}),
|
||||||
|
}).then((response) => {
|
||||||
|
return response.json();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (reply.code !== 200) {
|
||||||
|
console.log(reply.data);
|
||||||
|
throw new Error("Response was not valid.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.data;
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUsername(host: string, id: string) {
|
||||||
|
/**
|
||||||
|
* Gets the username of a given user.
|
||||||
|
*
|
||||||
|
* @param host - The address of the Tailchat server.
|
||||||
|
* @param id - The user ID to check.
|
||||||
|
*
|
||||||
|
* @returns The username associated with the given user ID.
|
||||||
|
*/
|
||||||
|
const reply = await getUserInfo(host, id);
|
||||||
|
|
||||||
|
return reply.nickname;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function isUserBot(host: string, id: string) {
|
||||||
|
/**
|
||||||
|
* Returns if the given user is a bot.
|
||||||
|
*
|
||||||
|
* @param host - The address of the Tailchat server.
|
||||||
|
* @param id - The user ID to check.
|
||||||
|
*
|
||||||
|
* @returns true if the user ID is associated with a bot, false if not.
|
||||||
|
*/
|
||||||
|
const reply = await getUserInfo(host, id);
|
||||||
|
|
||||||
|
return reply.type === "openapiBot";
|
||||||
|
}
|
109
tsconfig.json
Normal file
109
tsconfig.json
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
|
|
||||||
|
/* Projects */
|
||||||
|
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||||
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
|
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||||
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||||
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
|
/* Language and Environment */
|
||||||
|
"target": "es2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
|
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||||
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||||
|
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||||
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
|
||||||
|
/* Modules */
|
||||||
|
"module": "commonjs", /* Specify what module code is generated. */
|
||||||
|
"rootDir": "./src", /* Specify the root folder within your source files. */
|
||||||
|
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
|
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||||
|
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||||
|
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||||
|
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||||
|
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
|
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||||
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
|
/* JavaScript Support */
|
||||||
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
|
||||||
|
/* Emit */
|
||||||
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
|
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
|
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||||
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
|
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||||
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
|
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||||
|
|
||||||
|
/* Interop Constraints */
|
||||||
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
|
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
|
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||||
|
|
||||||
|
/* Type Checking */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
|
||||||
|
/* Completeness */
|
||||||
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue