This commit is contained in:
vorotamoroz 2023-03-15 17:14:42 +09:00
commit 95fc8656d8
15 changed files with 4377 additions and 0 deletions

10
.editorconfig Normal file
View file

@ -0,0 +1,10 @@
# top-most EditorConfig file
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 4
tab_width = 4

3
.eslintignore Normal file
View file

@ -0,0 +1,3 @@
node_modules/
main.js

30
.eslintrc Normal file
View file

@ -0,0 +1,30 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"env": {
"node": true
},
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"args": "none"
}
],
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off"
}
}

22
.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
# vscode
.vscode
# Intellij
*.iml
.idea
# npm
node_modules
# Don't include the compiled main.js file in the repo.
# They should be uploaded to GitHub releases instead.
main.js
# Exclude sourcemaps
*.map
# obsidian
data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store

1
.npmrc Normal file
View file

@ -0,0 +1 @@
tag-version-prefix=""

25
README.md Normal file
View file

@ -0,0 +1,25 @@
# Ring a secretary
Yet another ChatGPT powered assistant in Obsidian.
![screenshot](https://user-images.githubusercontent.com/45774780/225245960-09d5fd27-cd20-4471-adf6-c098d331f238.gif)
Note: We need the [API key of ChatGPT](https://platform.openai.com/account/api-keys) to use this plug-in.
## How to install
1. Install [Beta Reviewers Auto-update Tester](https://github.com/TfTHacker/obsidian42-brat)
2. Copy this repo's URL ([https://github.com/vrtmrz/ring-a-secretary](https://github.com/vrtmrz/ring-a-secretary))
3. Open command pallet, select `BRAT: Add a beta plugin for testing`
4. Paste copied URL into the opened dialogue.
5. Press `Add Plugin` button.
## How to use
1. choose `New dialogue` in the command-palette. Therefore, the dialogue area appears there.
2. That is all. Now, it is time to chat!
## Memo
- The dialogue is saved as a code block. We can continue the conversation anytime we want.
- Also, they are searchable.

50
esbuild.config.mjs Normal file
View file

@ -0,0 +1,50 @@
import esbuild from "esbuild";
import process from "process";
import builtins from "builtin-modules";
const banner =
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = (process.argv[2] === "production");
const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins],
format: "cjs",
target: "es2018",
logLevel: "info",
platform: "browser",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: "main.js",
});
if (prod) {
await context.rebuild();
process.exit(0);
} else {
await context.watch();
}

216
main.ts Normal file
View file

