├── .gitignore ├── LICENSE ├── README.md ├── favicon.ico └── frontend ├── env.local ├── index.html ├── package.json ├── public └── favicon.ico ├── serve.sh ├── src ├── app.js ├── assets │ └── logo.png ├── cmp │ ├── feed.vue │ ├── home.vue │ ├── modal-test-add.vue │ ├── modal-text-input.vue │ ├── modal.vue │ ├── prompt-entry.vue │ ├── prompt-list.vue │ ├── todo-entry.vue │ └── todo-list.vue ├── core │ ├── App.vue │ ├── Main.vue │ ├── app.js │ ├── cache.js │ ├── style.scss │ └── web-router.js ├── data │ ├── chains.js │ ├── message-handler.json │ ├── stream.js │ └── user-request.json ├── lib │ ├── ai-job.js │ ├── db.js │ ├── job-queue.js │ ├── prompt-chain.js │ ├── prompt-entry.js │ ├── streamer.js │ └── tree-store.js └── main.js └── vite.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Always on AI Assistant Demo 2 | 3 | This is an early demo of some of the possibilities of an always-on AI assistant. This is only 4 | scratching the surface to explore what an open source always-on assistant can/should do. 5 | 6 | # New Repo: Nucleo AI! 7 | This is now a full app, available here: 8 | https://github.com/AndrewVeee/nucleo-ai 9 | 10 | # Demo Video 11 | 12 | https://github.com/AndrewVeee/assistant-demo/assets/153542699/f7c4f149-b3e5-474c-925f-b570b941b824 13 | 14 | # Try It Out 15 | 16 | ## Requirements: 17 | 18 | The only requirement is an OpenAI-compatible API (through oobabooga, llama.cpp, etc). 19 | 20 | ## Usage: 21 | 22 | - Download the zip file from the releases page: https://github.com/AndrewVeee/assistant-demo/releases/tag/demo-0.1 23 | - Unzip and open the `index.html` file in your browser. 24 | - Click the "API" button at the top to set your API url (eg http://localhost:8000). 25 | - If you use an API that requires a key (like OpenAI), click Set Key to paste in the key. 26 | 27 | Note: This has been tested with `openhermes-2.5-mistral-7b.Q6_K.gguf` and prompt chains may require tweaking for other models. 28 | 29 | You should be ready to go. 30 | 31 | ## What to try: 32 | 33 | Keep in mind this is a tech demo, so the stream entries aren't saved when you close the tab. 34 | 35 | - **"Live" Feed:** In the Stream tab, you can click "Add Entry" at the top. You can paste in content, or use one of the examples at the top. When the content is filled, click Add. (Keep it kind of short - it doesn't check context length!) 36 | - **AI Feed:** Once you've added an entry, click "Run Message Handler" under the new entry and watch the AI categorize, summarize, extract invoice info from bills, and suggest responses to personal messages! 37 | - **Chat** with the AI in the Log section on the right. There's some fake "web data" about the weather, sports, politics, and AI news if you ask it ;-) 38 | - Note: This does not include chat history/context, it is only a demo of using a prompt chain to reply. 39 | - If you ask it to perform a task, it should make a bullet list that includes "assistants" it should use and instructions for each. (Example: Check the weather and add a to do list item of what to wear today.) 40 | - **Give it a Personality:** Click the "Personality" button at the top right to write a short sentence about how the AI should act and response to you. 41 | 42 | ## To Do list: 43 | 44 | This is an older UI to play with the idea of an AI breaking down your tasks and helping you complete them. Don't expect much here, but I think having access to a to do list would be crucial to a useful AI assistant. 45 | 46 | ## Prompts: 47 | 48 | I'm pretty sure this is too confusing to actually use, but you can get a sense for the structure of prompt chains, or view/edit the prompts. This is also not saved when the browser is closed. 49 | 50 | # What Next? 51 | 52 | I'm excited about the possibilities and hope it leads to a cool project (or even interoperable projects!) to create an always-on assistant. I'm personally thinking about: 53 | 54 | - A server to build on these ideas with a feed/stream of data. 55 | - Prompt chains that can be flexible in allowing code and user customization, triggered by feeds, calendars, UI interaction (chat, to do, stream), etc. 56 | - Prompts that work with the smallest models, so even the tiniest LLMs and cpu-only computers can run a full local assistant. 57 | - A fluid context system that can use chat history, stream data, and project/thought context to give well-rounded awareness. 58 | - Pluggable tools to give access to different systems, like email, texts, and social media streams, and tools like contact lists and calendars. 59 | - Function calling via prompt chains so small models can handle it. 60 | -------------------------------------------------------------------------------- /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewVeee/assistant-demo/1a40603981331dd84f20f83e23d26f969e0f1319/favicon.ico -------------------------------------------------------------------------------- /frontend/env.local: -------------------------------------------------------------------------------- 1 | export APP_PORT=4739 2 | -------------------------------------------------------------------------------- /frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | AI Assistant 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue2-vite", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "dev": "vite", 6 | "build": "vite build", 7 | "serve": "vite preview" 8 | }, 9 | "dependencies": { 10 | "idb": "^8.0.0", 11 | "sass": "^1.69.5", 12 | "vue": "^2.6.12", 13 | "vue-template-compiler": "^2.7.14" 14 | }, 15 | "devDependencies": { 16 | "vite": "^2.0.5", 17 | "vite-plugin-singlefile": "^0.13.5", 18 | "vite-plugin-vue2": "^2.0.1" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewVeee/assistant-demo/1a40603981331dd84f20f83e23d26f969e0f1319/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/serve.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | source env.local 4 | 5 | yarn vite serve --host 127.0.0.1 --port ${APP_PORT} $@ 6 | -------------------------------------------------------------------------------- /frontend/src/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | Entry point of app, so you can: 3 | 4 | - Initialize API 5 | - Initialize routes 6 | - Customize "app" to your needs 7 | 8 | After this, the Main.vue component will load. 9 | */ 10 | 11 | //import MyCmp from './cmp/my-cmp.vue' 12 | import Home from './cmp/home.vue' 13 | import * as LineStream from './lib/streamer.js' 14 | import * as Jobs from './lib/job-queue.js' 15 | import * as DB from './lib/db.js' 16 | import * as Prompt from './lib/prompt-entry.js' 17 | import {PromptChain} from './lib/prompt-chain.js' 18 | import {TreeStore} from './lib/tree-store.js' 19 | 20 | export function init(app, vue) { 21 | console.log("Initializing App!"); 22 | app.debug = false; 23 | app.store_prefix = 'bai_'; 24 | app.no_login = true; 25 | app.api_base = app.load_local('api_base', 'http://127.0.0.1:8080'); 26 | app.api_key = app.load_local('api_key', 'no_key'); 27 | app.api_model = app.load_local('api_model', 'gpt-3.5-turbo'); 28 | app.ai_tone = app.load_local('ai_tone', 'Reply as a friendly, intelligent, concise assistant.'); 29 | app.api = {}; 30 | app.chain_map = {}; 31 | app.chains = []; 32 | app.add_chain = (name,data) => { 33 | let chain = app.chainer.import_chain(app, data); 34 | chain.name = name; 35 | app.chain_map[name] = chain; 36 | app.chains.unshift(chain); 37 | }; 38 | app.stream = LineStream; 39 | app.jobs = Jobs; 40 | app.ai_log = []; 41 | app.prompter = Prompt; 42 | app.feed = []; 43 | app.chainer = PromptChain; 44 | app.modals = []; 45 | app.modal_id = 0; 46 | app.open_modal = (opts, evts) => { 47 | app.modal_id += 1; 48 | app.modals.unshift({modal_id: 1, opts: opts, evts: evts}); 49 | }; 50 | app.close_modal = () => { app.modals.splice(0, 1); }; 51 | app.ai_queue = new Jobs.JobQueue({debug: true}); 52 | app.ai_queue.run(); 53 | app.db = new DB.DB('busyai', 1, [ 54 | {name: 'store', attrs: ['id', 'type', 'pid', 'name', 'text', 'meta']}, 55 | {name: 'prompt', attrs: ['id', 'pid', 'name', 'prompt', 'meta']}, 56 | {name: 'content_ex', attrs: ['id', 'pid', 'type', 'name', 'content', 'meta']}, 57 | ]); 58 | app.todo_list = new TreeStore({pid: 'pid', id: 'id'}); 59 | app.user = {logged_in: true, alias: 'Admin'}; 60 | 61 | init.vue.component('Home', Home); 62 | 63 | }; 64 | -------------------------------------------------------------------------------- /frontend/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewVeee/assistant-demo/1a40603981331dd84f20f83e23d26f969e0f1319/frontend/src/assets/logo.png -------------------------------------------------------------------------------- /frontend/src/cmp/feed.vue: -------------------------------------------------------------------------------- 1 | 67 | 68 | 125 | -------------------------------------------------------------------------------- /frontend/src/cmp/home.vue: -------------------------------------------------------------------------------- 1 | 143 | 144 | 241 | -------------------------------------------------------------------------------- /frontend/src/cmp/modal-test-add.vue: -------------------------------------------------------------------------------- 1 | 33 | 34 | 64 | -------------------------------------------------------------------------------- /frontend/src/cmp/modal-text-input.vue: -------------------------------------------------------------------------------- 1 | 29 | 30 | 41 | -------------------------------------------------------------------------------- /frontend/src/cmp/modal.vue: -------------------------------------------------------------------------------- 1 | 19 | 20 | 33 | -------------------------------------------------------------------------------- /frontend/src/cmp/prompt-entry.vue: -------------------------------------------------------------------------------- 1 | 63 | 64 | 125 | -------------------------------------------------------------------------------- /frontend/src/cmp/prompt-list.vue: -------------------------------------------------------------------------------- 1 | 70 | 71 | 117 | -------------------------------------------------------------------------------- /frontend/src/cmp/todo-entry.vue: -------------------------------------------------------------------------------- 1 | 105 | 106 | 124 | -------------------------------------------------------------------------------- /frontend/src/cmp/todo-list.vue: -------------------------------------------------------------------------------- 1 | 41 | 42 | 65 | -------------------------------------------------------------------------------- /frontend/src/core/App.vue: -------------------------------------------------------------------------------- 1 | 24 | 25 | 28 | 29 | -------------------------------------------------------------------------------- /frontend/src/core/Main.vue: -------------------------------------------------------------------------------- 1 | 32 | 33 | 71 | -------------------------------------------------------------------------------- /frontend/src/core/app.js: -------------------------------------------------------------------------------- 1 | import WebRouter from './web-router.js'; 2 | import AppCache from './cache.js'; 3 | 4 | export class App { 5 | 6 | constructor(app_init) { 7 | this.ready = new Promise((res,rej) => { this.ready_res = res }); 8 | this.user = {logged_in: false}; 9 | this.store_prefix = 'app_'; 10 | this.page = null; 11 | this.api = null; 12 | this.cache = AppCache; 13 | this.router = new WebRouter(); 14 | 15 | // Initialize rest of app. 16 | if (app_init && app_init.init) app_init.init(this, app_init.init.vue); 17 | 18 | this.router.init(); 19 | this.checkLogin(); 20 | this.ready_res(); 21 | } 22 | 23 | open(path) { 24 | return this.router.open(path); 25 | } 26 | save_local(attr, value) { 27 | localStorage.setItem(this.store_prefix + attr, value); 28 | } 29 | rm_local(attr) { 30 | localStorage.removeItem(this.store_prefix + attr); 31 | } 32 | load_local(attr, def) { 33 | return localStorage.getItem(this.store_prefix + attr) || def; 34 | } 35 | openPage(cmp, opts) { 36 | this.page = {cmp: cmp, opts: opts || {}}; 37 | } 38 | closePage() { 39 | this.page = null; 40 | } 41 | 42 | auto_refresh(opts) { 43 | if (!opts) opts = {} 44 | if (this.refresh_timer) return false; 45 | this.refresh_timer = setInterval(() => { 46 | if (this.user.logged_in) this.checkLogin({renew: true}); 47 | }, (opts.minutes || 10) * 60 * 1000); 48 | } 49 | logout() { 50 | console.log("Logging out"); 51 | this.rm_local('auth'); 52 | this.user = {logged_in: false}; 53 | this.page = null; 54 | } 55 | setAuthToken(token) { 56 | if (!token) return false; 57 | this.api._include.auth = token; 58 | this.save_local('auth', token); 59 | return true; 60 | } 61 | checkLogin(opts) { 62 | if (this.no_login) { 63 | this.user = {logged_in: true, alias: 'Admin'}; 64 | return Promise.resolve(this.user); 65 | } 66 | if (!this.api) return Promise.reject({error: 'No api'}); 67 | opts = opts || {}; 68 | this.api._include.auth = this.load_local('auth'); 69 | return this.api.User.status(opts.renew).then((r) => { 70 | this.user = r; 71 | if (opts.renew) { 72 | this.setAuthToken(r.data.token); 73 | } 74 | }); 75 | } 76 | doLogin(email, pass) { 77 | return this.api.User.login(email, pass).then((r) => { 78 | this.user = r; 79 | this.setAuthToken(r.data.token); 80 | this.onLogin(); 81 | return r; 82 | }); 83 | } 84 | onLogin() { 85 | console.log("Login", this.user); 86 | } 87 | 88 | list_jobs() { 89 | this.jobs = []; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /frontend/src/core/cache.js: -------------------------------------------------------------------------------- 1 | 2 | export default class AppCache { 3 | 4 | constructor(opts) { 5 | if (!opts) opts = {}; 6 | this.items = {}; 7 | this.max = opts.max; 8 | this.opts = opts; 9 | } 10 | 11 | add_all(list, id_field) { 12 | for (let ent of list) this.add(ent[id_field], ent); 13 | } 14 | add(id, data) { 15 | // TODO: If self.max, check for removal. 16 | this.items[id] = data; 17 | } 18 | 19 | lookup(id) { 20 | if (!this.opts.lookup) return Promise.reject({error: 'No lookup function'}); 21 | return this.opts.lookup(id); 22 | } 23 | get(id) { 24 | return new Promise((res,rej) => { 25 | if (this.items[id]) { 26 | res(this.items[id]); 27 | return; 28 | } else { 29 | this.lookup(id).then((r) => { 30 | this.add(id, r); 31 | res(r); 32 | }).catch((err) => { rej(err) }); 33 | } 34 | }); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /frontend/src/core/style.scss: -------------------------------------------------------------------------------- 1 | @use "sass:list"; 2 | 3 | :root { 4 | font-family: Inter, Avenir, Helvetica, Arial, sans-serif; 5 | 6 | color-scheme: light dark; 7 | color: rgba(255, 255, 255, 0.87); 8 | background-color: #242424; 9 | 10 | font-synthesis: none; 11 | text-rendering: optimizeLegibility; 12 | -webkit-font-smoothing: antialiased; 13 | -moz-osx-font-smoothing: grayscale; 14 | -webkit-text-size-adjust: 100%; 15 | } 16 | 17 | body { 18 | height: 100vh; 19 | } 20 | body { 21 | margin: 0; 22 | } 23 | 24 | $bg-main: #fff; 25 | $bg-sec: #f0f0f0; 26 | $sizes: (0px, 0.5em, 1em, 1.5em, 2.5em, 4em); 27 | $primary-color: #646cff; 28 | $primary-color: #206cff; 29 | $border-color: $primary-color; 30 | $primary-alt: #fff; 31 | $border-width: 1px; 32 | $radius-lg: 20px; 33 | $radius: 7px; 34 | $radius-sm: 3px; 35 | $shadow: 2px 2px 2px 1px #0001; 36 | 37 | :root { 38 | --bg-main: $bg-main; 39 | --bg-sec: $bg-sec; 40 | --primary-color: $promary-color; 41 | --primary-alt: $primary-alt; 42 | --radius: $radius; 43 | --shadow: $shadow; 44 | } 45 | .clickable { 46 | cursor: pointer; 47 | } 48 | .form-control { 49 | padding: list.nth($sizes, 2); 50 | border-radius: $radius-sm; 51 | border: $border-width solid #{$border-color}40; 52 | box-shadow: $shadow; 53 | } 54 | .form-control:focus{ 55 | outline: none; 56 | border: $border-width solid #{$border-color}; 57 | } 58 | 59 | .flex-x, .flex-horiz { 60 | display: flex; 61 | flex-direction: row; 62 | align-items: center; 63 | } 64 | .flex-y, .flex-vert { 65 | display: flex; 66 | flex-direction: column; 67 | } 68 | .flex-space, .flex-grow { 69 | flex-grow: 1; 70 | } 71 | .flex-scroll-y { 72 | flex-grow: 1; 73 | overflow-y: auto; 74 | height: 0; 75 | } 76 | .flex-stretch { 77 | align-items: stretch; 78 | } 79 | a { 80 | font-weight: 500; 81 | color: #646cff; 82 | text-decoration: inherit; 83 | } 84 | a:hover { 85 | color: #535bf2; 86 | } 87 | 88 | a { 89 | font-weight: 500; 90 | color: #646cff; 91 | text-decoration: inherit; 92 | } 93 | a:hover { 94 | color: #535bf2; 95 | } 96 | 97 | h1 { 98 | font-size: 3.2em; 99 | line-height: 1.1; 100 | } 101 | 102 | .highlight { 103 | background-color: $primary-color; 104 | color: $primary-alt; 105 | } 106 | .bg-light { 107 | background-color: var(--bg-def); 108 | } 109 | .bg-sec { 110 | background-color: $bg-sec; 111 | } 112 | .card { 113 | padding: list.nth($sizes, 2); 114 | border-radius: $radius-lg; 115 | box-shadow: 1px 5px 20px 0px #0001; 116 | background-color: $bg-main; 117 | } 118 | .p-rel { position: relative; } 119 | .p-abs { position: absolute; } 120 | .w-100 { width: 100%; } 121 | .btn { 122 | border-radius: $radius; 123 | border: 0 solid #{$border-color}80; 124 | background-color: #{$primary-color}08; 125 | box-shadow: $shadow; 126 | padding: list.nth($sizes, 2) list.nth($sizes, 3); 127 | cursor: pointer; 128 | transition: border-color 0.25s; 129 | } 130 | .btn:hover { 131 | //border-color: #646cff; 132 | background-color: #{$primary-color}30; 133 | } 134 | .btn:focus, 135 | .btn:focus-visible { 136 | outline: 1px auto #{$border-color}50; 137 | } 138 | 139 | .btn-tab { 140 | border-width: 0; 141 | border-radius: #{$radius} #{$radius} #{$radius-sm} #{$radius-sm}; 142 | border-bottom: 3px solid #{$border-color}40; 143 | } 144 | .btn-tab-sel { 145 | border-bottom: 3px solid #{$border-color}ff; 146 | } 147 | .btn-pri { 148 | background: $border-color; 149 | color: #{$primary-alt}; 150 | } 151 | .btn-pri:hover { 152 | background: #{$border-color}c0; 153 | color: #{$primary-alt}; 154 | } 155 | .btn-ol { 156 | border-width: 2px; 157 | } 158 | .btn-lt { 159 | border-width: 0; 160 | } 161 | .btn-sm { 162 | //padding: 4px 7px; 163 | padding: calc(list.nth($sizes, 2) / 1.5) calc(list.nth($sizes, 3) / 1.5); //0.6em 1.2em; 164 | font-size: 80%; 165 | } 166 | .btn-md { 167 | padding: 6px 10px; 168 | } 169 | 170 | .border { 171 | border-color: #{$border-color}; 172 | border-width: 2px; 173 | border-radius: 2px; 174 | border-style: solid; 175 | } 176 | @media (prefers-color-scheme: light) { 177 | :root { 178 | color: #213547; 179 | background-color: #ffffff; 180 | } 181 | a:hover { 182 | color: #747bff; 183 | } 184 | button { 185 | background-color: #f9f9f9; 186 | } 187 | } 188 | 189 | ::-webkit-scrollbar { 190 | cursor: pointer; 191 | height: 11px; 192 | width: 11px; 193 | } 194 | ::-webkit-scrollbar-thumb { 195 | background: #{$primary-color}; 196 | border-radius: 18px; 197 | } 198 | ::-webkit-scrollbar-track { 199 | background: #{$primary-color}40; 200 | border-radius: 7px; 201 | } 202 | 203 | .lds-dual-ring { 204 | display: inline-block; 205 | width: 20px; 206 | height: 20px; 207 | } 208 | .lds-dual-ring:after { 209 | content: " "; 210 | display: block; 211 | width: 20px; 212 | height: 20px; 213 | margin: 1px; 214 | border-radius: 50%; 215 | border: 5px solid #fff; 216 | border-color: #fff transparent #fff transparent; 217 | animation: lds-dual-ring 1.2s linear infinite; 218 | } 219 | @keyframes lds-dual-ring { 220 | 0% { 221 | transform: rotate(0deg); 222 | } 223 | 100% { 224 | transform: rotate(360deg); 225 | } 226 | } 227 | 228 | @for $i from 0 through 5 { 229 | .p-#{$i} { padding: list.nth($sizes, $i+1) } 230 | .m-#{$i} { margin: list.nth($sizes, $i+1) } 231 | } 232 | @for $i from 0 through 5 { 233 | .py-#{$i} { padding-top: list.nth($sizes, $i+1); padding-bottom: list.nth($sizes, $i+1) } 234 | .px-#{$i} { padding-left: list.nth($sizes, $i+1); padding-right: list.nth($sizes, $i+1) } 235 | .my-#{$i} { margin-top: list.nth($sizes, $i+1); margin-bottom: list.nth($sizes, $i+1) } 236 | .mx-#{$i} { margin-left: list.nth($sizes, $i+1); margin-right: list.nth($sizes, $i+1) } 237 | } 238 | @for $i from 0 through 5 { 239 | .pt-#{$i} { padding-top: list.nth($sizes, $i+1) } 240 | .pl-#{$i} { padding-left: list.nth($sizes, $i+1) } 241 | .pb-#{$i} { padding-bottom: list.nth($sizes, $i+1) } 242 | .pr-#{$i} { padding-right: list.nth($sizes, $i+1) } 243 | .mt-#{$i} { margin-top: list.nth($sizes, $i+1) } 244 | .ml-#{$i} { margin-left: list.nth($sizes, $i+1) } 245 | .mb-#{$i} { margin-bottom: list.nth($sizes, $i+1) } 246 | .mr-#{$i} { margin-right: list.nth($sizes, $i+1) } 247 | } 248 | 249 | .b-0 { 250 | border: 0px; 251 | } 252 | .b-1 { 253 | border: 1px solid $border-color; 254 | border-radius: $radius-sm; 255 | } 256 | .b-2 { 257 | border: 2px solid $border-color; 258 | border-radius: $radius-sm; 259 | } 260 | 261 | .round-sm { border-radius: 3px; } 262 | .round { border-radius: 8px; } 263 | .round-lg { border-radius: 12px; } 264 | .round-xl { border-radius: 20px; } 265 | .text-center { 266 | text-align: center; 267 | } 268 | .text-sm { font-size: 90%; } 269 | .text-xs { font-size: 75%; } 270 | .text-lg { font-size: 110%; } 271 | .text-xl { font-size: 125%; } 272 | 273 | -------------------------------------------------------------------------------- /frontend/src/core/web-router.js: -------------------------------------------------------------------------------- 1 | export default class WebRouter { 2 | 3 | constructor() { 4 | this.routes = []; 5 | this.counter = 0; 6 | this.default_route = null; 7 | this.from = WebRouter.FROM_HASH; 8 | this.current = {cmp: null}; 9 | this.onRoute = null; 10 | if (typeof(window) != 'undefined') { 11 | window.addEventListener('popstate', (evt) => { 12 | this.onPopState(evt); 13 | }); 14 | } 15 | } 16 | 17 | init() { 18 | this.open(null, null, {no_push: true}); 19 | } 20 | onPopState(evt) { 21 | this.open(null, null, {no_push: true}); 22 | } 23 | open(path, params, opts) { 24 | if (!opts) opts = {}; 25 | if (path && this.from == WebRouter.FROM_HASH && !path.startsWith("#!")) { 26 | path = "#!" + path 27 | } 28 | let route = this.get_route(path, params); 29 | 30 | if (!route) return false; 31 | 32 | if (this.current.unload) { 33 | let res = this.current.unload(); 34 | if (!res) return false; 35 | } 36 | this.current = {route: route.route, cmp: route.route.opts.cmp, args: route.args, opts: opts}; 37 | this.counter += 1; 38 | if (this.onRoute) this.onRoute(this.current); 39 | if (!opts.no_push) { 40 | // TODO: Add URL params 41 | window.history.pushState({}, '', path); 42 | } 43 | return this.current; 44 | } 45 | get_route(path, params) { 46 | if (!path) { 47 | if (this.from == WebRouter.FROM_HASH) { 48 | path = document.location.hash.substring(2); 49 | let q = path.indexOf('?'), query = null; 50 | if (q) { 51 | query = path.substring(q+1); 52 | path = path.replace(/\?.*/, '') 53 | } 54 | params = new URLSearchParams(query); 55 | } else { 56 | path = document.location.pathname; 57 | params = document.location.search; 58 | } 59 | } else if (path.startsWith("#!")) { 60 | path = path.substring(2); 61 | } 62 | let parts = path.split("/").filter(pt => pt); 63 | for (let route of this.routes) { 64 | if (route.parts.length == parts.length) { 65 | let match = true, vals = {}; 66 | for (let i in parts) { 67 | let rpart = route.parts[i]; 68 | if (rpart.startsWith(':')) { 69 | vals[rpart.substring(1)] = parts[i]; 70 | } else if (rpart != parts[i]) { 71 | match = false; 72 | break; 73 | } 74 | } 75 | if (match) { 76 | return {route: route, cmp: route.opts.cmp, args: vals }; 77 | } 78 | } 79 | } 80 | return null; 81 | } 82 | 83 | add(route_str, opts) { 84 | if (!opts) opts = {}; 85 | let route = { 86 | path: route_str, 87 | parts: route_str.split("/").filter(pt => pt), 88 | opts: opts, 89 | }; 90 | this.routes.push(route); 91 | if (opts.default) this.default_route = route; 92 | 93 | } 94 | } 95 | 96 | WebRouter.FROM_LOCATION = 1; 97 | WebRouter.FROM_HASH = 2; 98 | -------------------------------------------------------------------------------- /frontend/src/data/chains.js: -------------------------------------------------------------------------------- 1 | export default [ 2 | 3 | '{"title":"User Request","prompts":[{"id":1,"log":"Start chain User Request","name":"prompt1","inputs":["message"],"outputs":[{"name":"result","store_response":true}],"prompt":"You are a smart categorization assistant.\n\nRequest:\n```\n{{message}}\n```\n\nShould we perform a web lookup or answer directly? Only reply with:\nAnswer Type: direct or lookup"},{"id":2,"log":"Replying directly","name":"prompt2","inputs":["message"],"outputs":[{"name":"result","store_response":true}],"prompt":"You are a helpful but assistant.\n\nRequest:\n```\n{{message}}\n```\n\nRespond to this request with a helpful, concise response."},{"id":3,"log":"Replying with lookup","name":"prompt3","inputs":["message"],"outputs":[{"name":"result","store_response":true}],"prompt":"You are a helpful assistant.\n\nYou have the following context available:\n```\nCurrent Date: Monday, 01/01/2024\nCurrent Weather: 78f\nSports News: Llamas beat GPTs 5-1\nPolitics: Mr. O. Hermes running for president this year\nTech: Local always-running AI assistants will be available this year!\n```\n\nMessage:\n```\n{{message}}\n```\n\nRespond to the message using the context above if it helps."}],"entry_points":[{"id":1,"opts":{"conditions":[],"map":{"message":"message"}},"entry_points":[{"id":2,"opts":{"conditions":[{"op":"exclude","name":"result","value":"lookup"}],"map":{"message":"message"}},"entry_points":[]},{"id":3,"opts":{"conditions":[{"op":"include","name":"result","value":"lookup"}],"map":{"message":"message"}},"entry_points":[]}]}]}', 4 | 5 | '{"title":"Message Handler","prompts":[{"id":1,"log":"Summarizing message","name":"prompt1","inputs":["message"],"outputs":[{"name":"summary","store_response":true}],"prompt":"You're a helpful bot that summarizes incoming messages.\n```\n{{message}}\n```\n\nMake sure to note if it's a bill, invoice, spam, ad, personal, automated email, or newsletter.\n\nWrite a one sentence summary from the perspective of the sender. Start with: This is a..."},{"id":2,"log":"Categorizing message","name":"prompt2","inputs":["summary"],"outputs":[{"name":"category","from_line":"category:","target":"msg_category"}],"prompt":"You're a helpful bot that categorizes incoming messages. Summary:\n```\n{{summary}}\n```\n\nCategorize this message as:\nbills: Bills, invoices, and other payments.\nautomated: Automated messages like social notifications.\nadvert: An advertisement.\nspam: Spam message.\npersonal: A personal message.\n\n Just reply with Category: "},{"id":3,"log":"Extracting invoice information","name":"prompt3","inputs":["invoice"],"outputs":[{"name":"invoice","store_response":true}],"prompt":"You're a helpful bot that extracts invoice information. Summary:\n```\n{{invoice}}\n```\n\nExtract as much information from the context above as you can: Due date, total cost, payment link, and service description if possible. Reply with each field and value on its own line."},{"id":4,"log":"Suggest replies","name":"prompt4","inputs":["message"],"outputs":[{"name":"result","store_response":true}],"prompt":"You are a helpful assistant.\n\nMessage:\n```\n{{message}}\n```\n\nWrite 4 options that the user might want to reply with."}],"entry_points":[{"id":1,"opts":{"conditions":[],"map":{"message":"message"}},"entry_points":[{"id":2,"opts":{"conditions":[],"map":{"summary":"message"}},"entry_points":[]},{"id":3,"opts":{"conditions":[{"op":"==","name":"msg_category","value":"bills"}],"map":{"invoice":"message"}},"entry_points":[]},{"id":4,"opts":{"conditions":[{"op":"==","name":"msg_category","value":"personal"}],"map":{"message":"message"}},"entry_points":[]}]}]}', 6 | 7 | 8 | ]; 9 | -------------------------------------------------------------------------------- /frontend/src/data/message-handler.json: -------------------------------------------------------------------------------- 1 | {"title":"Message Handler","prompts":[{"id":1,"log":"Summarizing message","name":"prompt1","inputs":["message"],"outputs":[{"name":"summary","event":"summary","parser":"full_response"}],"prompt":"You're a helpful bot that summarizes incoming messages.\n```\n{{message}}\n```\n\nExplain this message in one very short sentence. Make sure to note if it's a bill, invoice, spam, ad, personal, automated email, or newsletter in your explanation. {{ai_tone}}"},{"id":2,"log":"Categorizing message","name":"prompt2","inputs":["summary"],"outputs":[{"name":"msg_category","event":"categorize","parser":"from_line","parser_ex":"category:"}],"prompt":"You're a helpful bot that categorizes incoming messages. Summary:\n```\n{{summary}}\n```\n\nCategorize this message as:\nbills: Bills, invoices, and other payments from companies.\nautomated: Automated messages like social notifications and newsletters.\nad: An advertisement.\nspam: Spam message.\npersonal: A personal message.\n\n Just reply with Category: "},{"id":3,"log":"Extracting invoice information","name":"prompt3","inputs":["invoice"],"outputs":[{"name":"invoice","event":"summary:Invoice","parser":"full_response"}],"prompt":"You're a helpful bot that extracts invoice information. Summary:\n```\n{{invoice}}\n```\n\nExtract as much information from the context above as you can: Due date, total cost, payment link, and service description if possible. Reply with each field and value on its own line."},{"id":4,"log":"Suggest replies","name":"prompt4","inputs":["message"],"outputs":[{"name":"replies","event":"suggest:reply","parser":"full_response"}],"prompt":"You are a helpful assistant.\n\nMessage:\n```\n{{message}}\n```\n\nWrite 4 options that the user might want to reply with (include positive and negative responses). {{ai_tone}}"}],"entry_points":[{"id":1,"opts":{"conditions":[],"map":{"message":"message"}},"entry_points":[{"id":2,"opts":{"conditions":[],"map":{"summary":"message"}},"entry_points":[]},{"id":3,"opts":{"conditions":[{"op":"==","name":"msg_category","value":"bills"}],"map":{"invoice":"message"}},"entry_points":[]},{"id":4,"opts":{"conditions":[{"op":"==","name":"msg_category","value":"personal"}],"map":{"message":"message"}},"entry_points":[]}]}]} -------------------------------------------------------------------------------- /frontend/src/data/stream.js: -------------------------------------------------------------------------------- 1 | export default [ 2 | 3 | {type: 'email', title: 'Trip Plan', 4 | content: `Subject: Let's do Mexico! 5 | 6 | Dear Joel, 7 | 8 | Can you help plan a trip to Mexico in March? I'm thinking Cancun. 9 | 10 | Do you want to help plan the budget, places to stay, flight dates, or something else? 11 | 12 | - Jaden`}, 13 | 14 | 15 | {type: 'email', title: 'Work Project', 16 | content: `Subject: Task Update - "Build Moon Laser" Specifications 17 | 18 | Laser Team, 19 | 20 | A task has been updated in your dashboard. 21 | 22 | Safa has updated the specifications for the task "Build Moon Laser." You can find the latest version of the document in our shared drive under the folder named "Project Documents." 23 | 24 | TaskTracker (tm)`}, 25 | 26 | 27 | {type: 'email', title: 'Your Boxes', 28 | content: `Subject: Pick up your stuff! 29 | From: Mom 30 | 31 | Hey, we really need you to get your boxes out of the garage this weekend! We're doing spring cleaning this weekend and if it's not gone when we finish, they're going to the dump!`}, 32 | 33 | 34 | {type: 'email', title: 'Catch Up', 35 | content: `Subject: Great dinner! 36 | 37 | Hey Flynn, 38 | 39 | You asked me to send you a reminder that you owe me $37 for dinner the other night. Great catching up with you, let's do it again soon! 40 | 41 | - Mattie`}, 42 | 43 | {type: 'email', title: 'Car Registration', 44 | content: `Subject: Your Car Registration is due 45 | 46 | Subject: Vehicle Renewal Notice 47 | 48 | CLEMENTINE, 49 | Your vehicle registration expires soon. The fastest, easiest way to renew is online at dmv.ca.gov or at a DMV kiosk. 50 | 51 | Year | Make | VIN/HIN Last 5 digits | License/CF Plate # | Bill Amount | Renewal/Payment | Due Date | Smog Due 52 | 1927 | FORD | 65412| 1AIS321| $142 | 02/15/2024 | Yes 53 | 54 | Renew Today: http://www.dmv.ca.gov/portal/vehicle-registration/vehicle-registration-renewal/ 55 | Your mailing address on record is: 56 | 57 | Clementine Thomas 58 | 12345 Oak Hill Dr 59 | Llama, CA 23148 60 | The DMV will mail your new registration and sticker to this address. If this is not the correct address, please complete a change of address online 72 hours prior to renewing your vehicle registration.`}, 61 | 62 | {type: 'email', title: 'Reddit Reply', 63 | content: `Subject: u/mistral replied to your comment in r/LocalLLaMA 64 | 65 | Reddit Unsubscribe 66 | 67 | u/mistral replied to your comment in 68 | r/LocalLLaMA · 4d ago 69 | u/mistral · 1 votes 70 | You might be able to use a mistral quant or phi2 to power an always-on assistant. But...`}, 71 | 72 | {type: 'email', title: 'Hosting Notice', 73 | content: `Subject: [OverCharged] Billing Alert: Your Monthly Billable Usage Has Exceeded Your Threshold 74 | 75 | Billing Alert: Monthly usage exceeded threshold. 76 | Heads up: Your monthly billable usage of $40.12 has exceeded the $20.00 alert threshold set on your team. 77 | If you wish to adjust the threshold, or disable this notification, you may do so in your Team Settings. 78 | 79 | Happy coding, 80 | OverCharged - We bill, you pay!`}, 81 | 82 | 83 | {type: 'email', title: 'Stripe News', 84 | content: `Subject: Stripe Sessions is back for 2024 85 | 86 | Hello, 87 | 88 | 89 | Earlier this year, 3,000 of you – representing more than 1,500 companies and 90 countries – joined us in San Francisco for Stripe Sessions. In 2024, we're going even bigger. 90 | 91 | 92 | Join us from 23–25 April at Moscone West in San Francisco for our largest event ever, where you'll: 93 | 94 | Learn about major internet economy trends, including AI, automation and the future of payments 95 | Explore a packed agenda of keynotes, breakout sessions and demos 96 | Take part in hands-on training opportunities, and get practical insights for optimising your business 97 | Connect with a community of experts across industries`}, 98 | 99 | {type: 'email', title: 'Tax Ad', 100 | content: `Subject: Just for you, Ronnie: 25% off TurboTax 101 | 102 | Act fast: offer ends December 31 103 | Email exclusive 104 | Save up to $54 105 | Get 25% off any TurboTax DIY or Live Assisted 106 | federal product.* 107 | Just sign in to activate your offer, then finish 108 | and file when you're ready.`}, 109 | 110 | {type: 'email', title: 'Newsletter', 111 | content: `Subject: Marketing Weekly 112 | 113 | Marketing Weekly 114 | December 17 • Issue #52 • Tweet • Forward 115 | Erica Stanley 116 | 15 Sunday, December, 2023 117 | 👋Good day! 118 | 119 | Here's your weekly marketing news.☕️ 120 | 121 | ⚡️ Powered by Mstrpc.es • Brought to you by Robbie Vang 122 | 123 | Blogs 124 | Better Marketing - Medium 125 | I've Been Roadtesting Marketing Strategies For Writers, So You Don't Have To 126 | Ellen "Jelly" McRae 127 | Dec 15 128 | 129 | How We Grew 192% Through Landing Page Optimisation 130 | Daphne Tideman 131 | Dec 14 132 | 133 | Discounts Are Subtly Undermining Your Marketing. 134 | Zulie Rane 135 | Dec 14 136 | 137 | 12 Practical Strategies to More Memorable Marketing 138 | Anthony Robert 139 | Dec 13`}, 140 | 141 | ]; 142 | -------------------------------------------------------------------------------- /frontend/src/data/user-request.json: -------------------------------------------------------------------------------- 1 | {"title":"User Request","prompts":[{"id":1,"log":"Checking request type","name":"prompt1","inputs":["message"],"outputs":[{"name":"msg_type","event":"","parser":"full_response"}],"prompt":"You are a smart categorization assistant.\n\nRequest:\n```\n{{message}}\n```\n\nShould we answer directly, lookup information, or perform a task? Just reply with:\nAnswer Type: direct, lookup, or task"},{"id":2,"log":"Replying","name":"prompt2","inputs":["message"],"outputs":[{"name":"msg_type","parser":"full_response"}],"prompt":"You are a helpful assistant.\n\nRequest:\n```\n{{message}}\n```\n\nRespond to this request with a concise, useful response. {{ai_tone}}"},{"id":3,"log":"Replying with lookup","name":"prompt3","inputs":["message"],"outputs":[{"name":"result","parser":"full_response"}],"prompt":"You are a helpful assistant.\n\nYou have the following context available:\n```\nCurrent Date: Monday, 01/01/2024\nCurrent Weather: 78f\nSports News: Llamas beat GPTs 5-1\nPolitics: Mr. O. Hermes running for president this year\nTech: Local always-running AI assistants will be available this year!\n```\n\nMessage:\n```\n{{message}}\n```\n\nRespond to the message using the context above if it helps. {{ai_tone}}"},{"id":4,"log":"Handling task","name":"prompt4","inputs":["message"],"outputs":[{"name":"tasks","event":"task_list","parser":"full_response"}],"prompt":"How should I handle this request?\n```\n{{message}}\n```\n\nWe can use these assistants:\nSearcher: For requests to lookup information\nSecretary: For calendar, to do lists, etc\nWriter: For requests to draft messages\n\nRespond with a bullet list of which assistants we should use and what they should do, before replying to the user.\n\nExample list:\n1. Searcher: Find the current weather\n2. Secretary: Add to do task to make a call\n3. Writer: Draft a message about project update\n\nOnly use the assistants requested by the user."}],"entry_points":[{"id":1,"opts":{"conditions":[],"map":{"message":"message"}},"entry_points":[{"id":2,"opts":{"conditions":[{"op":"include","name":"msg_type","value":"direct"}],"map":{"message":"message"}},"entry_points":[]},{"id":3,"opts":{"conditions":[{"op":"include","name":"msg_type","value":"lookup"}],"map":{"message":"message"}},"entry_points":[]},{"id":4,"opts":{"conditions":[{"op":"include","name":"msg_type","value":"task"}],"map":{"message":"message"}},"entry_points":[]}]}]} -------------------------------------------------------------------------------- /frontend/src/lib/ai-job.js: -------------------------------------------------------------------------------- 1 | export function FindListItems(text) { 2 | let res = []; 3 | text.split("\n").forEach((line) => { 4 | let m; 5 | if (m = /^((\d+\.?)|(-)|(\*)) ?(.*)/.exec(line)) { 6 | res.push(m[5]); 7 | } 8 | }); 9 | return res; 10 | }; 11 | export class AIChatJob { 12 | static QUEUED = 0; 13 | static RUNNING = 1; 14 | static COMPLETED = 2; 15 | static ERROR = 3; 16 | constructor(app, opts) { 17 | if (!opts) opts = {}; 18 | this.ai_chat_job = true; 19 | this.api_base = opts.api_base || app.api_base || ''; 20 | this.api_key = opts.api_key || app.api_key; 21 | this.api_model = opts.api_model || app.api_model || 'gpt-3.5-turbo'; 22 | this.opts = opts; 23 | this.stream = ''; 24 | this.response = ''; 25 | this.running = false; 26 | this.messages = []; 27 | this.state = 0; 28 | this.app = app; 29 | this.response = ''; 30 | this.promise = new Promise((resolve, reject) => { this.promise_res = resolve; this.promise_rej = reject }); 31 | } 32 | 33 | add_message(prompt, role) { 34 | this.messages.push({ 35 | role: role || 'user', 36 | content: prompt, 37 | }); 38 | } 39 | run() { 40 | let p = this.promise; 41 | this.state = 1; 42 | let headers = {'content-type': 'application/json'}; 43 | if (this.api_key) headers.authorization = 'Bearer ' + this.api_key; 44 | let stream = new this.app.stream.LineStream(this.api_base + '/v1/chat/completions', { 45 | method: 'POST', 46 | body: JSON.stringify({ 47 | model: this.api_model, 48 | stream: true, 49 | messages: this.messages, 50 | }), 51 | headers: new Headers(headers), 52 | }); 53 | stream.run( 54 | (line) => { 55 | //console.log("Line:", line); 56 | let data; 57 | try { 58 | let m = /^data: (.*)$/.exec(line); 59 | if (m) { 60 | if (m[1] == '[DONE]') { 61 | data = {choices: [{delta: {content: ''}}]}; 62 | } else { 63 | data = JSON.parse(m[1]); 64 | } 65 | } else if (line == '') { 66 | data = {choices: [{delta: {content: ''}}]}; 67 | } else { 68 | data = {choices: [{delta: {content: "\n?? " + line + "\n"}}]}; 69 | } 70 | } catch { 71 | data = {choices: [{delta: {content: "\nError on: " + line + "\n"}}]}; 72 | } 73 | this.response += data.choices[0].delta.content || ''; 74 | }, 75 | () => { 76 | this.running = false; 77 | this.state = 2; 78 | this.promise_res(true); 79 | } 80 | ).catch((err) => { 81 | this.running = false; 82 | this.state = 3; 83 | this.error = err; 84 | this.promise_rej(err); 85 | }); 86 | return p; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /frontend/src/lib/db.js: -------------------------------------------------------------------------------- 1 | import * as idb from 'idb'; 2 | 3 | export class DB { 4 | 5 | constructor(name, version, tables) { 6 | this.name = name; 7 | this.tables = tables; 8 | this.version = version; 9 | this.db = idb.openDB(name, version, { 10 | upgrade: (db) => this.setup(db), 11 | }); 12 | tables.forEach((table) => { 13 | this[table.collection || table.name.toLowerCase()] = new Table(this, table); 14 | }); 15 | } 16 | 17 | destroy() { 18 | // TODO: this.db.destroy() 19 | } 20 | setup(db) { 21 | this.tables.forEach((table) => { 22 | let store = db.createObjectStore(table.name, { 23 | keyPath: table.id || 'id', 24 | autoIncrement: true, 25 | }); 26 | // TODO: store.createIndex(field, type); 27 | }); 28 | } 29 | 30 | promise_wrap(fn) { 31 | let res,rej,p; 32 | p = new Promise((resolve, reject) => { res = resolve; rej = reject }); 33 | fn(res, rej) 34 | return p; 35 | } 36 | conn_wrap(fn) { 37 | return this.promise_wrap((res, rej) => { 38 | this.db.then((db) => { 39 | fn(db, res, rej); 40 | }).catch((err) => rej(err)); 41 | }); 42 | } 43 | simple_wrap(fn, args) { 44 | return this.conn_wrap((db,res,rej) => { 45 | db[fn](...args).then((r) => { 46 | res(r); 47 | }).catch((err) => rej(err)); 48 | }); 49 | } 50 | } 51 | 52 | function createTableEntry(table) { 53 | let cls = function(data) { 54 | this.data = data || {}; 55 | this.table = table; 56 | this.conn = table.conn; 57 | }; 58 | 59 | cls.prototype.save = function() { 60 | return this.conn.simple_wrap('put', [this.table.name, this.data]); 61 | }; 62 | cls.prototype.destroy = function() { 63 | return this.conn.simple_wrap('delete', [this.table.name, this.data.id]); 64 | }; 65 | 66 | table.table.attrs.forEach((attr) => { 67 | Object.defineProperty(cls.prototype, attr, { 68 | get: function() { return this.data[attr] }, 69 | set: function(val) { this.data[attr] = val } 70 | }); 71 | }); 72 | 73 | return cls; 74 | }; 75 | 76 | export class Table { 77 | constructor(conn, table) { 78 | this.conn = conn; 79 | this.table = table; 80 | this.name = table.name; 81 | this.entry_cls = createTableEntry(this); 82 | } 83 | 84 | all(opts) { 85 | if (!opts) opts = {}; 86 | return this.conn.simple_wrap('getAll', [this.name]).then((r) => { 87 | let list = r.map((ent) => new this.entry_cls(ent)); 88 | if (opts.filter) list = list.filter((entry) => opts.filter(entry)); 89 | return list; 90 | }); 91 | } 92 | create(data) { 93 | return this.conn.conn_wrap((db,res,rej) => { 94 | db.add(this.name, data).then((r) => { 95 | res(new this.entry_cls({id: r, ...data})); 96 | }).catch((err) => { rej(err) }); 97 | }); 98 | } 99 | 100 | find(id) { 101 | let res,rej,p; 102 | p = new Promise((resolve, reject) => {res = resolve; rej = reject}); 103 | this.conn.db.then((db) => { 104 | db.get(this.name, id).then((r) => { 105 | res(new this.entry_cls(r)); 106 | }).catch((err) => rej(err)); 107 | }).catch((err) => rej(err)); 108 | return p; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /frontend/src/lib/job-queue.js: -------------------------------------------------------------------------------- 1 | export const job_status = { 2 | waiting: 1, 3 | running: 2, 4 | complete: 3, 5 | failed: 4, 6 | }; 7 | export class Job { 8 | constructor(opts) { 9 | if (!opts) opts = {}; 10 | this.opts = opts; 11 | this.id = opts.id; 12 | this.priority = opts.priority || 5; 13 | this.job = opts.job; 14 | this.job_args = opts.args || []; 15 | 16 | this.state = job_status.waiting; 17 | this.error = null; 18 | this.result = null; 19 | this.promise = new Promise((res, rej) => { 20 | this.p_res = res; 21 | this.p_rej = rej; 22 | }); 23 | } 24 | 25 | complete(result) { 26 | this.state = job_status.complete; 27 | this.error = null; 28 | this.result = result; 29 | this.p_res(result); 30 | } 31 | 32 | fail(result) { 33 | this.state = job_status.failed; 34 | this.error = result; 35 | this.result = null; 36 | } 37 | run() { 38 | this.state = job_status.running; 39 | let resolver,rejector,p; 40 | p = new Promise((res,rej) => { resolver = res; rejector = rej }); 41 | console.log("Running job", this.job_args); 42 | let res = this.job(...this.job_args); 43 | if (res.finally) { 44 | res.then((r) => { 45 | this.complete(r); 46 | resolver(r); 47 | }).catch((err) => { 48 | this.fail(err); 49 | rejector(err); 50 | }); 51 | } else { 52 | resolver(res); 53 | } 54 | return p; 55 | } 56 | } 57 | 58 | export class JobQueue { 59 | 60 | constructor(opts) { 61 | if (!opts) opts = {}; 62 | this.opts = opts; 63 | this.runners = 1; 64 | this.jobs = []; 65 | this.should_shutdown = false; 66 | this.run_count = 0; 67 | this.sleep_time = opts.sleep || 2000; 68 | this.low_pri_sleep = opts.low_pri_sleep || 10000; 69 | this.debug_mode = opts.debug || false; 70 | this.next_job_id = 0; 71 | } 72 | 73 | shutdown_now() { 74 | this.should_shutdown = true; 75 | } 76 | debug() { 77 | if (this.debug_mode) { 78 | console.log(...arguments); 79 | } 80 | } 81 | get_job_id() { 82 | this.next_job_id += 1; 83 | return this.next_job_id - 1; 84 | } 85 | get_job() { 86 | let job = this.jobs.splice(0, 1); 87 | return job ? job[0] : null; 88 | } 89 | add_job(fn, opts) { 90 | if (!opts) opts = {}; 91 | let job = new Job({ 92 | job: fn, 93 | id: opts.id || this.get_job_id(), 94 | ...opts, 95 | }); 96 | this.jobs.push(job); 97 | return job; 98 | } 99 | remove_job(job) { 100 | for (let i in this.jobs) { 101 | if (this.jobs[i] == job) { 102 | this.jobs.splice(i, 1); 103 | return true; 104 | } 105 | } 106 | return false; 107 | } 108 | run(id) { 109 | if (this.should_shutdown) { 110 | this.debug("Shutdown received for runner", id); 111 | this.run_count -= 1; 112 | return; 113 | } 114 | this.run_count += 1; 115 | let new_job = this.get_job(), run_p = null; 116 | if (!new_job) { 117 | run_p = new Promise((res,rej) => { 118 | setTimeout(() => res(), this.sleep_time); 119 | }); 120 | } else { 121 | this.debug("Runner new job", id, new_job); 122 | // Priority 0 has an additional delay. 123 | if (new_job.priority == 0) { 124 | run_p = new Promise((res,rej) => { 125 | setTimeout(() => { 126 | new_job.run().then((r) => { res(r)} ).catch((err) => { rej(err) }); 127 | }, this.low_pri_sleep); 128 | }); 129 | } else { 130 | run_p = new_job.run(); 131 | } 132 | } 133 | run_p.finally(() => { 134 | if (new_job) { 135 | this.debug("Job finished", new_job); 136 | this.remove_job(new_job); 137 | } 138 | this.run(id); 139 | }); 140 | return run_p; 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /frontend/src/lib/prompt-chain.js: -------------------------------------------------------------------------------- 1 | import * as Prompt from './prompt-entry.js' 2 | 3 | export class PromptChain { 4 | constructor(app, opts) { 5 | if (!opts) opts = {}; 6 | this.title = opts.title; 7 | this.opts = opts; 8 | this.app = app; 9 | this.prompts = {}; 10 | this.last_id = 0; 11 | 12 | this.entry_points = []; 13 | } 14 | 15 | import_entries(entry_parent, entrypoints) { 16 | for (let entry of entrypoints) { 17 | let child = entry_parent.entrypoint(entry.id, entry.opts); 18 | this.import_entries(child, entry.entry_points); 19 | } 20 | } 21 | static import_chain(app, data) { 22 | let chain = new PromptChain(app, { 23 | title: data.title, 24 | }); 25 | 26 | for (let prompt of data.prompts) { 27 | chain.register({ 28 | id: prompt.id, 29 | log: prompt.log, 30 | inputs: prompt.inputs, 31 | outputs: prompt.outputs, 32 | prompt: prompt.prompt, 33 | }); 34 | } 35 | for (let entry of data.entry_points) { 36 | let ep = chain.entrypoint(entry.id, entry.opts); 37 | chain.import_entries(ep, entry.entry_points); 38 | } 39 | return chain; 40 | } 41 | entry_export(entry) { 42 | let ent = { 43 | id: entry.prompt_id, 44 | opts: {conditions: entry.conditions, map: entry.fields}, 45 | entry_points: [], 46 | }; 47 | for (let child of entry.entry_points) { 48 | ent.entry_points.push(this.entry_export(child)); 49 | } 50 | return ent; 51 | } 52 | export_chain() { 53 | let chain = { 54 | title: this.title, 55 | prompts: [], 56 | entry_points: [], 57 | }; 58 | 59 | for (let key in this.prompts) { 60 | let p = this.prompts[key]; 61 | let entry = p.prompt_entry; 62 | let prompt = { 63 | id: p.id, 64 | log: p.log, 65 | name: p.name, 66 | inputs: entry.inputs, 67 | outputs: entry.outputs, 68 | prompt: entry.prompt, 69 | } 70 | chain.prompts.push(prompt); 71 | } 72 | 73 | for (let entry of this.entry_points) { 74 | chain.entry_points.push(this.entry_export(entry)); 75 | } 76 | 77 | return chain; 78 | } 79 | get_response_value(response, output) { 80 | if (output.parser == 'full_response') { 81 | return response; 82 | } else if (output.parser == 'from_line') { 83 | for (let line of response.split("\n")) { 84 | line = line.toLowerCase(); 85 | if (line.toLowerCase().startsWith(output.parser_ex)) { 86 | return line.slice(output.parser_ex.length).trim(); 87 | } 88 | } 89 | } 90 | return ''; 91 | } 92 | run_entry(ep, state) { 93 | //console.log("Starting entry", ep.prompt.name, state, ep); 94 | let ep_state = {ai_tone: state.ai_tone}; 95 | for (let key in ep.fields) { 96 | ep_state[key] = state[ep.fields[key]]; 97 | } 98 | return new Promise((res,rej) => { 99 | //console.log("Run entry", ep.prompt.name, ep_state, ep); 100 | let job = ep.prompt.prompt_entry.create_job(ep_state, { 101 | summary: (this.title) + ": " + (ep.prompt.log || ep.prompt.name), 102 | }); 103 | let fj = this.app.ai_queue.add_job(job.run.bind(job), {priority: 5}) 104 | this.app.ai_log.push({job: fj, request: job}) 105 | console.log("Starting entry job", ep.prompt.name, job.messages.map((m) => m.content)); 106 | 107 | job.promise.then((result) => { 108 | let response = job.response; 109 | let events = []; 110 | let i = 0; 111 | for (let output of ep.prompt.prompt_entry.outputs) { 112 | let out_name = output.target || output.name; 113 | let res = this.get_response_value(response, output); 114 | if (output.event) { 115 | events.push({event: output.event, value: res, source: output}); 116 | } 117 | state[out_name] = res; 118 | //console.log("Set output", output, out_name, res, "State:", state); 119 | } 120 | //console.log("Job finished", ep.prompt.name, state, job, ep_state); 121 | res({children: ep.entry_points, events: events}); 122 | }).catch((err) => { 123 | console.log("Job failed!", err) 124 | rej({error: err}); 125 | }); 126 | }); 127 | } 128 | 129 | check_condition(state, condition) { 130 | if (condition.op == '==') { 131 | return state[condition.name] == condition.value; 132 | } else if (condition.op == '!=') { 133 | return state[condition.name] != condition.value; 134 | } else if (condition.op == 'include') { 135 | return state[condition.name].indexOf(condition.value) != -1; 136 | } else if (condition.op == 'exclude') { 137 | return state[condition.name].indexOf(condition.value) == -1; 138 | } 139 | } 140 | start(fields, opts) { 141 | let state = {}; 142 | let p, res, rej; 143 | if (!opts) opts = {}; 144 | p = new Promise((resolve, reject) => { res = resolve; rej = reject; }); 145 | for (let key in fields) { 146 | state[key] = fields[key]; 147 | } 148 | let eps = [...this.entry_points]; 149 | 150 | console.log("Start chain", this.title, state); 151 | let run_next = (eps) => { 152 | let ep = eps.splice(0, 1)[0]; 153 | //console.log("Running next", eps.length, ep); 154 | if (!ep) { 155 | //console.log("Chain complete", this.title, state); 156 | if (opts.update) opts.update(state); 157 | res(state); 158 | return; 159 | } 160 | let should_run = true; 161 | 162 | if (ep.conditions) { 163 | for (let cond of ep.conditions) { 164 | let check = this.check_condition(state, cond); 165 | console.log("Check condition", cond, "=", check, state); 166 | if (!check) { 167 | should_run = false; 168 | break; 169 | } 170 | } 171 | } 172 | if (should_run) { 173 | this.run_entry(ep, state, opts).then((r) => { 174 | for (let c of r.children) { eps.push(c) } 175 | for (let evt of r.events) { 176 | if (opts.onEvent) opts.onEvent(evt); 177 | } 178 | if (opts.update) opts.update(state); 179 | run_next(eps); 180 | }); 181 | } else { 182 | run_next(eps); 183 | } 184 | }; 185 | 186 | run_next(eps); 187 | return p; 188 | } 189 | get_next_id() { 190 | this.last_id += 1; 191 | return this.last_id; 192 | } 193 | 194 | register(opts) { 195 | let prompt = new Prompt.PromptEntry(this.app, { 196 | prompt: opts.prompt, 197 | inputs: opts.inputs, 198 | outputs: opts.outputs, 199 | }); 200 | let id; 201 | if (opts.id) { 202 | id = opts.id; 203 | this.last_id = opts.id; 204 | } else { 205 | id = this.get_next_id(); 206 | } 207 | this.prompts[id] = { 208 | id: id, 209 | log: opts.log, 210 | name: opts.name || `prompt${id}`, 211 | prompt_entry: prompt, 212 | children: [], 213 | }; 214 | return this.prompts[id]; 215 | } 216 | 217 | add_child(ep, id, opts) { 218 | let p = this.prompts[id]; 219 | let ent = { 220 | prompt_id: id, 221 | prompt: p, 222 | conditions: opts.conditions || [], 223 | fields: opts.map, 224 | entry_points: [], 225 | }; 226 | ep.entry_points.push(ent); 227 | ent.entrypoint = this.add_child.bind(this, ent); 228 | } 229 | entrypoint(id, opts) { 230 | let p = this.prompts[id]; 231 | let ent = { 232 | prompt_id: id, 233 | prompt: p, 234 | conditions: opts.conditions || [], 235 | fields: opts.map, 236 | entry_points: [], 237 | }; 238 | ent.entrypoint = this.add_child.bind(this, ent); 239 | this.entry_points.push(ent); 240 | return ent; 241 | } 242 | 243 | } 244 | -------------------------------------------------------------------------------- /frontend/src/lib/prompt-entry.js: -------------------------------------------------------------------------------- 1 | import * as ai_job from './ai-job.js' 2 | 3 | export class PromptInstance { 4 | constructor(entry, opts) { 5 | this.entry = entry; 6 | this.inputs = {ai_tone: opts.inputs.ai_tone}; 7 | 8 | for (let input of entry.inputs) { 9 | this.inputs[input] = opts.inputs[input]; 10 | } 11 | 12 | this.outputs = {full_message: ''}; 13 | for (let output of entry.outputs) { 14 | this.outputs[output.name] = ''; 15 | } 16 | } 17 | 18 | generate_prompt() { 19 | let prompt_str = this.entry.prompt; 20 | for (let key in this.inputs) { 21 | prompt_str = prompt_str.replaceAll('{{' + key + '}}', this.inputs[key]); 22 | } 23 | return prompt_str; 24 | } 25 | } 26 | 27 | export class PromptEntry { 28 | constructor(app, opts) { 29 | if (!opts) opts = {}; 30 | this.opts = opts; 31 | this.app = app; 32 | this.prompt = opts.prompt; 33 | this.inputs = opts.inputs; 34 | this.outputs = opts.outputs; 35 | this.parser = opts.parser || this.line_parser; 36 | } 37 | 38 | create_job(inputs, opts) { 39 | if (!opts) opts = {}; 40 | let inst = new PromptInstance(this, {inputs: inputs}); 41 | let job = new ai_job.AIChatJob(this.app, {instance: inst, summary: opts.summary}); 42 | job.add_message(inst.generate_prompt(), this.opts.role || 'system'); 43 | return job; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /frontend/src/lib/streamer.js: -------------------------------------------------------------------------------- 1 | export function DataParser(line, parse_json) { 2 | let result = {}, match; 3 | if (line == '') { 4 | return {empty: true, text: ''}; 5 | } 6 | if (match = /^data: (.*)$/.exec(line)) { 7 | if (parse_json) 8 | result.json = JSON.parse(match[1]); 9 | else 10 | result.text = match[1] 11 | } else { 12 | result.error = 'No data header'; 13 | result.line = line; 14 | } 15 | return result; 16 | } 17 | export class LineStream { 18 | constructor(path, req, opts) { 19 | if (!opts) opts = {}; 20 | this.path = path; 21 | this.req = req; 22 | this.current = ''; 23 | this.on_line = null; 24 | this.on_done = null; 25 | this.opts = opts; 26 | } 27 | 28 | parse_lines(chunk, is_done) { 29 | let nl = chunk.indexOf("\n"), pos=0, count = 0; 30 | while (true) { 31 | count += 1; 32 | if (count > 20) return; 33 | if (nl == -1) { 34 | this.current += chunk; 35 | break; 36 | } else { 37 | this.current += chunk.substring(0, nl); 38 | this.on_line(this.opts.json ? JSON.parse(this.current) : this.current); 39 | this.current = ''; 40 | chunk = chunk.substring(nl+1); 41 | nl = chunk.indexOf("\n"); 42 | } 43 | } 44 | if (is_done && this.current) { 45 | this.on_line(this.opts.json ? JSON.parse(this.current) : this.current); 46 | this.current = ''; 47 | } 48 | } 49 | run(on_line, on_done) { 50 | this.on_line = on_line; 51 | this.on_done = on_done; 52 | let req = fetch(this.path, this.req); 53 | req.then((r) => { 54 | let reader = r.body.pipeThrough(new TextDecoderStream()).getReader(); 55 | let done, value, count = 0; 56 | let fn = () => { 57 | reader.read().then((v) => { 58 | //console.log("New", v); 59 | if (v.done) { 60 | this.parse_lines(v.value || '', true); 61 | if (this.on_done) this.on_done(); 62 | return; 63 | } 64 | this.parse_lines(v.value); 65 | fn(); 66 | }); 67 | }; 68 | fn(); 69 | }); 70 | return req; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /frontend/src/lib/tree-store.js: -------------------------------------------------------------------------------- 1 | export class TreeStore { 2 | 3 | constructor(opts) { 4 | this.opts = opts || {}; 5 | this.pid = opts.pid || 'pid'; 6 | this.id_field = opts.id || 'id'; 7 | this.roots = []; 8 | this.all_items = []; 9 | this.item_dict = {}; 10 | } 11 | 12 | add_item(parent, child) { 13 | parent.children.push(this.item_struct(child)); 14 | } 15 | remove_item(item) { 16 | if (item.parent) { 17 | let idx = item.parent.children.indexOf(item); 18 | if (idx !== -1) item.parent.children.splice(idx, 1); 19 | } else { 20 | let idx = this.roots.indexOf(item); 21 | if (idx !== -1) this.roots.splice(idx, 1); 22 | } 23 | } 24 | item_struct(item, p) { 25 | let new_item = { 26 | id: item[this.id_field], 27 | entry: item, 28 | children: [], 29 | parent: p, 30 | }; 31 | new_item.add = this.add_item.bind(this, new_item); 32 | new_item.remove = this.remove_item.bind(this, new_item); 33 | return new_item; 34 | } 35 | add_children(p) { 36 | for (let item of this.all_items) { 37 | if (item[this.pid] == p.id) { 38 | let new_child = this.item_struct(item, p); 39 | p.children.push(new_child); 40 | this.add_children(new_child); 41 | } 42 | } 43 | } 44 | add_root(item) { 45 | this.roots.push(this.item_struct(item, null)); 46 | } 47 | init(item_list) { 48 | this.all_items = item_list; 49 | this.item_dict = {}; 50 | this.roots = []; 51 | 52 | for (let item of item_list) { 53 | this.item_dict[item[this.id_field]] = item; 54 | if (!item[this.pid]) { 55 | this.roots.push(this.item_struct(item, null)); 56 | } 57 | } 58 | this.roots.forEach((root) => { this.add_children(root) }); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /frontend/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue'; 2 | import './core/style.scss' 3 | import App from './core/App.vue' 4 | import * as AppInit from './app.js' 5 | 6 | AppInit.init.vue = Vue; 7 | new Vue({ 8 | render: (h) => h(App, {props: {AppInit: AppInit}}), 9 | }).$mount('#app'); 10 | -------------------------------------------------------------------------------- /frontend/vite.config.js: -------------------------------------------------------------------------------- 1 | const { createVuePlugin } = require('vite-plugin-vue2'); 2 | import { viteSingleFile } from "vite-plugin-singlefile" 3 | 4 | module.exports = { 5 | plugins: [ 6 | createVuePlugin(), 7 | viteSingleFile(), 8 | ], 9 | base: './', 10 | server: { 11 | proxy: { 12 | '/llm/': { 13 | target: `http://127.0.0.1:8080/`, 14 | rewrite: (path) => path.replace(/^\/llm\//, ''), 15 | }, 16 | }, 17 | }, 18 | }; 19 | --------------------------------------------------------------------------------