@ -0,0 +1,216 @@
import { App, Editor, MarkdownRenderer, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, TFile } from 'obsidian';
import { Configuration, OpenAIApi } from "openai"
import axios from "axios";
interface RingASecretarySettings {
token: string;
defaultSystem: string;
}
const DEFAULT_SETTINGS: RingASecretarySettings = {
token: "",
defaultSystem: "",
}
const roleSystem = "**SYSTEM**";
const roleUser = "**USER**";
const roleAssistant = "**ASSISTANT**";
type DIALOGUE_ROLE = "**SYSTEM**" | "**USER**" | "**ASSISTANT**";
type API_ROLE = "system" | "user" | "assistant";
const MarkToRole = {
"**SYSTEM**": "system",
"**USER**": "user",
"**ASSISTANT**": "assistant",
} as Record<DIALOGUE_ROLE, API_ROLE>;
const WAIT_MARK = " WAITING FOR RESPONSE...";
export default class RingASecretaryPlugin extends Plugin {
settings: RingASecretarySettings;
configuration: Configuration;
processingFile?: TFile;
async askToAI(dialogue: string) {
const messages = [] as { role: "system" | "user" | "assistant", content: string }[];
let currentRole = "user" as "user" | "system" | "assistant";
let buffer = "";
const dialogLines = dialogue.split("\n");
for (const line of dialogLines) {
let lineBuf = line.trim();
if (lineBuf.startsWith("#")) continue;
let newRole = "" as "" | API_ROLE;
for (const [dialogueRole, APIRole] of Object.entries(MarkToRole)) {
if (lineBuf.startsWith(dialogueRole)) {
newRole = APIRole;
lineBuf = lineBuf.substring(dialogueRole.length + 1);
}
}
if (newRole != "" && buffer.trim() != "") {
messages.push({ role: currentRole, content: buffer.trim() });
currentRole = newRole;
buffer = "";
}
buffer += lineBuf + "\n";
}
if (buffer != "") {
messages.push({ role: currentRole, content: buffer });
}
const openai = new OpenAIApi(this.configuration);
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo-0301",
messages
// temperature: 0,
// max_tokens: 7,
});
const responseContent = response.data.choices[0].message?.content;
// const responseRole = response.data.choices[0].message?.role;
this.writeResponseToFile(responseContent ?? "");
}
async writeResponseToFile(response: string) {
if (!this.processingFile) return;
const file = this.processingFile;
await app.vault.process(file, (data) => {
return data.replace(WAIT_MARK, response);
});
app.vault.trigger("modify", file);
this.processingFile = undefined;
}
async onload() {
await this.loadSettings();
axios.defaults.adapter = "http";
this.configuration = new Configuration({ apiKey: this.settings.token });
this.registerMarkdownCodeBlockProcessor("aichat", (source, el, ctx) => {
const sourcePath = ctx.sourcePath;
const fx = el.createDiv({ text: "", cls: ["obsidian-fx"] });
MarkdownRenderer.renderMarkdown(source, fx, sourcePath, this)
const ops = el.createDiv({ text: "", cls: ["obsidian-fx-buttons"] });
const span = ops.createSpan({ text: "USER:" });
const input = ops.createEl("textarea");
const submit = ops.createEl("button", { text: "🤵" });
const secInfo = ctx.getSectionInfo(el);
ops.appendChild(span);
ops.appendChild(input)
ops.appendChild(submit);
fx.appendChild(ops)
el.replaceWith(fx);
// ctx.
const c = new AbortController();
const submitFunc = async () => {
if (source.contains(WAIT_MARK)) {
new Notice("Some question is already in progress...", 5000)//TODO:MESSAGE
return
}
const f = app.vault.getAbstractFileByPath(sourcePath);
if (!f) {
new Notice("Could not edit the file", 3000);
return;
}
if (!(f instanceof TFile)) {
new Notice("Could not edit the file", 3000);
return;
}
const dataMain = source;
const text = input.value;
//TODO:ESCAPE MARKDOWN?
const newBody = `${dataMain}\n${roleUser}:${text} \n${roleAssistant}: ${WAIT_MARK}`;
await app.vault.process(f, (data) => {
const dataList = data.split("\n");
const dataBefore = dataList.slice(0, (secInfo?.lineStart ?? 0) + 1);
const dataAfter = dataList.slice(secInfo?.lineEnd)
return dataBefore.join("\n") + `\n${newBody}\n` + dataAfter.join("\n");
});
this.processingFile = f;
setTimeout(() => {
this.askToAI(newBody).catch(err => {
this.writeResponseToFile("Something has been occurred (PLUGIN)")
});
}, 20);
app.vault.trigger("modify", f);
}
submit.addEventListener("click", submitFunc, { signal: c.signal });
input.addEventListener("keydown", e => {
console.dir(e);
if (e.key == "Enter" && (e.shiftKey) && !e.isComposing) {
e.preventDefault();
submitFunc();
input.value = "";
}
}, { signal: c.signal, capture: true })
});
this.addCommand({
id: 'obs-chat-new-dialogue',
name: 'New dialogue',
editorCallback: async (editor: Editor, view: MarkdownView) => {
editor.replaceSelection(
`${"```aichat"}
${this.settings.defaultSystem ? `${roleSystem}:${this.settings.defaultSystem}` : `#${roleSystem}:`}
${"```"}
`
)
}
});
this.addSettingTab(new RingASecretarySettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class RingASecretarySettingTab extends PluginSettingTab {
plugin: RingASecretaryPlugin;
constructor(app: App, plugin: RingASecretaryPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Settings for Ring a secretary' });
new Setting(containerEl)
.setName('Token')
.setDesc('The token of ChatGPT')
.addText(text => text
.setPlaceholder('sk-TrbCVkcuvcshu7b....')
.setValue(this.plugin.settings.token)
.onChange(async (value) => {
this.plugin.settings.token = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Initial prompt')
.setDesc('Initial prompt; i.e., instructions and prerequisites presented to the AI.')
.addText(text => text
.setPlaceholder('Behave as a British English speaker and answer my questions')
.setValue(this.plugin.settings.defaultSystem)
.onChange(async (value) => {
this.plugin.settings.defaultSystem = value;
await this.plugin.saveSettings();
}));
}
}

10
manifest.json Normal file
View file

@ -0,0 +1,10 @@
{
"id": "ring-a-secretary",
"name": "Ring a secretary",
"version": "0.0.1",
"minAppVersion": "0.15.0",
"description": "ChatGPT powered secretary",
"author": "vorotamoroz",
"authorUrl": "https://github.com/vrtmrz",
"isDesktopOnly": false
}

3908
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

27
package.json Normal file
View file

@ -0,0 +1,27 @@
{
"name": "ring-a-secretary",
"version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
"author": "vorotamoroz",
"license": "MIT",
"devDependencies": {
"@types/node": "^16.11.6",
"@typescript-eslint/eslint-plugin": "5.29.0",
"@typescript-eslint/parser": "5.29.0",
"axios": "^1.3.4",
"builtin-modules": "3.3.0",
"esbuild": "0.17.3",
"obsidian": "latest",
"openai": "^3.2.1",
"tslib": "2.4.0",
"typescript": "4.7.4"
},
"module": "node16"
}

33
styles.css Normal file
View file

@ -0,0 +1,33 @@
/*
This CSS file will be included with your plugin, and
available in the app when your plugin is enabled.
If your plugin does not need CSS, delete this file.
*/
.markdown-reading-view .obsidian-fx input,
.markdown-reading-view .obsidian-fx button {
display: none;
}
.obsidian-fx-buttons {
display: flex;
justify-content: center;
align-items: center;
margin: auto;
padding: 4px;
}
.obsidian-fx * {
margin: auto 2px;
}
.obsidian-fx textarea {
flex-grow: 1;
min-height: 3ex;
resize: vertical;
}
/*
.obsidian-fx textarea .obsidian-fx input,
.obsidian-fx button {} */

25
tsconfig.json Normal file
View file

@ -0,0 +1,25 @@
{
"compilerOptions": {
"baseUrl": ".",
"inlineSourceMap": true,
"inlineSources": true,
"module": "ESNext",
"target": "ES6",
"allowJs": true,
"noImplicitAny": true,
"moduleResolution": "node",
"importHelpers": true,
"isolatedModules": true,
"strictNullChecks": true,
"lib": [
"DOM",
"ES5",
"ES6",
"ES7"
],
"esModuleInterop": true
},
"include": [
"**/*.ts"
]
}

14
version-bump.mjs Normal file
View file

@ -0,0 +1,14 @@
import { readFileSync, writeFileSync } from "fs";
const targetVersion = process.env.npm_package_version;
// read minAppVersion from manifest.json and bump version to target version
let manifest = JSON.parse(readFileSync("manifest.json", "utf8"));
const { minAppVersion } = manifest;
manifest.version = targetVersion;
writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t"));
// update versions.json with target version and minAppVersion from manifest.json
let versions = JSON.parse(readFileSync("versions.json", "utf8"));
versions[targetVersion] = minAppVersion;
writeFileSync("versions.json", JSON.stringify(versions, null, "\t"));

3
versions.json Normal file
View file

@ -0,0 +1,3 @@
{
"1.0.0": "0.15.0"
}