Upload folder using huggingface_hub
Browse files- static/css/ragrqs.min.css +1 -1
- static/javascript/rag_cleaner.js +68 -86
- static/javascript/rag_data_mgr.js +2 -2
- static/javascript/rag_http.js +75 -51
- static/javascript/rag_mgr.js +121 -89
- static/javascript/rag_prompts.js +83 -87
- static/javascript/rag_rqs.js +6 -6
- static/javascript/rag_ui.js +7 -7
- static/javascript/ualog3.js +12 -2
- static/js/ragrqs.min.js +106 -106
- static/less/ragrqs.less +2 -2
- static/ragrqs_.html +1 -5
static/css/ragrqs.min.css
CHANGED
@@ -1 +1 @@
|
|
1 |
-
a,body,button,div,html,input,label,li,p,span,table,td,ul{padding:0;margin:0;font-family:arial,verdana,Helvetica,sans-serif}.bb0{background:#daee59!important}.bb1{background:#5487fc!important}html{background:#1a1a1a}body{background:#1a1a1a;box-sizing:border-box;min-height:100vh;height:100vh;position:relative;padding:0;margin:0;overflow:hidden;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400}.spinner{z-index:1000;position:absolute;top:70vh;left:50vw;transform:translate(-50%,-50%);cursor:pointer;display:none;align-items:center}.spinner .pulse-icon{width:20px;height:20px;background-color:#ff8c00;border-radius:50%;animation:1.5s ease-in-out infinite pulse}.spinner .stop-message{margin-left:15px;background-color:inherit;color:#8f8a8a;padding:8px 15px;border-radius:10px;font-size:22px;font-weight:700;opacity:1;transition:opacity .3s}.spinner:hover .stop-message{color:#fff;background:#595959;opacity:1}@keyframes pulse{0%{transform:scale(.6);box-shadow:0 0 0 0 rgba(255,140,0,.7)}70%{transform:scale(1.4);box-shadow:0 0 0 20px rgba(255,140,0,0)}100%{transform:scale(.6);box-shadow:0 0 0 0 rgba(255,140,0,0)}}.show-spinner{display:flex}.upload{background-color:#1e1e1e;padding:0 2em 2em;margin:0;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,.5);text-align:center}.upload h4{color:#fff;margin-bottom:1em}.upload form{display:flex;flex-direction:column;align-items:center}.upload form .file{background-color:#121212;border:1px solid #515151;color:#fff;padding:.5em;margin-bottom:1em;border-radius:4px;width:100%;box-sizing:border-box}.upload form .file::file-selector-button{background-color:#0a5f4e;color:#fff;border:none;padding:.5em 1em;border-radius:4px;cursor:pointer}.upload form .file::file-selector-button:hover{background-color:#053128}.upload form button{background-color:#0a5f4e;color:#fff;border:none;padding:.5em 1em;border-radius:4px;cursor:pointer;width:100%;box-sizing:border-box}.upload form button:hover{background-color:#053128}.upload .result{width:100%;background:#000;color:#fff;font-size:15px;font-weight:400;text-align:left}div.container{background:#1a1a1a;box-sizing:border-box;position:relative;top:5vh;left:0;height:95vh;margin:0;padding:0;transition:margin-left .5s;display:flex;flex-direction:column;justify-content:flex-start;align-items:stretch;flex-wrap:nowrap;overflow-y:auto;overflow-x:auto}div.container div.item{box-sizing:border-box;min-height:50px;margin:0;padding:0}div.container div.item1{flex:5;padding:.5vh .5vw 10vh}div.container div.item1 .output-wrapper{background-color:#1a1a1a;border-radius:20px;position:relative;bottom:0;right:0;left:0;width:100%;height:100%;display:flex;flex-direction:row;align-items:flex-start}div.container div.item1 .output-wrapper .text-out{flex:1;box-sizing:border-box;background:#000;color:#fff;border:none;padding:2px;min-width:50vw;height:100%;border-radius:10px;overflow-y:auto;outline:0;box-shadow:0 0 0 2px #4d4d4d}div.container div.item1 .output-wrapper .text-out:hover{box-shadow:0 0 0 2px #17d2ad}div.container div.item1 .output-wrapper .text-out .pre-text{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:20px;line-height:1.6;padding:2px;margin:0;height:100%;box-sizing:border-box;overflow-y:scroll;scroll-behavior:smooth}div.container div.item1 .output-wrapper .text-out .pre-text.copied{background-color:#0d0d0d;color:#61eed2}div.container div.item1 .output-wrapper .text-out .div-text{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:20px;line-height:1.6;padding:2px;margin:0;height:100%;box-sizing:border-box;overflow-y:scroll}div.container div.item1 .output-wrapper .text-out.copied{background-color:#0d0d0d;color:#61eed2}div.container div.item1 .output-actions{display:flex;flex-direction:column;align-items:flex-end;margin-left:.5vw;margin-right:.5vw}div.container div.item1 .output-actions .clear-output,div.container div.item1 .output-actions .copy-output,div.container div.item1 .output-actions .wnd-output{box-sizing:border-box;background-color:#333;color:#fff;border:none;padding:10px;cursor:pointer;border-radius:50%;width:40px;height:40px;display:flex;align-items:center;margin-bottom:5px}div.container div.item1 .output-actions .clear-output:hover,div.container div.item1 .output-actions .copy-output:hover,div.container div.item1 .output-actions .wnd-output:hover{background-color:#595959}div.container div.item1 .output-actions .copy-output{transition:background-color .3s,transform .3s}div.container div.item1 .output-actions .copy-output.copied{background:#33e9c5;transform:scale(1.2)}div.container div.item1 .output-actions .copy-output .copy-icon{fill:#ffffff;width:24px;height:24px}div.container div.item1 .output-actions .copy-output .copy-icon:hover{fill:#33e9c5}div.container div.item1 .output-actions .clear-output,div.container div.item1 .output-actions .wnd-output{transition:background-color .3s,transform .3s}div.container div.item1 .output-actions .clear-output .icon,div.container div.item1 .output-actions .wnd-output .icon{fill:#ffffff;width:24px;height:24px}div.container div.item1 .output-actions .clear-output .icon:hover,div.container div.item1 .output-actions .wnd-output .icon:hover{fill:#33e9c5}:hover{outline:0;caret-color:transparent}textarea:focus{caret-color:auto}div.item2{flex:2;padding:0 .5vw}div.item2 .input-wrapper{background-color:#1a1a1a;border-radius:20px;position:relative;bottom:2vh;right:0;left:0;width:100%;height:100%;display:flex;flex-direction:row;align-items:flex-start}div.item2 .input-wrapper:focus-within .clear-button{display:block}div.item2 .input-wrapper .text-input{flex:1;font-size:20px;font-family:arial,verdana,Helvetica,sans-serif;resize:none;box-sizing:border-box;background:#000;color:#fff;border:none;padding:2px 40px 2px 2px;height:100%;margin-left:5px;border-radius:10px;overflow-y:auto;outline:0;box-shadow:0 0 0 2px #4d4d4d}div.item2 .input-wrapper .text-input:hover{box-shadow:0 0 0 2px #17d2ad}div.item2 .input-wrapper .text-input:focus{box-shadow:0 0 0 2px #ff4500}div.item2 .input-wrapper .clear-button{position:absolute;right:60px;top:19vh;padding:5px;border-radius:50%;background:#333;border:none;font-size:20px;cursor:pointer;color:#ccc;display:none}div.item2 .input-wrapper .clear-button:hover{font-weight:700;background:#595959;color:#fff}div.item2 .input-wrapper .input-actions{display:flex;flex-direction:column;margin-left:.5vw;margin-right:.5vw}div.item2 .input-wrapper .input-actions .clear-input,div.item2 .input-wrapper .input-actions .send-input,div.item2 .input-wrapper .input-actions .send2-input{box-sizing:border-box;background-color:#333;color:#fff;border:none;padding:10px;cursor:pointer;border-radius:50%;width:40px;height:40px;margin-bottom:5px;transition:background-color .3s}div.item2 .input-wrapper .input-actions .send-input{background:#992900}div.item2 .input-wrapper .input-actions .send-input:hover{background:#ff4500}div.item2 .input-wrapper .input-actions .send2-input{background:#0d7661}div.item2 .input-wrapper .input-actions .send2-input:hover{background:#14bb9a}div.item2 .input-wrapper .input-actions .clear-input{background:#333;color:#e6e6e6}div.item2 .input-wrapper .input-actions .clear-input:hover{background:#595959;color:#33e9c5}.menu-open .container{margin-left:16vw}.menu-open .menu-box{left:0!important}div.menu-h{background-color:#1a1a1a;position:fixed;top:0;left:0;width:100vw;height:4.5vh;padding:0;margin:0;outline:0;box-shadow:0 0 0 2px #4d4d4d;z-index:100}div.menu-h .release{background:inherit;color:#ff6a33;font-weight:700;margin-left:50vw;margin-top:.5vh}div.menu-h .menu-btn{appearance:none}div.menu-h .menu-btn:checked+.menu-icon{border:1px solid #333}div.menu-h .menu-btn:checked+.menu-icon .nav-icon{transform:rotate(45deg)}div.menu-h .menu-btn:checked+.menu-icon .nav-icon::before{top:0}div.menu-h .menu-btn:checked+.menu-icon .nav-icon::after{top:0;transform:rotate(90deg)}div.menu-h .menu-icon{box-sizing:border-box;background-color:inherit;display:block;position:absolute;margin-left:2vw;top:0;left:0;width:4vw;height:4.5vh;cursor:pointer;padding:2px;z-index:1}div.menu-h .menu-icon:hover .nav-icon,div.menu-h .menu-icon:hover .nav-icon::after,div.menu-h .menu-icon:hover .nav-icon::before{background-color:#33e9c5}div.menu-h .menu-icon .nav-icon{background-color:#aea7a7;display:block;position:absolute;top:14px;left:0;width:25px;height:2px;transition-duration:.25s}div.menu-h .menu-icon .nav-icon::after,div.menu-h .menu-icon .nav-icon::before{content:"";position:absolute;left:0;background-color:inherit;width:inherit;height:inherit}div.menu-h .menu-icon .nav-icon::before{top:-8px}div.menu-h .menu-icon .nav-icon::after{top:8px}div.menu-h .head-wrapper{position:absolute;top:0;left:5vw;height:4vh;padding:0;margin:0;display:inline-flex;flex-direction:row;flex-wrap:nowrap;align-items:center;justify-content:flex-start}div.menu-h .head-wrapper .help,div.menu-h .head-wrapper .log,div.menu-h .head-wrapper .upload,div.menu-h .head-wrapper .upload-dir{margin-top:2px;margin-left:30px;margin-right:0;padding:5px 5px 0;border:none;cursor:pointer;border-radius:20%;font-size:20px;color:#fff;background:#333;max-height:4vh}div.menu-h .head-wrapper .help:hover,div.menu-h .head-wrapper .log:hover,div.menu-h .head-wrapper .upload-dir:hover,div.menu-h .head-wrapper .upload:hover{background:#595959}div.menu-h .upload,div.menu-h .upload-dir{transition:background-color .3s,transform .3s}div.menu-h .upload .icon,div.menu-h .upload-dir .icon{fill:#ffffff;width:24px;height:24px}div.menu-h .upload .icon:hover,div.menu-h .upload-dir .icon:hover{fill:#33e9c5}div.menu-h .log{font-size:14px!important;font-weight:400!important;background:#992900!important}div.menu-h .log:hover{background:#cc3700!important}div.menu-h .log.active{background:#0d7661!important}div.menu-h .log.active:hover{background:#12a487!important}div.menu-h div.menu-box{position:fixed;top:5vh;left:-2000px;height:95vh;width:16vw;transition:left .3s ease-out;padding:1vh 0 0 .5vw;z-index:101;background:#0d0d0d;box-sizing:border-box;outline:0;box-shadow:0 0 0 2px #4d4d4d;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;overflow-y:auto;overflow-x:auto}div.menu-h div.menu-box ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;border-top:1px solid #333}div.menu-h div.menu-box ul li{border-left:1px solid #333;border-right:1px solid #333;border-bottom:1px solid #333}div.menu-h div.menu-box ul li a{color:#fff;font-size:14px;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400;display:block;margin:0;padding:2px 2px 2px 0;text-align:left;text-decoration:none}div.menu-h div.menu-box ul li:hover{text-decoration:underline;background-color:#333;color:#33e9c5}div.menu-h div.menu-box ul a.delete{text-align:center;font-weight:700;font-style:italic;color:#000;background:#b3a80b}div.menu-h div.menu-box ul a.help{text-align:center;font-weight:700;font-style:italic;color:#000;background:#cc3700}div.menu-h div.menu-box ul li.show{background:#000;color:#fff;width:100%;text-align:center;box-sizing:border-box}div.menu-h div.menu-box ul li.show:hover{text-decoration:none}.window-text{position:relative;top:0;left:0;background:#1a1a1a;color:#fff;border:none;padding:0 2px 2px;width:78vw;height:80vh;border-radius:10px;box-sizing:border-box;outline:0;box-shadow:0 0 0 2px #b3a80b;overflow-y:auto;overflow-x:auto}.window-text pre.pre-text{color:#f8f292;white-space:pre-wrap;word-wrap:break-word;font-family:Georigia,"Ties New Roman",serif;font-size:18px;line-height:1.6;padding:2px;margin:0;text-align:left}.window-text div.div-text{color:#f8f292;word-wrap:break-word;font-family:Georigia,"Ties New Roman",serif;font-size:18px;padding:0 2px;margin:0}.window-text div.div-text ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;border-top:1px solid #333}.window-text div.div-text ul li{border-left:1px solid #333;border-right:1px solid #333;border-bottom:1px solid #333}.window-text div.div-text ul li a{color:#fff;font-size:14px;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400;display:block;margin:0;padding:5px 2px 2px 0;text-align:left;text-decoration:none}.window-text div.div-text ul li:hover{text-decoration:underline;background-color:#333;color:#33e9c5}.window-text div.text{font-size:18px;font-weight:400;padding-left:10px;padding-right:10px;margin:0}.window-text div.text pre{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:18px;line-height:1.3;padding:0 5px;margin:0;text-align:left}.window-text div.text .center{text-align:center;font-size:18px;font-weight:700;text-decoration:underline;font-style:italic;color:#e3d50e}.window-text div.text .label{margin:5px 0 5px 10px;font-size:18px;font-weight:700;font-style:italic;color:#e3d50e}.window-text div.text div{font-family:arial,verdana,Helvetica,sans-serif;font-size:18px;font-weight:700;padding-top:0;padding-bottom:0}.window-text div.text div a{background:#000;color:#fff;font-weight:400}.window-text div.text div a:hover{background:#333;color:#fff}.window-text div.text p{font-size:18px;font-weight:400;font-family:arial,verdana,Helvetica,sans-serif;text-align:justify;padding-bottom:9px;padding-right:0;padding-left:10px}.btn-wrapper{width:100%;height:2vw;position:sticky;top:0;padding:0;background:#262626}.btn-wrapper .btn-copy{position:absolute;top:1px;right:5vw;box-sizing:border-box;background:inherit;color:#fff;border:none;cursor:pointer;width:30px;margin:0;padding:0;transition:background-color .3s}.btn-wrapper .btn-copy:hover{background-color:#595959}.btn-wrapper .btn-copy .copy-icon{fill:#e6e6e6;width:20px;height:20px}.btn-wrapper .btn-copy .copy-icon:hover{fill:#33e9c5;background:#404040}.btn-wrapper .btn-close{position:absolute;top:0;right:2vw;margin:0;background-color:transparent;border:none;color:#e6e6e6;font-size:22px;font-weight:700;cursor:pointer;outline:0}.btn-wrapper .btn-close:hover{color:#33e9c5;background:#404040}.msg{box-sizing:border-box;position:fixed;width:300px;height:100px;top:50%;left:50%;transform:translate(-50%,-50%);background-color:#222;color:#ffeb3b;border:2px solid #ffeb3b;border-radius:15px;display:flex;align-items:center;justify-content:center;font-family:Arial,sans-serif;font-size:24px;font-weight:700;text-align:center;z-index:1000;box-shadow:0 4px 8px rgba(0,0,0,.2)}.alert,.confirm{background-color:#303030!important;color:#fff;padding:20px;border-radius:4px;box-shadow:0 2px 4px #00000033!important}.alert .button,.confirm .button{background-color:#37474f!important;color:#fff;border:none;padding:10px 20px;border-radius:4px;cursor:pointer;margin-top:20px}.alert .button:hover,.confirm .button:hover{background-color:#222c31}#ualog_{box-sizing:border-box;width:auto;height:auto;text-align:center;padding:2px;margin:2px 0 0;background:#333;color:#fff;font-size:16px;font-weight:400;border-radius:9px;border:1px solid #999}#ualog_ button{padding:5px;margin:0 5px;font-size:18px;font-weight:700;border:2px solid #888;border-radius:10px;color:#000}#ualog_ button:hover{cursor:pointer;text-decoration:underline}#ualog_ button.close{background:#cc3700}#ualog_ button.close:hover{background:#ff8f66;border-color:#992900}#ualog_ button.clear{background:#b3a80b}#ualog_ button.clear:hover{background:#f5ec62;border-color:#837b08}#ualog_ pre{box-sizing:border-box;width:auto;min-width:400px;max-width:400px;max-height:500px;text-align:left;font-size:16px;font-family:monospace;padding:2px;margin:2px;color:#fff;background:#111;overflow:auto;scrollbar-color:#23eb04 #454444;scrollbar-width:auto;word-wrap:break-word}
|
|
|
1 |
+
a,body,button,div,html,input,label,li,p,span,table,td,ul{padding:0;margin:0;font-family:arial,verdana,Helvetica,sans-serif}.bb0{background:#daee59!important}.bb1{background:#5487fc!important}html{background:#1a1a1a}body{background:#1a1a1a;box-sizing:border-box;min-height:100vh;height:100vh;position:relative;padding:0;margin:0;overflow:hidden;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400}.spinner{z-index:1000;position:absolute;top:70vh;left:50vw;transform:translate(-50%,-50%);cursor:pointer;display:none;align-items:center}.spinner .pulse-icon{width:20px;height:20px;background-color:#ff8c00;border-radius:50%;animation:1.5s ease-in-out infinite pulse}.spinner .stop-message{margin-left:15px;background-color:inherit;color:#8f8a8a;padding:8px 15px;border-radius:10px;font-size:22px;font-weight:700;opacity:1;transition:opacity .3s}.spinner:hover .stop-message{color:#fff;background:#595959;opacity:1}@keyframes pulse{0%{transform:scale(.6);box-shadow:0 0 0 0 rgba(255,140,0,.7)}70%{transform:scale(1.4);box-shadow:0 0 0 20px rgba(255,140,0,0)}100%{transform:scale(.6);box-shadow:0 0 0 0 rgba(255,140,0,0)}}.show-spinner{display:flex}.upload{background-color:#1e1e1e;padding:0 2em 2em;margin:0;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,.5);text-align:center}.upload h4{color:#fff;margin-bottom:1em}.upload form{display:flex;flex-direction:column;align-items:center}.upload form .file{background-color:#121212;border:1px solid #515151;color:#fff;padding:.5em;margin-bottom:1em;border-radius:4px;width:100%;box-sizing:border-box}.upload form .file::file-selector-button{background-color:#0a5f4e;color:#fff;border:none;padding:.5em 1em;border-radius:4px;cursor:pointer}.upload form .file::file-selector-button:hover{background-color:#053128}.upload form button{background-color:#0a5f4e;color:#fff;border:none;padding:.5em 1em;border-radius:4px;cursor:pointer;width:100%;box-sizing:border-box}.upload form button:hover{background-color:#053128}.upload .result{width:100%;background:#000;color:#fff;font-size:15px;font-weight:400;text-align:left}div.container{background:#1a1a1a;box-sizing:border-box;position:relative;top:5vh;left:0;height:95vh;margin:0;padding:0;transition:margin-left .5s;display:flex;flex-direction:column;justify-content:flex-start;align-items:stretch;flex-wrap:nowrap;overflow-y:auto;overflow-x:auto}div.container div.item{box-sizing:border-box;min-height:50px;margin:0;padding:0}div.container div.item1{flex:5;padding:.5vh .5vw 10vh}div.container div.item1 .output-wrapper{background-color:#1a1a1a;border-radius:20px;position:relative;bottom:0;right:0;left:0;width:100%;height:100%;display:flex;flex-direction:row;align-items:flex-start}div.container div.item1 .output-wrapper .text-out{flex:1;box-sizing:border-box;background:#000;color:#fff;border:none;padding:2px;min-width:50vw;height:100%;border-radius:10px;overflow-y:auto;outline:0;box-shadow:0 0 0 2px #4d4d4d}div.container div.item1 .output-wrapper .text-out:hover{box-shadow:0 0 0 2px #17d2ad}div.container div.item1 .output-wrapper .text-out .pre-text{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:20px;line-height:1.5;padding:2px;margin:0;height:100%;box-sizing:border-box;overflow-y:scroll;scroll-behavior:smooth}div.container div.item1 .output-wrapper .text-out .pre-text.copied{background-color:#0d0d0d;color:#61eed2}div.container div.item1 .output-wrapper .text-out .div-text{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:20px;line-height:1.5;padding:2px;margin:0;height:100%;box-sizing:border-box;overflow-y:scroll}div.container div.item1 .output-wrapper .text-out.copied{background-color:#0d0d0d;color:#61eed2}div.container div.item1 .output-actions{display:flex;flex-direction:column;align-items:flex-end;margin-left:.5vw;margin-right:.5vw}div.container div.item1 .output-actions .clear-output,div.container div.item1 .output-actions .copy-output,div.container div.item1 .output-actions .wnd-output{box-sizing:border-box;background-color:#333;color:#fff;border:none;padding:10px;cursor:pointer;border-radius:50%;width:40px;height:40px;display:flex;align-items:center;margin-bottom:5px}div.container div.item1 .output-actions .clear-output:hover,div.container div.item1 .output-actions .copy-output:hover,div.container div.item1 .output-actions .wnd-output:hover{background-color:#595959}div.container div.item1 .output-actions .copy-output{transition:background-color .3s,transform .3s}div.container div.item1 .output-actions .copy-output.copied{background:#33e9c5;transform:scale(1.2)}div.container div.item1 .output-actions .copy-output .copy-icon{fill:#ffffff;width:24px;height:24px}div.container div.item1 .output-actions .copy-output .copy-icon:hover{fill:#33e9c5}div.container div.item1 .output-actions .clear-output,div.container div.item1 .output-actions .wnd-output{transition:background-color .3s,transform .3s}div.container div.item1 .output-actions .clear-output .icon,div.container div.item1 .output-actions .wnd-output .icon{fill:#ffffff;width:24px;height:24px}div.container div.item1 .output-actions .clear-output .icon:hover,div.container div.item1 .output-actions .wnd-output .icon:hover{fill:#33e9c5}:hover{outline:0;caret-color:transparent}textarea:focus{caret-color:auto}div.item2{flex:2;padding:0 .5vw}div.item2 .input-wrapper{background-color:#1a1a1a;border-radius:20px;position:relative;bottom:2vh;right:0;left:0;width:100%;height:100%;display:flex;flex-direction:row;align-items:flex-start}div.item2 .input-wrapper:focus-within .clear-button{display:block}div.item2 .input-wrapper .text-input{flex:1;font-size:20px;font-family:arial,verdana,Helvetica,sans-serif;resize:none;box-sizing:border-box;background:#000;color:#fff;border:none;padding:2px 40px 2px 2px;height:100%;margin-left:5px;border-radius:10px;overflow-y:auto;outline:0;box-shadow:0 0 0 2px #4d4d4d}div.item2 .input-wrapper .text-input:hover{box-shadow:0 0 0 2px #17d2ad}div.item2 .input-wrapper .text-input:focus{box-shadow:0 0 0 2px #ff4500}div.item2 .input-wrapper .clear-button{position:absolute;right:60px;top:19vh;padding:5px;border-radius:50%;background:#333;border:none;font-size:20px;cursor:pointer;color:#ccc;display:none}div.item2 .input-wrapper .clear-button:hover{font-weight:700;background:#595959;color:#fff}div.item2 .input-wrapper .input-actions{display:flex;flex-direction:column;margin-left:.5vw;margin-right:.5vw}div.item2 .input-wrapper .input-actions .clear-input,div.item2 .input-wrapper .input-actions .send-input,div.item2 .input-wrapper .input-actions .send2-input{box-sizing:border-box;background-color:#333;color:#fff;border:none;padding:10px;cursor:pointer;border-radius:50%;width:40px;height:40px;margin-bottom:5px;transition:background-color .3s}div.item2 .input-wrapper .input-actions .send-input{background:#992900}div.item2 .input-wrapper .input-actions .send-input:hover{background:#ff4500}div.item2 .input-wrapper .input-actions .send2-input{background:#0d7661}div.item2 .input-wrapper .input-actions .send2-input:hover{background:#14bb9a}div.item2 .input-wrapper .input-actions .clear-input{background:#333;color:#e6e6e6}div.item2 .input-wrapper .input-actions .clear-input:hover{background:#595959;color:#33e9c5}.menu-open .container{margin-left:16vw}.menu-open .menu-box{left:0!important}div.menu-h{background-color:#1a1a1a;position:fixed;top:0;left:0;width:100vw;height:4.5vh;padding:0;margin:0;outline:0;box-shadow:0 0 0 2px #4d4d4d;z-index:100}div.menu-h .release{background:inherit;color:#ff6a33;font-weight:700;margin-left:50vw;margin-top:.5vh}div.menu-h .menu-btn{appearance:none}div.menu-h .menu-btn:checked+.menu-icon{border:1px solid #333}div.menu-h .menu-btn:checked+.menu-icon .nav-icon{transform:rotate(45deg)}div.menu-h .menu-btn:checked+.menu-icon .nav-icon::before{top:0}div.menu-h .menu-btn:checked+.menu-icon .nav-icon::after{top:0;transform:rotate(90deg)}div.menu-h .menu-icon{box-sizing:border-box;background-color:inherit;display:block;position:absolute;margin-left:2vw;top:0;left:0;width:4vw;height:4.5vh;cursor:pointer;padding:2px;z-index:1}div.menu-h .menu-icon:hover .nav-icon,div.menu-h .menu-icon:hover .nav-icon::after,div.menu-h .menu-icon:hover .nav-icon::before{background-color:#33e9c5}div.menu-h .menu-icon .nav-icon{background-color:#aea7a7;display:block;position:absolute;top:14px;left:0;width:25px;height:2px;transition-duration:.25s}div.menu-h .menu-icon .nav-icon::after,div.menu-h .menu-icon .nav-icon::before{content:"";position:absolute;left:0;background-color:inherit;width:inherit;height:inherit}div.menu-h .menu-icon .nav-icon::before{top:-8px}div.menu-h .menu-icon .nav-icon::after{top:8px}div.menu-h .head-wrapper{position:absolute;top:0;left:5vw;height:4vh;padding:0;margin:0;display:inline-flex;flex-direction:row;flex-wrap:nowrap;align-items:center;justify-content:flex-start}div.menu-h .head-wrapper .help,div.menu-h .head-wrapper .log,div.menu-h .head-wrapper .upload,div.menu-h .head-wrapper .upload-dir{margin-top:2px;margin-left:30px;margin-right:0;padding:5px 5px 0;border:none;cursor:pointer;border-radius:20%;font-size:20px;color:#fff;background:#333;max-height:4vh}div.menu-h .head-wrapper .help:hover,div.menu-h .head-wrapper .log:hover,div.menu-h .head-wrapper .upload-dir:hover,div.menu-h .head-wrapper .upload:hover{background:#595959}div.menu-h .upload,div.menu-h .upload-dir{transition:background-color .3s,transform .3s}div.menu-h .upload .icon,div.menu-h .upload-dir .icon{fill:#ffffff;width:24px;height:24px}div.menu-h .upload .icon:hover,div.menu-h .upload-dir .icon:hover{fill:#33e9c5}div.menu-h .log{font-size:14px!important;font-weight:400!important;background:#992900!important}div.menu-h .log:hover{background:#cc3700!important}div.menu-h .log.active{background:#0d7661!important}div.menu-h .log.active:hover{background:#12a487!important}div.menu-h div.menu-box{position:fixed;top:5vh;left:-2000px;height:95vh;width:16vw;transition:left .3s ease-out;padding:1vh 0 0 .5vw;z-index:101;background:#0d0d0d;box-sizing:border-box;outline:0;box-shadow:0 0 0 2px #4d4d4d;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;overflow-y:auto;overflow-x:auto}div.menu-h div.menu-box ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;border-top:1px solid #333}div.menu-h div.menu-box ul li{border-left:1px solid #333;border-right:1px solid #333;border-bottom:1px solid #333}div.menu-h div.menu-box ul li a{color:#fff;font-size:14px;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400;display:block;margin:0;padding:2px 2px 2px 0;text-align:left;text-decoration:none}div.menu-h div.menu-box ul li:hover{text-decoration:underline;background-color:#333;color:#33e9c5}div.menu-h div.menu-box ul a.delete{text-align:center;font-weight:700;font-style:italic;color:#000;background:#b3a80b}div.menu-h div.menu-box ul a.help{text-align:center;font-weight:700;font-style:italic;color:#000;background:#cc3700}div.menu-h div.menu-box ul li.show{background:#000;color:#fff;width:100%;text-align:center;box-sizing:border-box}div.menu-h div.menu-box ul li.show:hover{text-decoration:none}.window-text{position:relative;top:0;left:0;background:#1a1a1a;color:#fff;border:none;padding:0 2px 2px;width:78vw;height:80vh;border-radius:10px;box-sizing:border-box;outline:0;box-shadow:0 0 0 2px #b3a80b;overflow-y:auto;overflow-x:auto}.window-text pre.pre-text{color:#f8f292;white-space:pre-wrap;word-wrap:break-word;font-family:Georigia,"Ties New Roman",serif;font-size:18px;line-height:1.6;padding:2px;margin:0;text-align:left}.window-text div.div-text{color:#f8f292;word-wrap:break-word;font-family:Georigia,"Ties New Roman",serif;font-size:18px;padding:0 2px;margin:0}.window-text div.div-text ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;border-top:1px solid #333}.window-text div.div-text ul li{border-left:1px solid #333;border-right:1px solid #333;border-bottom:1px solid #333}.window-text div.div-text ul li a{color:#fff;font-size:14px;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400;display:block;margin:0;padding:5px 2px 2px 0;text-align:left;text-decoration:none}.window-text div.div-text ul li:hover{text-decoration:underline;background-color:#333;color:#33e9c5}.window-text div.text{font-size:18px;font-weight:400;padding-left:10px;padding-right:10px;margin:0}.window-text div.text pre{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:18px;line-height:1.3;padding:0 5px;margin:0;text-align:left}.window-text div.text .center{text-align:center;font-size:18px;font-weight:700;text-decoration:underline;font-style:italic;color:#e3d50e}.window-text div.text .label{margin:5px 0 5px 10px;font-size:18px;font-weight:700;font-style:italic;color:#e3d50e}.window-text div.text div{font-family:arial,verdana,Helvetica,sans-serif;font-size:18px;font-weight:700;padding-top:0;padding-bottom:0}.window-text div.text div a{background:#000;color:#fff;font-weight:400}.window-text div.text div a:hover{background:#333;color:#fff}.window-text div.text p{font-size:18px;font-weight:400;font-family:arial,verdana,Helvetica,sans-serif;text-align:justify;padding-bottom:9px;padding-right:0;padding-left:10px}.btn-wrapper{width:100%;height:2vw;position:sticky;top:0;padding:0;background:#262626}.btn-wrapper .btn-copy{position:absolute;top:1px;right:5vw;box-sizing:border-box;background:inherit;color:#fff;border:none;cursor:pointer;width:30px;margin:0;padding:0;transition:background-color .3s}.btn-wrapper .btn-copy:hover{background-color:#595959}.btn-wrapper .btn-copy .copy-icon{fill:#e6e6e6;width:20px;height:20px}.btn-wrapper .btn-copy .copy-icon:hover{fill:#33e9c5;background:#404040}.btn-wrapper .btn-close{position:absolute;top:0;right:2vw;margin:0;background-color:transparent;border:none;color:#e6e6e6;font-size:22px;font-weight:700;cursor:pointer;outline:0}.btn-wrapper .btn-close:hover{color:#33e9c5;background:#404040}.msg{box-sizing:border-box;position:fixed;width:300px;height:100px;top:50%;left:50%;transform:translate(-50%,-50%);background-color:#222;color:#ffeb3b;border:2px solid #ffeb3b;border-radius:15px;display:flex;align-items:center;justify-content:center;font-family:Arial,sans-serif;font-size:24px;font-weight:700;text-align:center;z-index:1000;box-shadow:0 4px 8px rgba(0,0,0,.2)}.alert,.confirm{background-color:#303030!important;color:#fff;padding:20px;border-radius:4px;box-shadow:0 2px 4px #00000033!important}.alert .button,.confirm .button{background-color:#37474f!important;color:#fff;border:none;padding:10px 20px;border-radius:4px;cursor:pointer;margin-top:20px}.alert .button:hover,.confirm .button:hover{background-color:#222c31}#ualog_{box-sizing:border-box;width:auto;height:auto;text-align:center;padding:2px;margin:2px 0 0;background:#333;color:#fff;font-size:16px;font-weight:400;border-radius:9px;border:1px solid #999}#ualog_ button{padding:5px;margin:0 5px;font-size:18px;font-weight:700;border:2px solid #888;border-radius:10px;color:#000}#ualog_ button:hover{cursor:pointer;text-decoration:underline}#ualog_ button.close{background:#cc3700}#ualog_ button.close:hover{background:#ff8f66;border-color:#992900}#ualog_ button.clear{background:#b3a80b}#ualog_ button.clear:hover{background:#f5ec62;border-color:#837b08}#ualog_ pre{box-sizing:border-box;width:auto;min-width:400px;max-width:400px;max-height:500px;text-align:left;font-size:16px;font-family:monospace;padding:2px;margin:2px;color:#fff;background:#111;overflow:auto;scrollbar-color:#23eb04 #454444;scrollbar-width:auto;word-wrap:break-word}
|
static/javascript/rag_cleaner.js
CHANGED
@@ -1,115 +1,97 @@
|
|
1 |
/** @format */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g;
|
5 |
-
return txt.replace(charsRm, "");
|
6 |
-
};
|
7 |
-
|
8 |
-
const replaceChars = (txt) => {
|
9 |
-
const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
|
10 |
-
return txt.replace(charsSrp, " ");
|
11 |
-
};
|
12 |
-
|
13 |
-
const removeTag = (txt) => {
|
14 |
-
return txt.replace(/<<</g, "").replace(/>>>/g, "").replace(/<<|>>/g, "");
|
15 |
-
};
|
16 |
-
|
17 |
-
const ALLOWED_CHARS = /\w\sàèéìòùÀÈÉÌÒÙáéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛçÇñÑ.,;:!?\'"()-/;
|
18 |
-
|
19 |
-
const cleanDoc = (txt) => {
|
20 |
try {
|
21 |
txt = removeTag(txt);
|
22 |
-
|
23 |
-
txt =
|
24 |
-
// Rimuove
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
// Uniforma i caratteri di quotazione
|
29 |
txt = txt.replace(/“/g, '"').replace(/”/g, '"');
|
30 |
-
// Rimuove caratteri speciali non comuni mantenendo i caratteri accentati e punteggiatura
|
31 |
-
txt = txt.replace(new RegExp(`[^${ALLOWED_CHARS.source}]`, "g"), " ");
|
32 |
// Rimuove spazi prima della punteggiatura
|
33 |
txt = txt.replace(/ +([.,;:!?])/g, "$1");
|
|
|
|
|
|
|
34 |
// Rimuove spazi multipli
|
35 |
txt = txt.replace(/ +/g, " ");
|
36 |
return txt.trim();
|
37 |
} catch (e) {
|
38 |
console.error(e);
|
39 |
-
return "Errore di codifica
|
40 |
}
|
41 |
-
}
|
42 |
|
43 |
-
|
44 |
try {
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
txt = txt.replace(
|
51 |
-
//
|
52 |
-
txt = txt.replace(
|
53 |
-
//
|
54 |
-
txt = txt.replace(
|
55 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
txt = txt.replace(/ +/g, " ");
|
57 |
return txt.trim();
|
58 |
} catch (e) {
|
59 |
console.error(e);
|
60 |
-
return
|
61 |
}
|
62 |
-
}
|
63 |
|
64 |
-
|
65 |
-
txt = removeTag(txt);
|
66 |
-
// Rimuove gli spazi bianchi iniziali e finali
|
67 |
-
text = text.trim();
|
68 |
-
// Sostituisce le sequenze di più di due newline con due newline
|
69 |
-
text = text.replace(/\n{3,}/g, "\n\n");
|
70 |
-
// Rimuove gli spazi bianchi extra all'inizio di ogni riga
|
71 |
-
text = text.replace(/^\s+/gm, "");
|
72 |
// Formatta gli elenchi puntati per una migliore leggibilità
|
73 |
-
|
74 |
// Formatta gli elenchi numerati per una migliore leggibilità
|
75 |
-
|
76 |
// Aggiunge una riga vuota prima e dopo i blocchi di codice
|
77 |
-
|
78 |
// Aggiunge un'andata a capo dopo ogni punto, eccetto quando seguito da newline o fine stringa
|
79 |
-
|
|
|
|
|
80 |
// Rimuove gli spazi bianchi extra alla fine di ogni riga
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
// function list2text(docList) {
|
86 |
-
// const docDict = {};
|
87 |
-
|
88 |
-
// function getLabel(txt) {
|
89 |
-
// const match = txt.match(/<<<(.*?)>>>/);
|
90 |
-
// return match ? match[1] : null;
|
91 |
-
// }
|
92 |
-
|
93 |
-
// for (let doc of docList) {
|
94 |
-
// const docName = getLabel(doc);
|
95 |
-
// // const content = doc.replace(/<<<.*?>>>/g, ''); //TODO
|
96 |
-
// const content = doc.replace(/<<<.*?>>>/, "");
|
97 |
-
// if (docName in docDict) {
|
98 |
-
// docDict[docName] += `\n ${content}`;
|
99 |
-
// } else {
|
100 |
-
// docDict[docName] = content;
|
101 |
-
// }
|
102 |
-
// }
|
103 |
-
// const lst = [];
|
104 |
-
// for (let [docName, content] of Object.entries(docDict)) {
|
105 |
-
// lst.push(`Documento: ${docName}.\n${content}`);
|
106 |
-
// }
|
107 |
-
// return lst.join("\n\n");
|
108 |
-
// }
|
109 |
|
110 |
// <<<doc_name>>> => Documento: doc_name
|
111 |
-
function subResponseDOcTag(txt) {
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
}
|
|
|
1 |
/** @format */
|
2 |
+
function removeTag(txt) {
|
3 |
+
txt = txt.replace(/<<</g, "").replace(/>>>/g, "");
|
4 |
+
txt = txt.replace(/<</g, "").replace(/>>/g, "");
|
5 |
+
return txt;
|
6 |
+
}
|
7 |
+
function uniteBrokenWords(txt) {
|
8 |
+
const regex = /-\n/g;
|
9 |
+
const unitedText = txt.replace(regex, "");
|
10 |
+
return unitedText;
|
11 |
+
}
|
12 |
|
13 |
+
function cleanDoc(txt) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
try {
|
15 |
txt = removeTag(txt);
|
16 |
+
//unisce le parole spezzate a di fine riga
|
17 |
+
txt = txt.replace(/-\n/g, "");
|
18 |
+
// Rimuove caratteri non stampabili specifici
|
19 |
+
const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g;
|
20 |
+
txt = txt.replace(charsRm, "");
|
21 |
+
// Sostituisce spazi non standard e altri caratteri con uno spazio
|
22 |
+
const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
|
23 |
+
txt = txt.replace(charsSrp, " ");
|
24 |
+
// Mantieni le sequenze di escape comuni
|
25 |
+
txt = txt.replace(/\\([nrtfb])/g, "$1");
|
26 |
+
// Mantieni le sequenze Unicode
|
27 |
+
txt = txt.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g, "$1");
|
28 |
+
// Mantieni i backslash nei path di file
|
29 |
+
txt = txt.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g, "\\\\$1");
|
30 |
+
// Rimuovi tutti gli altri backslash
|
31 |
+
txt = txt.replace(/\\/g, "");
|
32 |
// Uniforma i caratteri di quotazione
|
33 |
txt = txt.replace(/“/g, '"').replace(/”/g, '"');
|
|
|
|
|
34 |
// Rimuove spazi prima della punteggiatura
|
35 |
txt = txt.replace(/ +([.,;:!?])/g, "$1");
|
36 |
+
// Rimuove linee vuote multiple
|
37 |
+
txt = txt.replace(/\n\s*\n/g, "\n\n");
|
38 |
+
txt = txt.replace(/\n{3,}/g, "\n\n");
|
39 |
// Rimuove spazi multipli
|
40 |
txt = txt.replace(/ +/g, " ");
|
41 |
return txt.trim();
|
42 |
} catch (e) {
|
43 |
console.error(e);
|
44 |
+
return "Errore di codifica del documento";
|
45 |
}
|
46 |
+
}
|
47 |
|
48 |
+
function cleanResponse(txt) {
|
49 |
try {
|
50 |
+
// Rimuove caratteri non stampabili specifici
|
51 |
+
const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g;
|
52 |
+
txt = txt.replace(charsRm, "");
|
53 |
+
// Sostituisce spazi non standard e altri caratteri con uno spazio
|
54 |
+
const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
|
55 |
+
txt = txt.replace(charsSrp, " ");
|
56 |
+
// Mantieni le sequenze di escape comuni
|
57 |
+
txt = txt.replace(/\\([nrtfb])/g, "$1");
|
58 |
+
// Mantieni le sequenze Unicode
|
59 |
+
txt = txt.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g, "$1");
|
60 |
+
// Mantieni i backslash nei path di file
|
61 |
+
txt = txt.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g, "\\\\$1");
|
62 |
+
// Rimuovi tutti gli altri backslash
|
63 |
+
txt = txt.replace(/\\/g, "");
|
64 |
+
// Sostituisce le sequenze di più di due newline con due newline
|
65 |
+
txt = txt.replace(/\n{3,}/g, "\n\n");
|
66 |
+
// unifica spazi multipli
|
67 |
txt = txt.replace(/ +/g, " ");
|
68 |
return txt.trim();
|
69 |
} catch (e) {
|
70 |
console.error(e);
|
71 |
+
return `Errore di codifica nella risposta\n${e}`;
|
72 |
}
|
73 |
+
}
|
74 |
|
75 |
+
function cleanOut(txt) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
// Formatta gli elenchi puntati per una migliore leggibilità
|
77 |
+
// txt = txt.replace(/^(\s*[-*•])(\s*)/gm, "\n$1 ");
|
78 |
// Formatta gli elenchi numerati per una migliore leggibilità
|
79 |
+
// txt = txt.replace(/^(\s*\d+\.)(\s*)/gm, "\n$1 ");
|
80 |
// Aggiunge una riga vuota prima e dopo i blocchi di codice
|
81 |
+
// txt = txt.replace(/(```[\s\S]*?```)/g, "\n\n$1\n\n");
|
82 |
// Aggiunge un'andata a capo dopo ogni punto, eccetto quando seguito da newline o fine stringa
|
83 |
+
// txt = txt.replace(/\.(?!\n|$)/g, ".\n");
|
84 |
+
// Sostituisce le sequenze di più di due newline con due newline
|
85 |
+
txt = txt.replace(/\n{3,}/g, "\n\n");
|
86 |
// Rimuove gli spazi bianchi extra alla fine di ogni riga
|
87 |
+
// txt = txt.replace(/ +/g, " ");
|
88 |
+
// txt = txt.replace(/\s+$/gm, "");
|
89 |
+
return txt;
|
90 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
|
92 |
// <<<doc_name>>> => Documento: doc_name
|
93 |
+
// function subResponseDOcTag(txt) {
|
94 |
+
// const regex = /<<<(.*?)>>>/;
|
95 |
+
// const result = txt.replace(regex, (match, p1) => `Documento: ${p1}`);
|
96 |
+
// return result;
|
97 |
+
// }
|
static/javascript/rag_data_mgr.js
CHANGED
@@ -118,8 +118,8 @@ const DataMgr = {
|
|
118 |
}
|
119 |
Rag.ragQuery = "";
|
120 |
Rag.ragContext = "";
|
121 |
-
Rag.
|
122 |
-
Rag.
|
123 |
Rag.prompts = [];
|
124 |
ThreadMgr.rows = [];
|
125 |
},
|
|
|
118 |
}
|
119 |
Rag.ragQuery = "";
|
120 |
Rag.ragContext = "";
|
121 |
+
Rag.ragAnswer = "";
|
122 |
+
Rag.answers= [];
|
123 |
Rag.prompts = [];
|
124 |
ThreadMgr.rows = [];
|
125 |
},
|
static/javascript/rag_http.js
CHANGED
@@ -1,7 +1,6 @@
|
|
1 |
/** @format */
|
2 |
"use strict";
|
3 |
|
4 |
-
|
5 |
const model_name = "mistralai/Mistral-7B-Instruct-v0.3";
|
6 |
// const model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1";
|
7 |
// const model_name = "mistralai/Mixtral-8x22B-Instruct-v0.1"
|
@@ -37,6 +36,46 @@ async function requestGet(url) {
|
|
37 |
const ERROR_TOKENS = "ERROR_TOKENS";
|
38 |
const TIMEOUT_ERROR = "TIMEOUT_ERROR";
|
39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
const HfRequest = {
|
41 |
controller: null,
|
42 |
isCancelled: false,
|
@@ -45,12 +84,12 @@ const HfRequest = {
|
|
45 |
async post(payload, timeout = 50000) {
|
46 |
this.isCancelled = false;
|
47 |
this.controller = new AbortController();
|
48 |
-
|
49 |
try {
|
50 |
const timeoutId = setTimeout(() => {
|
51 |
this.controller.abort();
|
52 |
}, timeout);
|
53 |
-
|
54 |
method: "POST",
|
55 |
headers: {
|
56 |
Authorization: `Bearer ${tm}`,
|
@@ -63,20 +102,20 @@ const HfRequest = {
|
|
63 |
if (this.isCancelled) return null;
|
64 |
const data = await response.json();
|
65 |
if (!response.ok) {
|
66 |
-
const errorType =
|
67 |
-
const errorInfo =
|
68 |
throw new Error(errorInfo);
|
69 |
}
|
70 |
-
const
|
71 |
-
if (
|
72 |
-
const errorInfo =
|
73 |
throw new Error(errorInfo);
|
74 |
}
|
75 |
return data[0].generated_text.trim();
|
76 |
} catch (error) {
|
77 |
if (this.isCancelled) return null;
|
78 |
if (error.name === "AbortError") {
|
79 |
-
const errorInfo =
|
80 |
throw new Error(errorInfo);
|
81 |
}
|
82 |
throw error;
|
@@ -88,55 +127,40 @@ const HfRequest = {
|
|
88 |
this.controller.abort();
|
89 |
}
|
90 |
},
|
91 |
-
checkError(status, data) {
|
92 |
-
let errorType;
|
93 |
-
if (status >= 500) {
|
94 |
-
errorType = "SERVER_ERROR";
|
95 |
-
} else if (status >= 400 && status < 500) {
|
96 |
-
if (typeof data === "object" && data.error_type === "validation") {
|
97 |
-
if (data.error.includes("tokens")) {
|
98 |
-
errorType = ERROR_TOKENS;
|
99 |
-
} else {
|
100 |
-
errorType = "ERROR_VALIDATION";
|
101 |
-
}
|
102 |
-
} else {
|
103 |
-
errorType = "CLIENT_ERROR";
|
104 |
-
}
|
105 |
-
} else {
|
106 |
-
errorType = "UNKNOWN_ERROR";
|
107 |
-
}
|
108 |
-
return errorType;
|
109 |
-
},
|
110 |
-
isInvalidResponse(data) {
|
111 |
-
if (!data || !Array.isArray(data) || data.length === 0) {
|
112 |
-
return "INVALID_DATA";
|
113 |
-
}
|
114 |
-
if (!data[0].generated_text) {
|
115 |
-
return "MISSING_GENERATED_TEXT";
|
116 |
-
}
|
117 |
-
return null;
|
118 |
-
},
|
119 |
-
createErrorInfo(status, statusText, msg, errorType) {
|
120 |
-
const err = {
|
121 |
-
status: status,
|
122 |
-
statusText: statusText,
|
123 |
-
errorType: errorType,
|
124 |
-
message: msg || "Errore sconosciuto",
|
125 |
-
};
|
126 |
-
return JSON.stringify(err);
|
127 |
-
},
|
128 |
};
|
129 |
|
130 |
-
function
|
131 |
-
|
132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
}
|
134 |
|
135 |
function errorToText(err) {
|
136 |
-
|
137 |
-
|
|
|
|
|
138 |
Status: ${j.status}
|
139 |
Status Text: ${j.statusText}
|
140 |
Error Type: ${j.errorType}
|
141 |
Message: ${j.message}`;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
}
|
|
|
1 |
/** @format */
|
2 |
"use strict";
|
3 |
|
|
|
4 |
const model_name = "mistralai/Mistral-7B-Instruct-v0.3";
|
5 |
// const model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1";
|
6 |
// const model_name = "mistralai/Mixtral-8x22B-Instruct-v0.1"
|
|
|
36 |
const ERROR_TOKENS = "ERROR_TOKENS";
|
37 |
const TIMEOUT_ERROR = "TIMEOUT_ERROR";
|
38 |
|
39 |
+
const getErrorType = (status, data) => {
|
40 |
+
let errorType;
|
41 |
+
if (status >= 500) {
|
42 |
+
errorType = "SERVER_ERROR";
|
43 |
+
} else if (status >= 400 && status < 500) {
|
44 |
+
if (typeof data === "object" && data.error_type === "validation") {
|
45 |
+
if (data.error.includes("tokens")) {
|
46 |
+
errorType = ERROR_TOKENS;
|
47 |
+
} else {
|
48 |
+
errorType = "ERROR_VALIDATION";
|
49 |
+
}
|
50 |
+
} else {
|
51 |
+
errorType = "CLIENT_ERROR";
|
52 |
+
}
|
53 |
+
} else {
|
54 |
+
errorType = "UNKNOWN_ERROR";
|
55 |
+
}
|
56 |
+
return errorType;
|
57 |
+
};
|
58 |
+
|
59 |
+
const checkResponse = (data) => {
|
60 |
+
if (!data || !Array.isArray(data) || data.length === 0) {
|
61 |
+
return "INVALID_DATA";
|
62 |
+
}
|
63 |
+
if (!data[0].generated_text) {
|
64 |
+
return "MISSING_GENERATED_TEXT";
|
65 |
+
}
|
66 |
+
return "ok";
|
67 |
+
};
|
68 |
+
|
69 |
+
const createErrorInfo = (status, statusText, msg, errorType) => {
|
70 |
+
const err = {
|
71 |
+
status: status,
|
72 |
+
statusText: statusText,
|
73 |
+
errorType: errorType,
|
74 |
+
message: msg || "Errore sconosciuto",
|
75 |
+
};
|
76 |
+
return JSON.stringify(err);
|
77 |
+
};
|
78 |
+
|
79 |
const HfRequest = {
|
80 |
controller: null,
|
81 |
isCancelled: false,
|
|
|
84 |
async post(payload, timeout = 50000) {
|
85 |
this.isCancelled = false;
|
86 |
this.controller = new AbortController();
|
87 |
+
let response;
|
88 |
try {
|
89 |
const timeoutId = setTimeout(() => {
|
90 |
this.controller.abort();
|
91 |
}, timeout);
|
92 |
+
response = await fetch(`${this.baseUrl}/${model_name}`, {
|
93 |
method: "POST",
|
94 |
headers: {
|
95 |
Authorization: `Bearer ${tm}`,
|
|
|
102 |
if (this.isCancelled) return null;
|
103 |
const data = await response.json();
|
104 |
if (!response.ok) {
|
105 |
+
const errorType = getErrorType(response.status, data);
|
106 |
+
const errorInfo = createErrorInfo(response.status, response.statusText, data.error, errorType);
|
107 |
throw new Error(errorInfo);
|
108 |
}
|
109 |
+
const okResp = checkResponse(data);
|
110 |
+
if (okResp !== "ok") {
|
111 |
+
const errorInfo = createErrorInfo(response.status, response.statusText, data.error, okResp);
|
112 |
throw new Error(errorInfo);
|
113 |
}
|
114 |
return data[0].generated_text.trim();
|
115 |
} catch (error) {
|
116 |
if (this.isCancelled) return null;
|
117 |
if (error.name === "AbortError") {
|
118 |
+
const errorInfo = createErrorInfo(0, "Timeout", "La richiesta è scaduta", TIMEOUT_ERROR);
|
119 |
throw new Error(errorInfo);
|
120 |
}
|
121 |
throw error;
|
|
|
127 |
this.controller.abort();
|
128 |
}
|
129 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
};
|
131 |
|
132 |
+
function getErrorInfo(error) {
|
133 |
+
let js = {};
|
134 |
+
try {
|
135 |
+
js = JSON.parse(error.message);
|
136 |
+
} catch (err) {
|
137 |
+
const msg = `getErrorInfo\n${error}`;
|
138 |
+
console.error(msg);
|
139 |
+
js = {
|
140 |
+
status: "0",
|
141 |
+
statusText: "status_errorInof",
|
142 |
+
errorType: "UNKNOWN_ERROR_errorInfo",
|
143 |
+
message: msg,
|
144 |
+
};
|
145 |
+
} finally {
|
146 |
+
return js;
|
147 |
+
}
|
148 |
}
|
149 |
|
150 |
function errorToText(err) {
|
151 |
+
let s;
|
152 |
+
try {
|
153 |
+
const j = JSON.parse(err.message);
|
154 |
+
s = `Error:
|
155 |
Status: ${j.status}
|
156 |
Status Text: ${j.statusText}
|
157 |
Error Type: ${j.errorType}
|
158 |
Message: ${j.message}`;
|
159 |
+
} catch (err) {
|
160 |
+
const msg = `errorToText\n${err}`;
|
161 |
+
console.error(msg);
|
162 |
+
s = `${err}`;
|
163 |
+
} finally {
|
164 |
+
return s;
|
165 |
+
}
|
166 |
}
|
static/javascript/rag_mgr.js
CHANGED
@@ -24,6 +24,18 @@ const PROMPT_DECR = 1024 * 2;
|
|
24 |
|
25 |
const TIMEOUT = 60000;
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
const truncInput = (txt, decr) => {
|
28 |
const tl = txt.length;
|
29 |
const lim = tl - decr;
|
@@ -31,6 +43,12 @@ const truncInput = (txt, decr) => {
|
|
31 |
return s;
|
32 |
};
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
const getPartSize = (doc, prompt, decr) => {
|
35 |
const limitWIthPoint = (s, free_len) => {
|
36 |
const idx = s.indexOf(".", free_len);
|
@@ -57,15 +75,15 @@ const getPartDoc = (pRgt, partSize) => {
|
|
57 |
return [pLft, pRgt];
|
58 |
};
|
59 |
|
60 |
-
const ragLog = (msg,
|
61 |
const maxl = MAX_PROMPT_LENGTH;
|
62 |
-
const
|
63 |
return acc + cur.length;
|
64 |
}, 0);
|
65 |
-
let s = `${msg} mx:${maxl} lft:${
|
66 |
xlog(s);
|
67 |
-
|
68 |
-
UaLog.log(
|
69 |
};
|
70 |
|
71 |
const Rag = {
|
@@ -74,9 +92,9 @@ const Rag = {
|
|
74 |
//query usata per creare la lista delle rispste
|
75 |
ragQuery: "",
|
76 |
// risposta finale alla qury contetso
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
prompts: [],
|
81 |
doc: "",
|
82 |
doc_part: "",
|
@@ -88,7 +106,7 @@ const Rag = {
|
|
88 |
const js = {
|
89 |
context: this.ragContext,
|
90 |
ragquery: this.ragQuery,
|
91 |
-
|
92 |
};
|
93 |
UaDb.saveJson(ID_RAG, js);
|
94 |
UaDb.saveArray(ID_THREAD, ThreadMgr.rows);
|
@@ -97,14 +115,14 @@ const Rag = {
|
|
97 |
const js = UaDb.readJson(ID_RAG);
|
98 |
this.ragContext = js.context || "";
|
99 |
this.ragQuery = js.ragquery || "";
|
100 |
-
this.
|
101 |
ThreadMgr.rows = UaDb.readArray(ID_THREAD);
|
102 |
},
|
103 |
saveRespToDb() {
|
104 |
-
UaDb.saveArray(ID_RESPONSES, this.
|
105 |
},
|
106 |
readRespsFromDb() {
|
107 |
-
this.
|
108 |
},
|
109 |
// addPrompt(p) {
|
110 |
// this.prompts.push(p);
|
@@ -115,8 +133,10 @@ const Rag = {
|
|
115 |
DataMgr.readDbDocNames();
|
116 |
DataMgr.readDbDocs();
|
117 |
this.ragQuery = query;
|
|
|
118 |
let ndoc = 0;
|
119 |
try {
|
|
|
120 |
for (let i = 0; i < DataMgr.docs.length; i++) {
|
121 |
let doc = DataMgr.docs[i];
|
122 |
if (doc.trim() == "") continue;
|
@@ -125,13 +145,13 @@ const Rag = {
|
|
125 |
xlog(`${docName} (${doc_entire_len}) `);
|
126 |
UaLog.log(`${docName} (${doc_entire_len}) `);
|
127 |
++ndoc;
|
128 |
-
let npart =
|
129 |
let decr = 0;
|
130 |
let prompt = "";
|
131 |
let lft = "";
|
132 |
let rgt = "";
|
133 |
-
let
|
134 |
-
let
|
135 |
|
136 |
while (true) {
|
137 |
let partSize = getPartSize(doc, promptDoc("", query, ""), decr);
|
@@ -139,117 +159,124 @@ const Rag = {
|
|
139 |
break;
|
140 |
}
|
141 |
[lft, rgt] = getPartDoc(doc, partSize);
|
142 |
-
ragLog(`${ndoc},${npart
|
143 |
prompt = promptDoc(lft, query, docName);
|
144 |
const payload = getPayloadDoc(prompt);
|
145 |
try {
|
146 |
-
|
147 |
-
if (!
|
148 |
} catch (err) {
|
149 |
-
|
|
|
150 |
if (ei.errorType === ERROR_TOKENS) {
|
151 |
-
UaLog.log(`Error tokens Doc ${
|
152 |
-
console.error(`Error tokens. Doc ${prompt.length}`);
|
153 |
decr += PROMPT_DECR;
|
154 |
continue;
|
|
|
|
|
|
|
|
|
|
|
155 |
} else {
|
156 |
-
console.error(err);
|
157 |
throw err;
|
158 |
}
|
159 |
-
}
|
160 |
npart++;
|
|
|
161 |
doc = rgt;
|
162 |
-
|
163 |
-
|
164 |
-
const s = `DOCUMENTO : ${docName}\n${
|
165 |
-
this.
|
166 |
} // end while
|
167 |
-
|
168 |
//implemntare build context
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
}
|
195 |
}
|
196 |
-
|
197 |
-
|
198 |
-
} //end
|
199 |
-
UaLog.log(`context ${
|
200 |
-
|
201 |
-
|
202 |
-
this.
|
203 |
} // end for document
|
204 |
} catch (err) {
|
205 |
console.error(err);
|
206 |
throw err;
|
207 |
}
|
208 |
-
|
209 |
-
this.ragContext = this.contextAnswers.join("\n");
|
210 |
this.saveToDb();
|
211 |
|
212 |
// query finale utilizza context
|
213 |
{
|
214 |
-
let
|
215 |
let context = this.ragContext;
|
216 |
try {
|
217 |
while (true) {
|
218 |
let prompt = promptWithContext(context, query);
|
219 |
const payload = getPayloadWithContext(prompt);
|
220 |
try {
|
221 |
-
|
222 |
-
if (!
|
223 |
} catch (err) {
|
224 |
-
|
|
|
225 |
if (ei.errorType === ERROR_TOKENS) {
|
226 |
-
UaLog.log(`Error tokens with
|
227 |
-
console.error(`Error tokens context. Doc ${prompt.length}`);
|
228 |
context = truncInput(context, PROMPT_DECR);
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
continue;
|
230 |
} else {
|
231 |
-
console.error(err);
|
232 |
throw err;
|
233 |
}
|
234 |
}
|
235 |
break;
|
236 |
}
|
237 |
-
|
238 |
-
this.
|
239 |
this.saveRespToDb();
|
240 |
ThreadMgr.init();
|
241 |
this.saveToDb();
|
242 |
-
UaLog.log(`Risposta (${
|
243 |
} catch (err) {
|
244 |
console.error(err);
|
245 |
-
|
246 |
throw err;
|
247 |
} finally {
|
248 |
-
return
|
249 |
}
|
250 |
} // end query
|
251 |
},
|
252 |
-
|
253 |
// thread
|
254 |
async requestContext(query) {
|
255 |
let text = "";
|
@@ -270,14 +297,17 @@ const Rag = {
|
|
270 |
text = await HfRequest.post(payload, TIMEOUT);
|
271 |
if (!text) return "";
|
272 |
} catch (err) {
|
273 |
-
|
|
|
274 |
if (ei.errorType === ERROR_TOKENS) {
|
275 |
-
UaLog.log(`Error tokens Thread Init
|
276 |
-
console.error(`Error tokens Thread Init. ${prompt.length}`);
|
277 |
thread = truncInput(thread, PROMPT_DECR);
|
|
|
|
|
|
|
|
|
278 |
continue;
|
279 |
} else {
|
280 |
-
console.error(err);
|
281 |
throw err;
|
282 |
}
|
283 |
} //end catch
|
@@ -306,14 +336,16 @@ const Rag = {
|
|
306 |
text = await HfRequest.post(payload, TIMEOUT);
|
307 |
if (!text) return "";
|
308 |
} catch (err) {
|
309 |
-
|
|
|
310 |
if (ei.errorType === ERROR_TOKENS) {
|
311 |
UaLog.log(`Error tokens Thread ${prompt.length}`);
|
312 |
-
console.error(`Error tokens Thread. ${prompt.length}`);
|
313 |
thread = truncInput(thread, PROMPT_DECR);
|
314 |
continue;
|
|
|
|
|
|
|
315 |
} else {
|
316 |
-
console.error(err);
|
317 |
throw err;
|
318 |
}
|
319 |
}
|
@@ -334,15 +366,15 @@ const Rag = {
|
|
334 |
},
|
335 |
};
|
336 |
|
337 |
-
const LLM = "Assistant:";
|
338 |
-
const USER = "User:";
|
339 |
|
340 |
const ThreadMgr = {
|
341 |
rows: [],
|
342 |
init() {
|
343 |
this.rows = [];
|
344 |
-
if (!!Rag.
|
345 |
-
this.add(Rag.ragQuery, Rag.
|
346 |
} else {
|
347 |
this.add("", "");
|
348 |
}
|
@@ -357,9 +389,9 @@ const ThreadMgr = {
|
|
357 |
for (const ua of this.rows) {
|
358 |
const u = ua[0];
|
359 |
const a = ua[1];
|
360 |
-
rows.push(
|
361 |
}
|
362 |
-
return rows.join("")
|
363 |
},
|
364 |
isFirst() {
|
365 |
return this.rows.length < 2;
|
|
|
24 |
|
25 |
const TIMEOUT = 60000;
|
26 |
|
27 |
+
function wait(seconds) {
|
28 |
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
29 |
+
}
|
30 |
+
|
31 |
+
async function example() {
|
32 |
+
console.log("Inizio attesa...");
|
33 |
+
await wait(5); // Attende 5 secondi
|
34 |
+
console.log("Fine attesa!");
|
35 |
+
}
|
36 |
+
|
37 |
+
example();
|
38 |
+
|
39 |
const truncInput = (txt, decr) => {
|
40 |
const tl = txt.length;
|
41 |
const lim = tl - decr;
|
|
|
43 |
return s;
|
44 |
};
|
45 |
|
46 |
+
//setta il prompt al limite massimo
|
47 |
+
const setMaxLen = (s) => {
|
48 |
+
const lim = MAX_PROMPT_LENGTH - 1000;
|
49 |
+
return s.substring(0, lim);
|
50 |
+
};
|
51 |
+
|
52 |
const getPartSize = (doc, prompt, decr) => {
|
53 |
const limitWIthPoint = (s, free_len) => {
|
54 |
const idx = s.indexOf(".", free_len);
|
|
|
75 |
return [pLft, pRgt];
|
76 |
};
|
77 |
|
78 |
+
const ragLog = (msg, lftL, rgtL, answers) => {
|
79 |
const maxl = MAX_PROMPT_LENGTH;
|
80 |
+
const rspsL = answers.reduce((acc, cur) => {
|
81 |
return acc + cur.length;
|
82 |
}, 0);
|
83 |
+
let s = `${msg} mx:${maxl} lft:${lftL} rgt:${rgtL} arr:${rspsL}`;
|
84 |
xlog(s);
|
85 |
+
const row = formatRow([msg, lftL, rgtL, rspsL], [8, -7, -7, -7]);
|
86 |
+
UaLog.log(row);
|
87 |
};
|
88 |
|
89 |
const Rag = {
|
|
|
92 |
//query usata per creare la lista delle rispste
|
93 |
ragQuery: "",
|
94 |
// risposta finale alla qury contetso
|
95 |
+
ragAnswer: "",
|
96 |
+
answers: [],
|
97 |
+
docContextLst: [],
|
98 |
prompts: [],
|
99 |
doc: "",
|
100 |
doc_part: "",
|
|
|
106 |
const js = {
|
107 |
context: this.ragContext,
|
108 |
ragquery: this.ragQuery,
|
109 |
+
raganswer: this.ragAnswer,
|
110 |
};
|
111 |
UaDb.saveJson(ID_RAG, js);
|
112 |
UaDb.saveArray(ID_THREAD, ThreadMgr.rows);
|
|
|
115 |
const js = UaDb.readJson(ID_RAG);
|
116 |
this.ragContext = js.context || "";
|
117 |
this.ragQuery = js.ragquery || "";
|
118 |
+
this.ragAnswer = js.raganswer || "";
|
119 |
ThreadMgr.rows = UaDb.readArray(ID_THREAD);
|
120 |
},
|
121 |
saveRespToDb() {
|
122 |
+
UaDb.saveArray(ID_RESPONSES, this.answers);
|
123 |
},
|
124 |
readRespsFromDb() {
|
125 |
+
this.answers = UaDb.readArray(ID_RESPONSES);
|
126 |
},
|
127 |
// addPrompt(p) {
|
128 |
// this.prompts.push(p);
|
|
|
133 |
DataMgr.readDbDocNames();
|
134 |
DataMgr.readDbDocs();
|
135 |
this.ragQuery = query;
|
136 |
+
this.saveToDb();
|
137 |
let ndoc = 0;
|
138 |
try {
|
139 |
+
let j = 1;
|
140 |
for (let i = 0; i < DataMgr.docs.length; i++) {
|
141 |
let doc = DataMgr.docs[i];
|
142 |
if (doc.trim() == "") continue;
|
|
|
145 |
xlog(`${docName} (${doc_entire_len}) `);
|
146 |
UaLog.log(`${docName} (${doc_entire_len}) `);
|
147 |
++ndoc;
|
148 |
+
let npart = 1;
|
149 |
let decr = 0;
|
150 |
let prompt = "";
|
151 |
let lft = "";
|
152 |
let rgt = "";
|
153 |
+
let answer = "";
|
154 |
+
let docAnswersLst = [];
|
155 |
|
156 |
while (true) {
|
157 |
let partSize = getPartSize(doc, promptDoc("", query, ""), decr);
|
|
|
159 |
break;
|
160 |
}
|
161 |
[lft, rgt] = getPartDoc(doc, partSize);
|
162 |
+
ragLog(`${j}) ${ndoc},${npart}`, lft.length, rgt.length, this.answers);
|
163 |
prompt = promptDoc(lft, query, docName);
|
164 |
const payload = getPayloadDoc(prompt);
|
165 |
try {
|
166 |
+
answer = await HfRequest.post(payload, TIMEOUT);
|
167 |
+
if (!answer) return "";
|
168 |
} catch (err) {
|
169 |
+
console.error(`RR1)\n`, err);
|
170 |
+
const ei = getErrorInfo(err);
|
171 |
if (ei.errorType === ERROR_TOKENS) {
|
172 |
+
UaLog.log(`Error tokens Doc ${prompt.length}`);
|
|
|
173 |
decr += PROMPT_DECR;
|
174 |
continue;
|
175 |
+
} else if (ei.errorType === TIMEOUT_ERROR) {
|
176 |
+
UaLog.log(`Error timeout Doc`);
|
177 |
+
wait(5);
|
178 |
+
// UaLog.log(`Error timeout Doc 2`);
|
179 |
+
continue;
|
180 |
} else {
|
|
|
181 |
throw err;
|
182 |
}
|
183 |
+
} //end catch
|
184 |
npart++;
|
185 |
+
j++;
|
186 |
doc = rgt;
|
187 |
+
answer = cleanResponse(answer);
|
188 |
+
docAnswersLst.push(answer);
|
189 |
+
const s = `DOCUMENTO : ${docName}_${npart}\n${answer}`;
|
190 |
+
this.answers.push(s);
|
191 |
} // end while
|
|
|
192 |
//implemntare build context
|
193 |
+
const docAnswersLen = docAnswersLst.length;
|
194 |
+
let docAnswresTxt = docAnswersLst.join("\n\n"); //TODO
|
195 |
+
let docContext = "";
|
196 |
+
|
197 |
+
while (true) {
|
198 |
+
prompt = promptBuildContext(docAnswresTxt, this.ragQuery);
|
199 |
+
const payload = getPayloadBuildContext(prompt);
|
200 |
+
try {
|
201 |
+
docContext = await HfRequest.post(payload, TIMEOUT);
|
202 |
+
if (!docContext) return "";
|
203 |
+
} catch (err) {
|
204 |
+
console.error(`RR2)`, err);
|
205 |
+
const ei = getErrorInfo(err);
|
206 |
+
if (ei.errorType === ERROR_TOKENS) {
|
207 |
+
UaLog.log(`Error tokens build Context ${prompt.length}`);
|
208 |
+
docAnswresTxt = truncInput(docAnswresTxt, PROMPT_DECR);
|
209 |
+
docAnswresTxt = setMaxLen(docAnswresTxt);
|
210 |
+
continue;
|
211 |
+
} else if (ei.errorType === TIMEOUT_ERROR) {
|
212 |
+
UaLog.log(`Error timeout build Context`);
|
213 |
+
wait(5);
|
214 |
+
// UaLog.log(`Error timeout build Context 2`);
|
215 |
+
continue;
|
216 |
+
} else {
|
217 |
+
throw err;
|
|
|
218 |
}
|
219 |
+
}
|
220 |
+
break;
|
221 |
+
} //end while
|
222 |
+
UaLog.log(`context ${docAnswersLen} => ${docContext.length}`);
|
223 |
+
// docContext = cleanResponse(docContext); //AAA
|
224 |
+
docContext = `\n### DOCUMENTO: ${docName}\n ${docContext}`;
|
225 |
+
this.docContextLst.push(docContext);
|
226 |
} // end for document
|
227 |
} catch (err) {
|
228 |
console.error(err);
|
229 |
throw err;
|
230 |
}
|
231 |
+
this.ragContext = this.docContextLst.join("\n\n");
|
|
|
232 |
this.saveToDb();
|
233 |
|
234 |
// query finale utilizza context
|
235 |
{
|
236 |
+
let answer = "";
|
237 |
let context = this.ragContext;
|
238 |
try {
|
239 |
while (true) {
|
240 |
let prompt = promptWithContext(context, query);
|
241 |
const payload = getPayloadWithContext(prompt);
|
242 |
try {
|
243 |
+
answer = await HfRequest.post(payload, TIMEOUT);
|
244 |
+
if (!answer) return "";
|
245 |
} catch (err) {
|
246 |
+
console.error(`RR3)`, err);
|
247 |
+
const ei = getErrorInfo(err);
|
248 |
if (ei.errorType === ERROR_TOKENS) {
|
249 |
+
UaLog.log(`Error tokens with Context ${prompt.length}`);
|
|
|
250 |
context = truncInput(context, PROMPT_DECR);
|
251 |
+
context = setMaxLen(context);
|
252 |
+
continue;
|
253 |
+
} else if (ei.errorType === TIMEOUT_ERROR) {
|
254 |
+
UaLog.log(`Error timeout with Context`);
|
255 |
+
wait(5);
|
256 |
+
// UaLog.log(`Error timeout with Context 2`);
|
257 |
continue;
|
258 |
} else {
|
|
|
259 |
throw err;
|
260 |
}
|
261 |
}
|
262 |
break;
|
263 |
}
|
264 |
+
answer = cleanResponse(answer);
|
265 |
+
this.ragAnswer = answer;
|
266 |
this.saveRespToDb();
|
267 |
ThreadMgr.init();
|
268 |
this.saveToDb();
|
269 |
+
UaLog.log(`Risposta (${this.ragAnswer.length})`);
|
270 |
} catch (err) {
|
271 |
console.error(err);
|
272 |
+
answer = `${err}`;
|
273 |
throw err;
|
274 |
} finally {
|
275 |
+
return answer;
|
276 |
}
|
277 |
} // end query
|
278 |
},
|
279 |
+
|
280 |
// thread
|
281 |
async requestContext(query) {
|
282 |
let text = "";
|
|
|
297 |
text = await HfRequest.post(payload, TIMEOUT);
|
298 |
if (!text) return "";
|
299 |
} catch (err) {
|
300 |
+
console.error(`RR4)`, err);
|
301 |
+
const ei = getErrorInfo(err);
|
302 |
if (ei.errorType === ERROR_TOKENS) {
|
303 |
+
UaLog.log(`Error tokens Thread Init ${prompt.length}`);
|
|
|
304 |
thread = truncInput(thread, PROMPT_DECR);
|
305 |
+
context = setMaxLen(context);
|
306 |
+
continue;
|
307 |
+
} else if (ei.errorType === TIMEOUT_ERROR) {
|
308 |
+
UaLog.log(`Error timeout Thread Init`);
|
309 |
continue;
|
310 |
} else {
|
|
|
311 |
throw err;
|
312 |
}
|
313 |
} //end catch
|
|
|
336 |
text = await HfRequest.post(payload, TIMEOUT);
|
337 |
if (!text) return "";
|
338 |
} catch (err) {
|
339 |
+
console.error(`RR5)`, err);
|
340 |
+
const ei = getErrorInfo(err);
|
341 |
if (ei.errorType === ERROR_TOKENS) {
|
342 |
UaLog.log(`Error tokens Thread ${prompt.length}`);
|
|
|
343 |
thread = truncInput(thread, PROMPT_DECR);
|
344 |
continue;
|
345 |
+
} else if (ei.errorType === TIMEOUT_ERROR) {
|
346 |
+
UaLog.log(`Error timeout Thread`);
|
347 |
+
continue;
|
348 |
} else {
|
|
|
349 |
throw err;
|
350 |
}
|
351 |
}
|
|
|
366 |
},
|
367 |
};
|
368 |
|
369 |
+
const LLM = "## Assistant:";
|
370 |
+
const USER = "## User:";
|
371 |
|
372 |
const ThreadMgr = {
|
373 |
rows: [],
|
374 |
init() {
|
375 |
this.rows = [];
|
376 |
+
if (!!Rag.ragAnswer) {
|
377 |
+
this.add(Rag.ragQuery, Rag.ragAnswer);
|
378 |
} else {
|
379 |
this.add("", "");
|
380 |
}
|
|
|
389 |
for (const ua of this.rows) {
|
390 |
const u = ua[0];
|
391 |
const a = ua[1];
|
392 |
+
rows.push(`${USER}\n${u}\n${LLM}\n${a}\n`);
|
393 |
}
|
394 |
+
return rows.join("\n\n");
|
395 |
},
|
396 |
isFirst() {
|
397 |
return this.rows.length < 2;
|
static/javascript/rag_prompts.js
CHANGED
@@ -4,73 +4,80 @@
|
|
4 |
|
5 |
function promptDoc(documento, domanda, docName) {
|
6 |
return `
|
7 |
-
SYSTEM:
|
8 |
-
- Sei un assistente AI specializzato nell'analisi di documenti.
|
9 |
-
- Rispondi sempre ed esclusivamente in italiano.
|
10 |
|
11 |
-
TASK:
|
12 |
-
- Analizza il documento fornito ed estrai le informazioni rilevanti per rispondere alla domanda fornita.
|
13 |
-
- Attieniti rigorosamente alle istruzioni.
|
14 |
|
15 |
INSTRUCTIONS:
|
16 |
-
1.
|
17 |
-
2.
|
18 |
-
3.
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
|
|
|
|
24 |
|
25 |
DOCUMENTO:
|
26 |
-
<<<
|
27 |
${documento}
|
28 |
-
<<<
|
29 |
|
30 |
DOMANDA:
|
31 |
${domanda}
|
32 |
|
33 |
OUTPUT_FORMAT:
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
RESPONSE:
|
37 |
-
|
38 |
}
|
39 |
|
40 |
-
function promptBuildContext(
|
41 |
return `
|
42 |
-
SYSTEM:
|
43 |
-
- Sei un assistente AI specializzato nell'analisi di documenti.
|
44 |
-
- Rispondi sempre ed esclusivamente in italiano.
|
45 |
|
46 |
-
TASK:
|
47 |
-
- Analizza e riorganizza logicamente il documento fornito.
|
48 |
-
- Attieniti rigorosamente alle istruzioni.
|
49 |
|
50 |
INSTRUCTIONS:
|
51 |
-
1.
|
52 |
-
2.
|
53 |
-
3.
|
54 |
-
4.
|
55 |
-
5.
|
56 |
-
6.
|
57 |
-
7.
|
58 |
-
8.
|
59 |
-
9.
|
60 |
-
10.
|
61 |
-
11.
|
62 |
-
12.
|
63 |
-
|
64 |
-
|
65 |
-
|
|
|
|
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
${documento}
|
70 |
-
<<<FINE_DOCUMENTO>>>
|
71 |
|
72 |
OUTPUT_FORMAT:
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
RESPONSE:
|
76 |
`;
|
@@ -78,22 +85,17 @@ RESPONSE:
|
|
78 |
|
79 |
function promptWithContext(contesto, domanda) {
|
80 |
return `
|
81 |
-
SYSTEM:
|
82 |
-
- Sei un assistente AI specializzato nell'analisi e nell'elaborazione di informazioni contestuali.
|
83 |
-
- Rispondi sempre ed esclusivamente in italiano.
|
84 |
|
85 |
-
TASK:
|
86 |
-
Elabora la risposta alla domanda sulla base del contesto fornito.
|
87 |
|
88 |
INSTRUCTIONS:
|
89 |
-
1. Analizza attentamente il
|
90 |
2. Estrai i concetti chiave e fai inferenze ragionevoli.
|
91 |
-
3. Prepara una risposta chiara e
|
92 |
-
4.
|
93 |
-
5.
|
94 |
-
6.
|
95 |
-
7. Assicurati che la risposta sia interamente in italiano.
|
96 |
-
8. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
97 |
|
98 |
CONTESTO:
|
99 |
<<<INIZIO_CONTESTO>>>
|
@@ -104,20 +106,17 @@ DOMANDA:
|
|
104 |
${domanda}
|
105 |
|
106 |
OUTPUT_FORMAT:
|
107 |
-
Rispondi con un testo
|
108 |
|
109 |
RESPONSE:
|
110 |
-
|
111 |
}
|
112 |
|
113 |
function promptThread(contesto, conversazione, richiesta) {
|
114 |
return `
|
115 |
-
SYSTEM:
|
116 |
-
- Sei un assistente AI versatile progettato per gestire conversazioni dinamiche e adattarti a varie richieste.
|
117 |
-
- Rispondi sempre in italiano.
|
118 |
|
119 |
-
TASK:
|
120 |
-
Elaborare la risposta alla richista sulla base del contesto fornito e della conversazione.
|
121 |
|
122 |
INSTRUCTIONS:
|
123 |
1. Analizza attentamente il contesto, la conversazione precedente e la richiesta attuale.
|
@@ -130,14 +129,12 @@ INSTRUCTIONS:
|
|
130 |
8. Se l'intento non è chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
|
131 |
9. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
|
132 |
10. Se è necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
|
133 |
-
11. Assicurati che la risposta sia interamente in italiano.
|
134 |
|
135 |
CONTESTO:
|
136 |
-
<<<
|
137 |
${contesto}
|
138 |
-
<<<
|
139 |
|
140 |
-
CONVERSAZIONE:
|
141 |
<<<INIZIO_CONVERSAZIONE>>>
|
142 |
${conversazione}
|
143 |
<<<FINE_CONVERSAZIONE>>>
|
@@ -146,14 +143,13 @@ RICHIESTA:
|
|
146 |
${richiesta}
|
147 |
|
148 |
OUTPUT_FORMAT:
|
149 |
-
Rispondi con un testo
|
150 |
|
151 |
RESPONSE:
|
152 |
-
|
153 |
}
|
154 |
|
155 |
/*
|
156 |
-
|
157 |
1. max_new_tokens: 512
|
158 |
Questo è un valore ragionevole per risposte di lunghezza media.
|
159 |
Potrebbe essere aumentato a 1024 o più se si desiderano risposte più lunghe e dettagliate.
|
@@ -213,9 +209,9 @@ function getPayloadDoc(prompt) {
|
|
213 |
task: "text2text-generation",
|
214 |
max_new_tokens: 1024,
|
215 |
num_return_sequences: 1,
|
216 |
-
temperature: 0.
|
217 |
-
|
218 |
-
|
219 |
do_sample: false,
|
220 |
no_repeat_ngram_size: 4,
|
221 |
num_beams: 4,
|
@@ -238,18 +234,18 @@ function getPayloadBuildContext(prompt) {
|
|
238 |
inputs: prompt,
|
239 |
parameters: {
|
240 |
task: "text2text-generation",
|
241 |
-
max_new_tokens:
|
242 |
num_return_sequences: 1,
|
243 |
-
temperature: 0.
|
244 |
-
|
245 |
-
|
246 |
do_sample: false,
|
247 |
no_repeat_ngram_size: 4,
|
248 |
-
num_beams:
|
249 |
-
repetition_penalty: 1.
|
250 |
return_full_text: false,
|
251 |
details: false,
|
252 |
-
max_time:
|
253 |
seed: 42,
|
254 |
},
|
255 |
options: {
|
@@ -267,9 +263,9 @@ function getPayloadWithContext(prompt) {
|
|
267 |
task: "text2text-generation",
|
268 |
max_new_tokens: 2048,
|
269 |
num_return_sequences: 1,
|
270 |
-
temperature: 0.
|
271 |
-
|
272 |
-
|
273 |
do_sample: false,
|
274 |
no_repeat_ngram_size: 4,
|
275 |
num_beams: 5,
|
@@ -294,9 +290,9 @@ function getPayloadThread(prompt) {
|
|
294 |
task: "text2text-generation",
|
295 |
max_new_tokens: 2048,
|
296 |
num_return_sequences: 1,
|
297 |
-
temperature: 0.
|
298 |
-
|
299 |
-
|
300 |
do_sample: false,
|
301 |
no_repeat_ngram_size: 4,
|
302 |
num_beams: 5,
|
|
|
4 |
|
5 |
function promptDoc(documento, domanda, docName) {
|
6 |
return `
|
7 |
+
SYSTEM: Sei un assistente AI specializzato nell'analisi di documenti. Rispondi ESCLUSIVAMENTE in italiano. Non usare altre lingue in nessuna parte della risposta.
|
|
|
|
|
8 |
|
9 |
+
TASK: Analizza il documento ${docName} ed estrai le informazioni rilevanti per rispondere alla domanda fornita.
|
|
|
|
|
10 |
|
11 |
INSTRUCTIONS:
|
12 |
+
1. Identifica la tipologia e lo scopo del documento (es. articolo scientifico, racconto, saggio, documento tecnico) e adatta l'analisi di conseguenza.
|
13 |
+
2. Analizza attentamente il documento fornito e identifica le informazioni pertinenti alla domanda.
|
14 |
+
3. Estrai i concetti chiave e fai inferenze ragionevoli.
|
15 |
+
3. Focalizzati sull'estrazione di concetti chiave e inferenze rilevanti per la domanda.
|
16 |
+
4. Seleziona citazioni specifiche direttamente collegate alla domanda.
|
17 |
+
5. Prepara una risposta chiara e dettagliata.
|
18 |
+
6. Inizia con una breve introduzione, sviluppa l'analisi, esponi le inferenze e concludi con una sintesi.
|
19 |
+
7. Cita le fonti quando è utile per chiarire informazioni o inferenze.
|
20 |
+
8. Se trovi contenuti in altre lingue nel documento, traducili in italiano prima di includerli nella risposta.
|
21 |
+
9. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
22 |
|
23 |
DOCUMENTO:
|
24 |
+
<<<INIZIO_DOCUMENTO>>>
|
25 |
${documento}
|
26 |
+
<<<FINE_DOCUMENTO>>>
|
27 |
|
28 |
DOMANDA:
|
29 |
${domanda}
|
30 |
|
31 |
OUTPUT_FORMAT:
|
32 |
+
La risposta dovrà essere strutturata nel seguente modo:
|
33 |
+
- Introduzione:
|
34 |
+
- Concetti chiav:e
|
35 |
+
- Citazioni:
|
36 |
+
- Inferenze:
|
37 |
+
- Dettagli rilevanti:
|
38 |
+
- Conclusione:
|
39 |
|
40 |
RESPONSE:
|
41 |
+
`;
|
42 |
}
|
43 |
|
44 |
+
function promptBuildContext(informazioni, domanda) {
|
45 |
return `
|
46 |
+
SYSTEM: Sei un assitente AI specializzato nella riorganizzazione di informazioni come contesto nelle interrogazioni ad un LLM. Rispondi ESCLUSIVAMENTE in italiano. Non usare altre lingue in nessuna parte della risposta.
|
|
|
|
|
47 |
|
48 |
+
TASK: Analizza e riorganizza le informazioi rilevanti per rispondere alla domada fornite seguendo le istruzioni.
|
|
|
|
|
49 |
|
50 |
INSTRUCTIONS:
|
51 |
+
1. Analizza attentamente le informazioi e identifica i temi e i concetti pertinenti alla domanda.
|
52 |
+
2. Estrai i concetti chiave e fai inferenze ragionevoli.
|
53 |
+
3. Organizza le informazioni in una struttura logica e coerente.
|
54 |
+
4. Prepara una risposta che riorganizzi i contenuti, dando priorità alle informazioni più importanti o rilevanti.
|
55 |
+
5. Includi una breve introduzione che presenti i temi principali.
|
56 |
+
6. Sviluppa l'analisi raggruppando le informazioni per argomenti correlati.
|
57 |
+
7. Presenta le inferenze e le connessioni tra i diversi concetti.
|
58 |
+
8. Includi, se rilevanti, dettagli specifici come nomi propri, termini tecnici, date o luoghi che contribuiscono alla precisione del contesto.
|
59 |
+
9. Concludi con una sintesi che riassuma i punti chiave e la struttura logica.
|
60 |
+
10. Evidenzia le connessioni tra contenuti estratti da fonti diverse.
|
61 |
+
11. Effettua un controllo finale per assicurarti che tutte le informazioni chiave siano state incluse.
|
62 |
+
12. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
63 |
+
|
64 |
+
INFORAZIONI:
|
65 |
+
<<<INIZIO_INFORMAZIONI>>>
|
66 |
+
${informazioni}
|
67 |
+
<<<FINE_INFORMAZIONI>>>
|
68 |
|
69 |
+
DOMANDA:
|
70 |
+
${domanda}
|
|
|
|
|
71 |
|
72 |
OUTPUT_FORMAT:
|
73 |
+
La risposta dovrà essere strutturata nel seguente modo:
|
74 |
+
- Introduzione:
|
75 |
+
- Concetti chiav:e
|
76 |
+
- Citazioni:
|
77 |
+
- Inferenze:
|
78 |
+
- Connessioni fra contenuti:
|
79 |
+
- Dettagli rilevanti:
|
80 |
+
- Conclusione:
|
81 |
|
82 |
RESPONSE:
|
83 |
`;
|
|
|
85 |
|
86 |
function promptWithContext(contesto, domanda) {
|
87 |
return `
|
88 |
+
SYSTEM: Sei un sistema AI specializzato nell'analisi semantica di informazioni estratte da documenti. Rispondi sempre ed esclusivamente in italiano.
|
|
|
|
|
89 |
|
90 |
+
TASK: Elabora la risposta alla domanda sulla base del contesto fornito.
|
|
|
91 |
|
92 |
INSTRUCTIONS:
|
93 |
+
1. Analizza attentamente il contesto e identifica le informazioni pertinenti alla domanda.
|
94 |
2. Estrai i concetti chiave e fai inferenze ragionevoli.
|
95 |
+
3. Prepara una risposta chiara e dettagliata utilizzandoo al meglio il contesto.
|
96 |
+
4. Inizia con una breve introduzione, sviluppa l'analisi, elabora le inferenze e concludi con una sintesi.
|
97 |
+
5. Se la domanda richiede di citare le fonti, fai riferimento al documento fornito distinguendolo chiaramente da eventuali altre fonti citate all'interno del contesto stesso.
|
98 |
+
6. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
|
|
|
|
99 |
|
100 |
CONTESTO:
|
101 |
<<<INIZIO_CONTESTO>>>
|
|
|
106 |
${domanda}
|
107 |
|
108 |
OUTPUT_FORMAT:
|
109 |
+
Rispondi con un testo piano suddiviso in paragrafi.Evita di usare etichette, elenchi o marcatori speciali.
|
110 |
|
111 |
RESPONSE:
|
112 |
+
`;
|
113 |
}
|
114 |
|
115 |
function promptThread(contesto, conversazione, richiesta) {
|
116 |
return `
|
117 |
+
SYSTEM: Sei un assistente AI versatile progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Rispondi sempre in italiano.
|
|
|
|
|
118 |
|
119 |
+
TASK: Elabora la risposta alla richiesta sulla base del contesto fornito e della conversazione.
|
|
|
120 |
|
121 |
INSTRUCTIONS:
|
122 |
1. Analizza attentamente il contesto, la conversazione precedente e la richiesta attuale.
|
|
|
129 |
8. Se l'intento non è chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
|
130 |
9. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
|
131 |
10. Se è necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
|
|
|
132 |
|
133 |
CONTESTO:
|
134 |
+
<<<BEGIN_CONTESTO>>>
|
135 |
${contesto}
|
136 |
+
<<<END_CONTESTO>>>
|
137 |
|
|
|
138 |
<<<INIZIO_CONVERSAZIONE>>>
|
139 |
${conversazione}
|
140 |
<<<FINE_CONVERSAZIONE>>>
|
|
|
143 |
${richiesta}
|
144 |
|
145 |
OUTPUT_FORMAT:
|
146 |
+
Rispondi con un testo piano suddiviso in paragrafi.Evita di usare etichette, elenchi o marcatori speciali.
|
147 |
|
148 |
RESPONSE:
|
149 |
+
`;
|
150 |
}
|
151 |
|
152 |
/*
|
|
|
153 |
1. max_new_tokens: 512
|
154 |
Questo è un valore ragionevole per risposte di lunghezza media.
|
155 |
Potrebbe essere aumentato a 1024 o più se si desiderano risposte più lunghe e dettagliate.
|
|
|
209 |
task: "text2text-generation",
|
210 |
max_new_tokens: 1024,
|
211 |
num_return_sequences: 1,
|
212 |
+
temperature: 0.2,
|
213 |
+
top_p: 0.85,
|
214 |
+
top_k: 30,
|
215 |
do_sample: false,
|
216 |
no_repeat_ngram_size: 4,
|
217 |
num_beams: 4,
|
|
|
234 |
inputs: prompt,
|
235 |
parameters: {
|
236 |
task: "text2text-generation",
|
237 |
+
max_new_tokens: 6000,
|
238 |
num_return_sequences: 1,
|
239 |
+
temperature: 0.2,
|
240 |
+
top_p: 0.85,
|
241 |
+
top_k: 30,
|
242 |
do_sample: false,
|
243 |
no_repeat_ngram_size: 4,
|
244 |
+
num_beams: 4,
|
245 |
+
repetition_penalty: 1.2,
|
246 |
return_full_text: false,
|
247 |
details: false,
|
248 |
+
max_time: 180.0,
|
249 |
seed: 42,
|
250 |
},
|
251 |
options: {
|
|
|
263 |
task: "text2text-generation",
|
264 |
max_new_tokens: 2048,
|
265 |
num_return_sequences: 1,
|
266 |
+
temperature: 0.3,
|
267 |
+
top_p: 0.85,
|
268 |
+
top_k: 30,
|
269 |
do_sample: false,
|
270 |
no_repeat_ngram_size: 4,
|
271 |
num_beams: 5,
|
|
|
290 |
task: "text2text-generation",
|
291 |
max_new_tokens: 2048,
|
292 |
num_return_sequences: 1,
|
293 |
+
temperature: 0.3,
|
294 |
+
top_p: 0.85,
|
295 |
+
top_k: 30,
|
296 |
do_sample: false,
|
297 |
no_repeat_ngram_size: 4,
|
298 |
num_beams: 5,
|
static/javascript/rag_rqs.js
CHANGED
@@ -19,7 +19,7 @@
|
|
19 |
*/
|
20 |
|
21 |
"use strict";
|
22 |
-
const VERS = "0.1.
|
23 |
|
24 |
var xlog = console.log;
|
25 |
var xerror = console.error;
|
@@ -67,7 +67,7 @@ const hideSpinner = () => {
|
|
67 |
};
|
68 |
|
69 |
var tm;
|
70 |
-
|
71 |
function openApp() {
|
72 |
tm = umgm();
|
73 |
wnds.init();
|
@@ -98,7 +98,7 @@ function showQuery(e) {
|
|
98 |
|
99 |
//Risposta Rsg
|
100 |
function showRagResponse(e) {
|
101 |
-
const txt = `\n${Rag.
|
102 |
wnds.wpre.show(txt);
|
103 |
}
|
104 |
|
@@ -110,17 +110,17 @@ function showThread(e) {
|
|
110 |
|
111 |
//elenco risposte
|
112 |
function elencoRisposte(e) {
|
113 |
-
let rs = [...Rag.
|
114 |
if (rs.length == 0) {
|
115 |
rs = UaDb.readArray(ID_RESPONSES);
|
116 |
}
|
117 |
if (rs.length == 0) return;
|
118 |
const text = rs
|
119 |
.map((x, i) => {
|
120 |
-
x = subResponseDOcTag(x);
|
121 |
return `\n[${i + 1}]\n ${x.trim()}`;
|
122 |
})
|
123 |
-
.join("\n");
|
124 |
wnds.wpre.show(text);
|
125 |
}
|
126 |
|
|
|
19 |
*/
|
20 |
|
21 |
"use strict";
|
22 |
+
const VERS = "0.1.47 (24-08-2024)";
|
23 |
|
24 |
var xlog = console.log;
|
25 |
var xerror = console.error;
|
|
|
67 |
};
|
68 |
|
69 |
var tm;
|
70 |
+
|
71 |
function openApp() {
|
72 |
tm = umgm();
|
73 |
wnds.init();
|
|
|
98 |
|
99 |
//Risposta Rsg
|
100 |
function showRagResponse(e) {
|
101 |
+
const txt = `\n${Rag.ragAnswer}`;
|
102 |
wnds.wpre.show(txt);
|
103 |
}
|
104 |
|
|
|
110 |
|
111 |
//elenco risposte
|
112 |
function elencoRisposte(e) {
|
113 |
+
let rs = [...Rag.answers];
|
114 |
if (rs.length == 0) {
|
115 |
rs = UaDb.readArray(ID_RESPONSES);
|
116 |
}
|
117 |
if (rs.length == 0) return;
|
118 |
const text = rs
|
119 |
.map((x, i) => {
|
120 |
+
// x = subResponseDOcTag(x);
|
121 |
return `\n[${i + 1}]\n ${x.trim()}`;
|
122 |
})
|
123 |
+
.join("\n");
|
124 |
wnds.wpre.show(text);
|
125 |
}
|
126 |
|
static/javascript/rag_ui.js
CHANGED
@@ -111,7 +111,6 @@ const WndDiv = (id) => {
|
|
111 |
};
|
112 |
};
|
113 |
|
114 |
-
//TODO
|
115 |
const wnds = {
|
116 |
wdiv: null,
|
117 |
wpre: null,
|
@@ -130,7 +129,6 @@ const wnds = {
|
|
130 |
|
131 |
const Menu = {
|
132 |
init() {
|
133 |
-
// gestione menu
|
134 |
const btn = document.querySelector("#id-menu-btn");
|
135 |
btn.addEventListener("change", () => {
|
136 |
document.querySelector("body").classList.toggle("menu-open", btn.checked);
|
@@ -151,7 +149,7 @@ const Menu = {
|
|
151 |
UaLog.callShow = show;
|
152 |
|
153 |
UaLog.setXY(54, 13).setZ(111).new();
|
154 |
-
UaLog.log_show("Buon Lavoro");
|
155 |
},
|
156 |
close() {
|
157 |
const btn = document.querySelector("#menu-toggle");
|
@@ -255,8 +253,9 @@ const TextInput = {
|
|
255 |
setOutText("");
|
256 |
const msg = this.inp.value.trim();
|
257 |
try {
|
258 |
-
|
259 |
-
|
|
|
260 |
this.inp.value = "";
|
261 |
UaLog.close();
|
262 |
} catch (err) {
|
@@ -279,11 +278,12 @@ const TextInput = {
|
|
279 |
if (ThreadMgr.isFirst()) setOutText("");
|
280 |
const query = this.inp.value.trim();
|
281 |
try {
|
282 |
-
|
283 |
if (text == "") {
|
284 |
hideSpinner();
|
285 |
return;
|
286 |
}
|
|
|
287 |
setOutText(text);
|
288 |
this.inp.value = "";
|
289 |
} catch (err) {
|
@@ -306,7 +306,7 @@ const TextInput = {
|
|
306 |
ThreadMgr.init();
|
307 |
},
|
308 |
};
|
309 |
-
|
310 |
const setOutText = (txt) => {
|
311 |
let out = document.getElementById("id-text-out");
|
312 |
const h = `<pre class="pre-text"></pre>`;
|
|
|
111 |
};
|
112 |
};
|
113 |
|
|
|
114 |
const wnds = {
|
115 |
wdiv: null,
|
116 |
wpre: null,
|
|
|
129 |
|
130 |
const Menu = {
|
131 |
init() {
|
|
|
132 |
const btn = document.querySelector("#id-menu-btn");
|
133 |
btn.addEventListener("change", () => {
|
134 |
document.querySelector("body").classList.toggle("menu-open", btn.checked);
|
|
|
149 |
UaLog.callShow = show;
|
150 |
|
151 |
UaLog.setXY(54, 13).setZ(111).new();
|
152 |
+
// UaLog.log_show("Buon Lavoro");
|
153 |
},
|
154 |
close() {
|
155 |
const btn = document.querySelector("#menu-toggle");
|
|
|
253 |
setOutText("");
|
254 |
const msg = this.inp.value.trim();
|
255 |
try {
|
256 |
+
let text = await Rag.requestDocsRAG(msg);
|
257 |
+
text = cleanOut(text);
|
258 |
+
setOutText(text);
|
259 |
this.inp.value = "";
|
260 |
UaLog.close();
|
261 |
} catch (err) {
|
|
|
278 |
if (ThreadMgr.isFirst()) setOutText("");
|
279 |
const query = this.inp.value.trim();
|
280 |
try {
|
281 |
+
let text = await Rag.requestContext(query);
|
282 |
if (text == "") {
|
283 |
hideSpinner();
|
284 |
return;
|
285 |
}
|
286 |
+
text = cleanOut(text);
|
287 |
setOutText(text);
|
288 |
this.inp.value = "";
|
289 |
} catch (err) {
|
|
|
306 |
ThreadMgr.init();
|
307 |
},
|
308 |
};
|
309 |
+
|
310 |
const setOutText = (txt) => {
|
311 |
let out = document.getElementById("id-text-out");
|
312 |
const h = `<pre class="pre-text"></pre>`;
|
static/javascript/ualog3.js
CHANGED
@@ -15,6 +15,16 @@
|
|
15 |
// utilizzare l'ultima versione di UaWindowAdm
|
16 |
// setXY con vw ,vh
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
var UaLog = {
|
19 |
callHide: function () {},
|
20 |
callShow: function () {},
|
@@ -52,9 +62,9 @@ var UaLog = {
|
|
52 |
return this;
|
53 |
},
|
54 |
prn_(...args) {
|
55 |
-
let s = args.join("\n");
|
56 |
let e = document.getElementById(this.msg_id);
|
57 |
-
let h = e.textContent + s + "\n";
|
58 |
e.textContent = h;
|
59 |
},
|
60 |
print(...args) {
|
|
|
15 |
// utilizzare l'ultima versione di UaWindowAdm
|
16 |
// setXY con vw ,vh
|
17 |
|
18 |
+
function formatRow(vs, sps) {
|
19 |
+
return vs
|
20 |
+
.map((v, i) => {
|
21 |
+
const space = sps[i];
|
22 |
+
const frtm = space < 0 ? v.toString().padStart(Math.abs(space), " ") : v.toString().padEnd(space, " ");
|
23 |
+
return frtm;
|
24 |
+
})
|
25 |
+
.join(" ");
|
26 |
+
}
|
27 |
+
|
28 |
var UaLog = {
|
29 |
callHide: function () {},
|
30 |
callShow: function () {},
|
|
|
62 |
return this;
|
63 |
},
|
64 |
prn_(...args) {
|
65 |
+
let s = args.join("\n");
|
66 |
let e = document.getElementById(this.msg_id);
|
67 |
+
let h = e.textContent + s + "\n";
|
68 |
e.textContent = h;
|
69 |
},
|
70 |
print(...args) {
|
static/js/ragrqs.min.js
CHANGED
@@ -1,18 +1,19 @@
|
|
1 |
-
|
2 |
-
cleanDoc
|
3 |
-
|
4 |
-
function
|
|
|
5 |
save(a,b){localStorage.setItem(a,b)},getAllIds(){const a=[];for(let b=0;b<localStorage.length;b++)a.push(localStorage.key(b));return a},saveArray(a,b){b=JSON.stringify(b);UaDb.save(a,b)},readArray(a){a=UaDb.read(a);return 0==a.trim().length?[]:JSON.parse(a)},saveJson(a,b){b=JSON.stringify(b);UaDb.save(a,b)},readJson(a){return(a=UaDb.read(a))?JSON.parse(a):{}}},DataMgr={docs:[],doc_names:[],linkToName(a){a=a.split("/");return a[a.length-1]},async loadDoc(a){this.readDbDocNames();try{const b=await requestGet(a),
|
6 |
c=cleanDoc(b),d=this.linkToName(a);if(this.doc_names.includes(d))alert(`Il docuento ${d} \u00e8 gi\u00e0 caricato`);else return this.doc_names.push(d),this.docs.push(c),this.saveDbDocs(),c}catch(b){alert("loadDoc()\n"+b+"\n"+a)}},addDoc(a,b){b=cleanDoc(b);this.docs.push(b);this.doc_names.push(a);this.saveDbDocs()},saveDbDocs(){UaDb.saveArray(ID_DOC_NAMES,this.doc_names);UaDb.saveArray(ID_DOCS,this.docs)},readDbDocs(){this.docs=UaDb.readArray(ID_DOCS)},readDbDocNames(){this.doc_names=UaDb.readArray(ID_DOC_NAMES)},
|
7 |
-
deleteJsonDati(){const a=UaDb.getAllIds();for(const b of a)[ID_DOCS,ID_DOC_NAMES].includes(b)||UaDb.delete(b);Rag.ragQuery="";Rag.ragContext="";Rag.
|
8 |
-
const ERROR_TOKENS="ERROR_TOKENS",TIMEOUT_ERROR="TIMEOUT_ERROR",
|
9 |
-
|
10 |
-
(
|
11 |
-
function
|
12 |
-
Status: ${
|
13 |
-
Status Text: ${
|
14 |
-
Error Type: ${
|
15 |
-
Message: ${
|
16 |
|
17 |
rag_rqs
|
18 |
Copyright (C) 2024 [Il tuo nome]
|
@@ -30,98 +31,101 @@ function errorInfo(a){return JSON.parse(a.message)}function errorToText(a){a=JSO
|
|
30 |
You should have received a copy of the GNU General Public License
|
31 |
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
32 |
*/
|
33 |
-
const MAX_PROMPT_LENGTH=81920,PROMPT_DECR=2048,TIMEOUT=6E4
|
34 |
-
|
35 |
-
this.
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
this.
|
40 |
-
|
41 |
-
|
42 |
-
b
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
TASK:
|
48 |
-
- Analizza il documento fornito ed estrai le informazioni rilevanti per rispondere alla domanda fornita.
|
49 |
-
- Attieniti rigorosamente alle istruzioni.
|
50 |
|
51 |
INSTRUCTIONS:
|
52 |
-
1.
|
53 |
-
2.
|
54 |
-
3.
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
60 |
|
61 |
DOCUMENTO:
|
62 |
-
<<<
|
63 |
${a}
|
64 |
-
<<<
|
65 |
|
66 |
DOMANDA:
|
67 |
${b}
|
68 |
|
69 |
OUTPUT_FORMAT:
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
RESPONSE:
|
73 |
-
|
74 |
-
SYSTEM:
|
75 |
-
- Sei un assistente AI specializzato nell'analisi di documenti.
|
76 |
-
- Rispondi sempre ed esclusivamente in italiano.
|
77 |
|
78 |
-
TASK:
|
79 |
-
- Analizza e riorganizza logicamente il documento fornito.
|
80 |
-
- Attieniti rigorosamente alle istruzioni.
|
81 |
|
82 |
INSTRUCTIONS:
|
83 |
-
1.
|
84 |
-
2.
|
85 |
-
3.
|
86 |
-
4.
|
87 |
-
5.
|
88 |
-
6.
|
89 |
-
7.
|
90 |
-
8.
|
91 |
-
9.
|
92 |
-
10.
|
93 |
-
11.
|
94 |
-
12.
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
DOCUMENTO:
|
100 |
-
<<<INIZIO_DOCUMENTO>>>
|
101 |
${a}
|
102 |
-
<<<
|
|
|
|
|
|
|
103 |
|
104 |
OUTPUT_FORMAT:
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
RESPONSE:
|
108 |
`}function promptWithContext(a,b){return`
|
109 |
-
SYSTEM:
|
110 |
-
- Sei un assistente AI specializzato nell'analisi e nell'elaborazione di informazioni contestuali.
|
111 |
-
- Rispondi sempre ed esclusivamente in italiano.
|
112 |
|
113 |
-
TASK:
|
114 |
-
Elabora la risposta alla domanda sulla base del contesto fornito.
|
115 |
|
116 |
INSTRUCTIONS:
|
117 |
-
1. Analizza attentamente il
|
118 |
2. Estrai i concetti chiave e fai inferenze ragionevoli.
|
119 |
-
3. Prepara una risposta chiara e
|
120 |
-
4.
|
121 |
-
5.
|
122 |
-
6.
|
123 |
-
7. Assicurati che la risposta sia interamente in italiano.
|
124 |
-
8. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
125 |
|
126 |
CONTESTO:
|
127 |
<<<INIZIO_CONTESTO>>>
|
@@ -132,16 +136,13 @@ DOMANDA:
|
|
132 |
${b}
|
133 |
|
134 |
OUTPUT_FORMAT:
|
135 |
-
Rispondi con un testo
|
136 |
|
137 |
RESPONSE:
|
138 |
-
|
139 |
-
SYSTEM:
|
140 |
-
- Sei un assistente AI versatile progettato per gestire conversazioni dinamiche e adattarti a varie richieste.
|
141 |
-
- Rispondi sempre in italiano.
|
142 |
|
143 |
-
TASK:
|
144 |
-
Elaborare la risposta alla richista sulla base del contesto fornito e della conversazione.
|
145 |
|
146 |
INSTRUCTIONS:
|
147 |
1. Analizza attentamente il contesto, la conversazione precedente e la richiesta attuale.
|
@@ -154,14 +155,12 @@ INSTRUCTIONS:
|
|
154 |
8. Se l'intento non \u00e8 chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
|
155 |
9. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
|
156 |
10. Se \u00e8 necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
|
157 |
-
11. Assicurati che la risposta sia interamente in italiano.
|
158 |
|
159 |
CONTESTO:
|
160 |
-
<<<
|
161 |
${a}
|
162 |
-
<<<
|
163 |
|
164 |
-
CONVERSAZIONE:
|
165 |
<<<INIZIO_CONVERSAZIONE>>>
|
166 |
${b}
|
167 |
<<<FINE_CONVERSAZIONE>>>
|
@@ -170,15 +169,15 @@ RICHIESTA:
|
|
170 |
${c}
|
171 |
|
172 |
OUTPUT_FORMAT:
|
173 |
-
Rispondi con un testo
|
174 |
|
175 |
RESPONSE:
|
176 |
-
|
177 |
-
function getPayloadBuildContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:
|
178 |
-
function getPayloadWithContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.
|
179 |
-
function getPayloadThread(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.
|
180 |
-
function openApp(){tm=umgm();wnds.init();Menu.init();TextInput.init();TextOutput.init();Rag.init();document.querySelector(".menu-btn").checked=!1;release()}function release(){document.querySelector(".release").innerHTML=VERS}const op0=async function(a){a=await requestGet("./help1.html");wnds.wdiv.show(a)};function showQuery(a){wnds.wpre.show(`\n${Rag.ragQuery}`)}function showRagResponse(a){wnds.wpre.show(`\n${Rag.
|
181 |
-
function elencoRisposte(a){a=[...Rag.
|
182 |
function elencoDocs(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=DataMgr.doc_names,b=UaJtfh();let c=0;b.append("<ul>");for(const g of a){a=b;var d=a.append,e=g,f=c++;d.call(a,`
|
183 |
<li><a href="#" onCLick="showT(${f});">${f+1}.${e}</a></li>
|
184 |
`)}b.append("</ul>");b=b.html();wnds.wdiv.show(`<br><br>${b}`)}function calcQuery(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=[];let b=0,c=0;a.push("Documento Num.Parti");a.push("==================");for(const d of DataMgr.docs){const e=DataMgr.doc_names[c];c+=1;const f=Math.ceil(d.length/MAX_PROMPT_LENGTH);b+=f;a.push(`${e} [${f}]`)}a.push("==================");a.push(`Totale num. Parti: ${b}`);a=a.join("\n");wnds.wpre.show(a)}
|
@@ -208,12 +207,12 @@ function loadTestoEsempio(a){DataMgr.loadDoc(`data/${a}`);wnds.wdiv.close()}asyn
|
|
208 |
<div class="div-text">${b}</div>
|
209 |
</div>
|
210 |
`;this.w.drag();this.w.setZ(12);this.w.vw_vh().setXY(16.5,10,-1);this.w.setHtml(b);this.w.show();this.w.getElement().querySelector(".btn-copy").addEventListener("click",()=>this.copy())},close(){this.w.close()},async copy(){const b=this.w.getElement().querySelector(".div-text").textContent;try{await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}}}),wnds={wdiv:null,wpre:null,wout:null,init(){this.wdiv=WndDiv("id_w0");this.wpre=WndPre("id_w1");this.wout=WndPre("id_out")},
|
211 |
-
closeAll(){UaWindowAdm.close("id_w0");UaWindowAdm.close("id_w1");UaWindowAdm.close("id_out")}},Menu={init(){const a=document.querySelector("#id-menu-btn");a.addEventListener("change",()=>{document.querySelector("body").classList.toggle("menu-open",a.checked)});const b=document.getElementById("id_log");UaLog.callHide=()=>{b.classList.contains("active")&&b.classList.remove("active")};UaLog.callShow=()=>{b.classList.contains("active")||b.classList.add("active")};UaLog.setXY(54,13).setZ(111).new()
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
TextOutput={init(){this.copyBtn=document.querySelector(".copy-output");this.copyBtn.addEventListener("click",()=>this.copy());document.querySelector(".clear-output").addEventListener("click",()=>this.clear());document.querySelector(".wnd-output").addEventListener("click",()=>this.openWnd())},openWnd(){const a=document.getElementById("id-text-out").textContent;wnds.wout.show(a)},async copy(){const a=document.getElementById("id-text-out").querySelector("pre");if(a){var b=a.textContent;a.classList.add("copied");
|
218 |
this.copyBtn.classList.add("copied");try{await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}setTimeout(()=>{this.copyBtn.classList.remove("copied");a.classList.remove("copied")},5E3)}},clear(){document.getElementById("id-text-out").textContent=""}};const RagUpload={open(){const a=UaWindowAdm.create("id_upload");a.drag();a.setZ(12);a.vw_vh().setXY(16.5,10,-1);a.setHtml('\n <div class="window-text">\n <div class="btn-wrapper">\n <button class="btn-close" title="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>\n </div> \n <div class="upload"> \n <h4>Upload file Text / PDF</h4> \n <form id="uploadForm">\n <input class="file" type="file" id="id_fileupload" > \n <button type="button" onclick="RagUpload.upload();">Upload and Convert</button>\n </form>\n <div id="result" class="result"></div>\n </div>\n </div>\n ');
|
219 |
a.show()},async upload(){const a=document.getElementById("id_fileupload").files[0];if(a){var b=a.name;if(DataMgr.doc_names.includes(b))alert("Il file \u00e8 gi\u00e0 in archivio");else{var c=document.getElementById("result"),d=a.name.split(".").pop().toLowerCase();showSpinner();try{let e;if("pdf"===d){const f=new PdfHandler;await f.loadPdfJs();e=await f.extractTextFromPDF(a);f.cleanup()}else if("txt"===d)e=await readTextFile(a);else{alert("Formato file non supportato.");return}DataMgr.addDoc(b,e);
|
@@ -224,8 +223,9 @@ class PdfHandler{constructor(){this.workerScriptElement=this.scriptElement=this.
|
|
224 |
document.body.appendChild(this.workerScriptElement);this.workerScriptElement.onload=a}}));this.pdfjsLib=window["pdfjs-dist/build/pdf"];this.pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js"}async extractTextFromPDF(a){a=await a.arrayBuffer();a=await this.pdfjsLib.getDocument({data:a}).promise;let b="";for(let c=1;c<=a.numPages;c++){const d=(await (await a.getPage(c)).getTextContent()).items.map(e=>e.str).join(" ");b+=d+"\n"}return b}cleanup(){this.scriptElement&&
|
225 |
(document.body.removeChild(this.scriptElement),this.scriptElement=null);this.workerScriptElement&&(document.body.removeChild(this.workerScriptElement),this.workerScriptElement=null);this.pdfjsLib=null;window.gc&&window.gc()}}
|
226 |
async function readTextFile(a){if(!a||"text/plain"!==a.type)throw Error("Invalid file type. Please select a text file.");return new Promise((b,c)=>{const d=new FileReader;d.onload=e=>b(e.target.result);d.onerror=e=>c(Error("Error reading file: "+e.message));d.readAsText(a)})};const nodrag_tds=["input","select","a"],nodrag_cls="nodrag";
|
227 |
-
var UaDrag=function(a){return function(b){let c=0,d=0,e=0,f=0;const g=function(h){h=h||window.event;h.preventDefault();c=e-h.clientX;d=f-h.clientY;e=h.clientX;f=h.clientY;b.style.top=b.offsetTop-d+"px";b.style.left=b.offsetLeft-c+"px"},
|
228 |
-
|
|
|
229 |
this.y,-1):this.wind.setCenter(-1);this.z&&this.wind.setZ(this.z);return this},setXY(a,b){this.x=a;this.y=b;return this},setZ(a){this.z=a;return this},prn_(...a){a=a.join("\n");let b=document.getElementById(this.msg_id);b.textContent=b.textContent+a+"\n"},print(...a){null!=this.wind&&this.active&&this.prn_(...a)},log(...a){null!=this.wind&&this.prn_(...a)},log_show(...a){null!=this.wind&&(this.active||this.toggle(),this.prn_(...a))},cls(){if(null!=this.wind)return document.getElementById(this.msg_id).innerHTML=
|
230 |
"",this},close(){null!=this.wind&&(this.wind.hide(),this.active=!1,this.callHide())},toggle(){null!=this.wind&&(this.active?(this.active=!1,this.wind.hide(),this.callHide()):(this.active=!0,this.wind.show(),this.callShow()))}};var UaWindowAdm={ws:{},create(a,b=null){let c=document.getElementById(a);c||(c=document.createElement("div"),b?document.getElementById(b).appendChild(c):document.body.appendChild(c),c.id=a,c.setAttribute("data-name","ua-window"),b=this.newUaWindow(c),this.ws[a]=b);a=this.ws[a];c.style.display="none";return a},get(a){return this.ws[a]?this.ws[a]:null},show(a){this.ws[a]&&this.ws[a].show()},close(a){this.ws[a]&&this.ws[a].close()},toggle(a){this.ws[a]&&this.ws[a].toggle()},hide(a){this.ws[a]&&this.ws[a].hide()},
|
231 |
closeThis(a){a=a.closest('[data-name="ua-window"]').id;this.ws[a].close()},showAll(){for(let a in this.ws)this.ws[a].show()},hideAll(){for(let a in this.ws)this.ws[a].hide()},closeAll(){for(let a in this.ws)this.ws[a].close()},remove(a){this.ws[a]&&(document.getElementById(a).remove(),this.ws[a]=null,delete this.ws[a])},removeAll(){for(let a in this.ws)this.remove(a);this.ws={}},newUaWindow(a){let b={initialize(c){this.w=c;this.wy=this.wx="0px";this.isVisible=this.isOpen=!1;this.firstShow=!0;this.wz=
|
|
|
1 |
+
function removeTag(a){a=a.replace(/<<</g,"").replace(/>>>/g,"");return a=a.replace(/<</g,"").replace(/>>/g,"")}function uniteBrokenWords(a){return a.replace(/-\n/g,"")}
|
2 |
+
function cleanDoc(a){try{return a=removeTag(a),a=a.replace(/-\n/g,""),a=a.replace(/[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g,""),a=a.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g," "),a=a.replace(/\\([nrtfb])/g,"$1"),a=a.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g,"$1"),a=a.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g,"\\\\$1"),a=a.replace(/\\/g,""),a=a.replace(/\u201c/g,'"').replace(/\u201d/g,'"'),a=a.replace(/ +([.,;:!?])/g,"$1"),a=a.replace(/\n\s*\n/g,"\n\n"),a=a.replace(/\n{3,}/g,
|
3 |
+
"\n\n"),a=a.replace(/ +/g," "),a.trim()}catch(b){return console.error(b),"Errore di codifica del documento"}}
|
4 |
+
function cleanResponse(a){try{return a=a.replace(/[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g,""),a=a.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g," "),a=a.replace(/\\([nrtfb])/g,"$1"),a=a.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g,"$1"),a=a.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g,"\\\\$1"),a=a.replace(/\\/g,""),a=a.replace(/\n{3,}/g,"\n\n"),a=a.replace(/ +/g," "),a.trim()}catch(b){return console.error(b),`Errore di codifica nella risposta\n${b}`}}
|
5 |
+
function cleanOut(a){return a=a.replace(/\n{3,}/g,"\n\n")};const ID_RESPONSES="id_responses",ID_DOC_NAMES="id_doc_names",ID_DOCS="id_docs;",ID_RAG="id_rag",ID_THREAD="id_thread",UaDb={create(a,b){localStorage.getItem(a)?xerror(`ID ${a} already exists.`):localStorage.setItem(a,b)},read(a){const b=localStorage.getItem(a);return null===b?(xlog(`UaDb.read ${a} not found.`),""):b},update(a,b){localStorage.getItem(a)?localStorage.setItem(a,b):xlog(`UaDb.update ${a} not found.`)},delete(a){localStorage.getItem(a)?localStorage.removeItem(a):xerror(`ID ${a} not found.`)},
|
6 |
save(a,b){localStorage.setItem(a,b)},getAllIds(){const a=[];for(let b=0;b<localStorage.length;b++)a.push(localStorage.key(b));return a},saveArray(a,b){b=JSON.stringify(b);UaDb.save(a,b)},readArray(a){a=UaDb.read(a);return 0==a.trim().length?[]:JSON.parse(a)},saveJson(a,b){b=JSON.stringify(b);UaDb.save(a,b)},readJson(a){return(a=UaDb.read(a))?JSON.parse(a):{}}},DataMgr={docs:[],doc_names:[],linkToName(a){a=a.split("/");return a[a.length-1]},async loadDoc(a){this.readDbDocNames();try{const b=await requestGet(a),
|
7 |
c=cleanDoc(b),d=this.linkToName(a);if(this.doc_names.includes(d))alert(`Il docuento ${d} \u00e8 gi\u00e0 caricato`);else return this.doc_names.push(d),this.docs.push(c),this.saveDbDocs(),c}catch(b){alert("loadDoc()\n"+b+"\n"+a)}},addDoc(a,b){b=cleanDoc(b);this.docs.push(b);this.doc_names.push(a);this.saveDbDocs()},saveDbDocs(){UaDb.saveArray(ID_DOC_NAMES,this.doc_names);UaDb.saveArray(ID_DOCS,this.docs)},readDbDocs(){this.docs=UaDb.readArray(ID_DOCS)},readDbDocNames(){this.doc_names=UaDb.readArray(ID_DOC_NAMES)},
|
8 |
+
deleteJsonDati(){const a=UaDb.getAllIds();for(const b of a)[ID_DOCS,ID_DOC_NAMES].includes(b)||UaDb.delete(b);Rag.ragQuery="";Rag.ragContext="";Rag.ragAnswer="";Rag.answers=[];Rag.prompts=[];ThreadMgr.rows=[]}};function umgm(){return["bWtkW0l+XX0=","SXx2d1FxbVc=","V1tRXlxneUY=","flV6a1NdbUg=","VllpUkc="].map(a=>atob(a).split("").map(b=>String.fromCharCode((b.charCodeAt(0)-5+256)%256)).join("")).join("")};const model_name="mistralai/Mistral-7B-Instruct-v0.3";async function requestGet(a){try{var b=await fetch(a,{method:"GET",headers:{"Content-Type":"text/plain;charset=UTF-8"}});if(!b.ok)throw Error(`HTTP error! status: ${b.status}`);const c=await b.arrayBuffer();return(new TextDecoder("utf-8")).decode(c)}catch(c){throw console.error(c),b="AbortError"===c.name?"Request was aborted":c.message.includes("HTTP error! status")?c.message:"An error occurred",alert(`requestGet()\nurl: ${a}\n${b}`),c;}}
|
9 |
+
const ERROR_TOKENS="ERROR_TOKENS",TIMEOUT_ERROR="TIMEOUT_ERROR",getErrorType=(a,b)=>500<=a?"SERVER_ERROR":400<=a&&500>a?"object"===typeof b&&"validation"===b.error_type?b.error.includes("tokens")?ERROR_TOKENS:"ERROR_VALIDATION":"CLIENT_ERROR":"UNKNOWN_ERROR",checkResponse=a=>a&&Array.isArray(a)&&0!==a.length?a[0].generated_text?"ok":"MISSING_GENERATED_TEXT":"INVALID_DATA",createErrorInfo=(a,b,c,d)=>JSON.stringify({status:a,statusText:b,errorType:d,message:c||"Errore sconosciuto"}),HfRequest={controller:null,
|
10 |
+
isCancelled:!1,baseUrl:"https://api-inference.huggingface.co/models",async post(a,b=5E4){this.isCancelled=!1;this.controller=new AbortController;let c;try{const d=setTimeout(()=>{this.controller.abort()},b);c=await fetch(`${this.baseUrl}/${model_name}`,{method:"POST",headers:{Authorization:`Bearer ${tm}`,"Content-Type":"application/json"},body:JSON.stringify(a),signal:this.controller.signal});clearTimeout(d);if(this.isCancelled)return null;const e=await c.json();if(!c.ok){const g=getErrorType(c.status,
|
11 |
+
e),k=createErrorInfo(c.status,c.statusText,e.error,g);throw Error(k);}const f=checkResponse(e);if("ok"!==f){const g=createErrorInfo(c.status,c.statusText,e.error,f);throw Error(g);}return e[0].generated_text.trim()}catch(d){if(this.isCancelled)return null;if("AbortError"===d.name)throw a=createErrorInfo(0,"Timeout","La richiesta \u00e8 scaduta",TIMEOUT_ERROR),Error(a);throw d;}},cancelRequest(){this.controller&&(this.isCancelled=!0,this.controller.abort())}};
|
12 |
+
function getErrorInfo(a){let b={};try{b=JSON.parse(a.message)}catch(c){a=`getErrorInfo\n${a}`,console.error(a),b={status:"0",statusText:"status_errorInof",errorType:"UNKNOWN_ERROR_errorInfo",message:a}}finally{return b}}function errorToText(a){let b;try{const c=JSON.parse(a.message);b=`Error:
|
13 |
+
Status: ${c.status}
|
14 |
+
Status Text: ${c.statusText}
|
15 |
+
Error Type: ${c.errorType}
|
16 |
+
Message: ${c.message}`}catch(c){console.error(`errorToText\n${c}`),b=`${c}`}finally{return b}};/*
|
17 |
|
18 |
rag_rqs
|
19 |
Copyright (C) 2024 [Il tuo nome]
|
|
|
31 |
You should have received a copy of the GNU General Public License
|
32 |
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
33 |
*/
|
34 |
+
const MAX_PROMPT_LENGTH=81920,PROMPT_DECR=2048,TIMEOUT=6E4;function wait(a){return new Promise(b=>setTimeout(b,1E3*a))}async function example(){console.log("Inizio attesa...");await wait(5);console.log("Fine attesa!")}example();
|
35 |
+
const truncInput=(a,b)=>a.substring(0,a.length-b),setMaxLen=a=>a.substring(0,MAX_PROMPT_LENGTH-1E3),getPartSize=(a,b,c)=>{c=MAX_PROMPT_LENGTH-c;a.length+b.length<c?c=a.length:(a=a.indexOf(".",c),a=(-1!=a?a:c)+1,a>c+100&&(a=c),c=a);return c},getPartDoc=(a,b)=>{const c=a.substring(0,b);a=a.substring(b).trim();return[c,a]},ragLog=(a,b,c,d)=>{const e=MAX_PROMPT_LENGTH;d=d.reduce((f,g)=>f+g.length,0);xlog(`${a} mx:${e} lft:${b} rgt:${c} arr:${d}`);a=formatRow([a,b,c,d],[8,-7,-7,-7]);UaLog.log(a)},Rag=
|
36 |
+
{ragContext:"",ragQuery:"",ragAnswer:"",answers:[],docContextLst:[],prompts:[],doc:"",doc_part:"",init(){this.readRespsFromDb();this.readFromDb()},saveToDb(){UaDb.saveJson(ID_RAG,{context:this.ragContext,ragquery:this.ragQuery,raganswer:this.ragAnswer});UaDb.saveArray(ID_THREAD,ThreadMgr.rows)},readFromDb(){const a=UaDb.readJson(ID_RAG);this.ragContext=a.context||"";this.ragQuery=a.ragquery||"";this.ragAnswer=a.raganswer||"";ThreadMgr.rows=UaDb.readArray(ID_THREAD)},saveRespToDb(){UaDb.saveArray(ID_RESPONSES,
|
37 |
+
this.answers)},readRespsFromDb(){this.answers=UaDb.readArray(ID_RESPONSES)},async requestDocsRAG(a){DataMgr.deleteJsonDati();DataMgr.readDbDocNames();DataMgr.readDbDocs();this.ragQuery=a;this.saveToDb();var b=0;try{var c=1;for(let e=0;e<DataMgr.docs.length;e++){let f=DataMgr.docs[e];if(""==f.trim())continue;const g=DataMgr.doc_names[e],k=f.length;xlog(`${g} (${k}) `);UaLog.log(`${g} (${k}) `);++b;var d=1;let h=0,l="",t="",u="",m="",v=[];for(;;){let r=getPartSize(f,promptDoc("",a,""),h);if(10>r)break;
|
38 |
+
[t,u]=getPartDoc(f,r);ragLog(`${c}) ${b},${d}`,t.length,u.length,this.answers);l=promptDoc(t,a,g);const p=getPayloadDoc(l);try{if(m=await HfRequest.post(p,TIMEOUT),!m)return""}catch(n){console.error("RR1)\n",n);const w=getErrorInfo(n);if(w.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Doc ${l.length}`);h+=PROMPT_DECR;continue}else if(w.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Doc");wait(5);continue}else throw n;}d++;c++;f=u;m=cleanResponse(m);v.push(m);this.answers.push(`DOCUMENTO : ${g}_${d}\n${m}`)}const x=
|
39 |
+
v.length;let q=v.join("\n\n");for(d="";;){l=promptBuildContext(q,this.ragQuery);const r=getPayloadBuildContext(l);try{if(d=await HfRequest.post(r,TIMEOUT),!d)return""}catch(p){console.error("RR2)",p);const n=getErrorInfo(p);if(n.errorType===ERROR_TOKENS){UaLog.log(`Error tokens build Context ${l.length}`);q=truncInput(q,PROMPT_DECR);q=setMaxLen(q);continue}else if(n.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout build Context");wait(5);continue}else throw p;}break}UaLog.log(`context ${x} => ${d.length}`);
|
40 |
+
d=`\n### DOCUMENTO: ${g}\n ${d}`;this.docContextLst.push(d)}}catch(e){throw console.error(e),e;}this.ragContext=this.docContextLst.join("\n\n");this.saveToDb();b="";c=this.ragContext;try{for(;;){let e=promptWithContext(c,a);const f=getPayloadWithContext(e);try{if(b=await HfRequest.post(f,TIMEOUT),!b)return""}catch(g){console.error("RR3)",g);const k=getErrorInfo(g);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens with Context ${e.length}`);c=truncInput(c,PROMPT_DECR);c=setMaxLen(c);continue}else if(k.errorType===
|
41 |
+
TIMEOUT_ERROR){UaLog.log("Error timeout with Context");wait(5);continue}else throw g;}break}this.ragAnswer=b=cleanResponse(b);this.saveRespToDb();ThreadMgr.init();this.saveToDb();UaLog.log(`Risposta (${this.ragAnswer.length})`)}catch(e){throw console.error(e),b=`${e}`,e;}finally{return b}},async requestContext(a){let b="";if(!this.ragContext&&!await confirm("Contesto vuoto. Vuoi continuare?"))return"";if(ThreadMgr.isFirst()){ThreadMgr.init();try{var c=this.ragContext;let d=ThreadMgr.getThread();
|
42 |
+
for(;;){prompt=promptThread(c,d,a);const e=getPayloadThread(prompt);try{if(b=await HfRequest.post(e,TIMEOUT),!b)return""}catch(f){console.error("RR4)",f);const g=getErrorInfo(f);if(g.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Thread Init ${prompt.length}`);d=truncInput(d,PROMPT_DECR);c=setMaxLen(c);continue}else if(g.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Thread Init");continue}else throw f;}break}b=cleanResponse(b);ThreadMgr.add(a,b);b=ThreadMgr.getThread();UaLog.log(`Inizio Conversazione (${prompt.length})`)}catch(d){throw console.error(d),
|
43 |
+
b=`${d}`,d;}finally{return b}}else try{let d=this.ragContext,e=ThreadMgr.getThread();for(c="";;){c=promptThread(d,e,a);const f=getPayloadThread(c);try{if(b=await HfRequest.post(f,TIMEOUT),!b)return""}catch(g){console.error("RR5)",g);const k=getErrorInfo(g);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Thread ${c.length}`);e=truncInput(e,PROMPT_DECR);continue}else if(k.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Thread");continue}else throw g;}break}b=cleanResponse(b);ThreadMgr.add(a,
|
44 |
+
b);b=ThreadMgr.getThread();UaLog.log(`Conversazione (${c.length})`)}catch(d){throw console.error(d),b=`${d}`,d;}finally{return b}}},LLM="## Assistant:",USER="## User:",ThreadMgr={rows:[],init(){this.rows=[];Rag.ragAnswer?this.add(Rag.ragQuery,Rag.ragAnswer):this.add("","")},add(a,b){this.rows.push([a,b]);UaDb.saveArray(ID_THREAD,ThreadMgr.rows)},getThread(){const a=[];for(const b of this.rows)a.push(`${USER}\n${b[0]}\n${LLM}\n${b[1]}\n`);return a.join("\n\n")},isFirst(){return 2>this.rows.length}};function promptDoc(a,b,c){return`
|
45 |
+
SYSTEM: Sei un assistente AI specializzato nell'analisi di documenti. Rispondi ESCLUSIVAMENTE in italiano. Non usare altre lingue in nessuna parte della risposta.
|
46 |
+
|
47 |
+
TASK: Analizza il documento ${c} ed estrai le informazioni rilevanti per rispondere alla domanda fornita.
|
|
|
|
|
|
|
48 |
|
49 |
INSTRUCTIONS:
|
50 |
+
1. Identifica la tipologia e lo scopo del documento (es. articolo scientifico, racconto, saggio, documento tecnico) e adatta l'analisi di conseguenza.
|
51 |
+
2. Analizza attentamente il documento fornito e identifica le informazioni pertinenti alla domanda.
|
52 |
+
3. Estrai i concetti chiave e fai inferenze ragionevoli.
|
53 |
+
3. Focalizzati sull'estrazione di concetti chiave e inferenze rilevanti per la domanda.
|
54 |
+
4. Seleziona citazioni specifiche direttamente collegate alla domanda.
|
55 |
+
5. Prepara una risposta chiara e dettagliata.
|
56 |
+
6. Inizia con una breve introduzione, sviluppa l'analisi, esponi le inferenze e concludi con una sintesi.
|
57 |
+
7. Cita le fonti quando \u00e8 utile per chiarire informazioni o inferenze.
|
58 |
+
8. Se trovi contenuti in altre lingue nel documento, traducili in italiano prima di includerli nella risposta.
|
59 |
+
9. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
60 |
|
61 |
DOCUMENTO:
|
62 |
+
<<<INIZIO_DOCUMENTO>>>
|
63 |
${a}
|
64 |
+
<<<FINE_DOCUMENTO>>>
|
65 |
|
66 |
DOMANDA:
|
67 |
${b}
|
68 |
|
69 |
OUTPUT_FORMAT:
|
70 |
+
La risposta dovr\u00e0 essere strutturata nel seguente modo:
|
71 |
+
- Introduzione:
|
72 |
+
- Concetti chiav:e
|
73 |
+
- Citazioni:
|
74 |
+
- Inferenze:
|
75 |
+
- Dettagli rilevanti:
|
76 |
+
- Conclusione:
|
77 |
|
78 |
RESPONSE:
|
79 |
+
`}function promptBuildContext(a,b){return`
|
80 |
+
SYSTEM: Sei un assitente AI specializzato nella riorganizzazione di informazioni come contesto nelle interrogazioni ad un LLM. Rispondi ESCLUSIVAMENTE in italiano. Non usare altre lingue in nessuna parte della risposta.
|
|
|
|
|
81 |
|
82 |
+
TASK: Analizza e riorganizza le informazioi rilevanti per rispondere alla domada fornite seguendo le istruzioni.
|
|
|
|
|
83 |
|
84 |
INSTRUCTIONS:
|
85 |
+
1. Analizza attentamente le informazioi e identifica i temi e i concetti pertinenti alla domanda.
|
86 |
+
2. Estrai i concetti chiave e fai inferenze ragionevoli.
|
87 |
+
3. Organizza le informazioni in una struttura logica e coerente.
|
88 |
+
4. Prepara una risposta che riorganizzi i contenuti, dando priorit\u00e0 alle informazioni pi\u00f9 importanti o rilevanti.
|
89 |
+
5. Includi una breve introduzione che presenti i temi principali.
|
90 |
+
6. Sviluppa l'analisi raggruppando le informazioni per argomenti correlati.
|
91 |
+
7. Presenta le inferenze e le connessioni tra i diversi concetti.
|
92 |
+
8. Includi, se rilevanti, dettagli specifici come nomi propri, termini tecnici, date o luoghi che contribuiscono alla precisione del contesto.
|
93 |
+
9. Concludi con una sintesi che riassuma i punti chiave e la struttura logica.
|
94 |
+
10. Evidenzia le connessioni tra contenuti estratti da fonti diverse.
|
95 |
+
11. Effettua un controllo finale per assicurarti che tutte le informazioni chiave siano state incluse.
|
96 |
+
12. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
97 |
+
|
98 |
+
INFORAZIONI:
|
99 |
+
<<<INIZIO_INFORMAZIONI>>>
|
|
|
|
|
|
|
100 |
${a}
|
101 |
+
<<<FINE_INFORMAZIONI>>>
|
102 |
+
|
103 |
+
DOMANDA:
|
104 |
+
${b}
|
105 |
|
106 |
OUTPUT_FORMAT:
|
107 |
+
La risposta dovr\u00e0 essere strutturata nel seguente modo:
|
108 |
+
- Introduzione:
|
109 |
+
- Concetti chiav:e
|
110 |
+
- Citazioni:
|
111 |
+
- Inferenze:
|
112 |
+
- Connessioni fra contenuti:
|
113 |
+
- Dettagli rilevanti:
|
114 |
+
- Conclusione:
|
115 |
|
116 |
RESPONSE:
|
117 |
`}function promptWithContext(a,b){return`
|
118 |
+
SYSTEM: Sei un sistema AI specializzato nell'analisi semantica di informazioni estratte da documenti. Rispondi sempre ed esclusivamente in italiano.
|
|
|
|
|
119 |
|
120 |
+
TASK: Elabora la risposta alla domanda sulla base del contesto fornito.
|
|
|
121 |
|
122 |
INSTRUCTIONS:
|
123 |
+
1. Analizza attentamente il contesto e identifica le informazioni pertinenti alla domanda.
|
124 |
2. Estrai i concetti chiave e fai inferenze ragionevoli.
|
125 |
+
3. Prepara una risposta chiara e dettagliata utilizzandoo al meglio il contesto.
|
126 |
+
4. Inizia con una breve introduzione, sviluppa l'analisi, elabora le inferenze e concludi con una sintesi.
|
127 |
+
5. Se la domanda richiede di citare le fonti, fai riferimento al documento fornito distinguendolo chiaramente da eventuali altre fonti citate all'interno del contesto stesso.
|
128 |
+
6. Mantieni un tono oggettivo e uno stile fluido e coerente.
|
|
|
|
|
129 |
|
130 |
CONTESTO:
|
131 |
<<<INIZIO_CONTESTO>>>
|
|
|
136 |
${b}
|
137 |
|
138 |
OUTPUT_FORMAT:
|
139 |
+
Rispondi con un testo piano suddiviso in paragrafi.Evita di usare etichette, elenchi o marcatori speciali.
|
140 |
|
141 |
RESPONSE:
|
142 |
+
`}function promptThread(a,b,c){return`
|
143 |
+
SYSTEM: Sei un assistente AI versatile progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Rispondi sempre in italiano.
|
|
|
|
|
144 |
|
145 |
+
TASK: Elabora la risposta alla richiesta sulla base del contesto fornito e della conversazione.
|
|
|
146 |
|
147 |
INSTRUCTIONS:
|
148 |
1. Analizza attentamente il contesto, la conversazione precedente e la richiesta attuale.
|
|
|
155 |
8. Se l'intento non \u00e8 chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
|
156 |
9. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
|
157 |
10. Se \u00e8 necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
|
|
|
158 |
|
159 |
CONTESTO:
|
160 |
+
<<<BEGIN_CONTESTO>>>
|
161 |
${a}
|
162 |
+
<<<END_CONTESTO>>>
|
163 |
|
|
|
164 |
<<<INIZIO_CONVERSAZIONE>>>
|
165 |
${b}
|
166 |
<<<FINE_CONVERSAZIONE>>>
|
|
|
169 |
${c}
|
170 |
|
171 |
OUTPUT_FORMAT:
|
172 |
+
Rispondi con un testo piano suddiviso in paragrafi.Evita di usare etichette, elenchi o marcatori speciali.
|
173 |
|
174 |
RESPONSE:
|
175 |
+
`}function getPayloadDoc(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:1024,num_return_sequences:1,temperature:.2,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:4,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:90,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
176 |
+
function getPayloadBuildContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:6E3,num_return_sequences:1,temperature:.2,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:4,repetition_penalty:1.2,return_full_text:!1,details:!1,max_time:180,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
177 |
+
function getPayloadWithContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.3,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:120,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
178 |
+
function getPayloadThread(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.3,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:120,seed:42},options:{use_cache:!1,wait_for_model:!0}}};const VERS="0.1.47 (24-08-2024)";var xlog=console.log,xerror=console.error;const cancelRequest=()=>{confirm("Confermi Cancellazione Richeista ?")&&(HfRequest.cancelRequest(),hideSpinner())},showSpinner=()=>{const a=document.getElementById("spinner");a.classList.add("show-spinner");a.addEventListener("click",cancelRequest)},hideSpinner=()=>{const a=document.getElementById("spinner");a.classList.remove("show-spinner");a.removeEventListener("click",cancelRequest)};var tm;
|
179 |
+
function openApp(){tm=umgm();wnds.init();Menu.init();TextInput.init();TextOutput.init();Rag.init();document.querySelector(".menu-btn").checked=!1;release()}function release(){document.querySelector(".release").innerHTML=VERS}const op0=async function(a){a=await requestGet("./help1.html");wnds.wdiv.show(a)};function showQuery(a){wnds.wpre.show(`\n${Rag.ragQuery}`)}function showRagResponse(a){wnds.wpre.show(`\n${Rag.ragAnswer}`)}function showThread(a){a=ThreadMgr.getThread();wnds.wpre.show(a)}
|
180 |
+
function elencoRisposte(a){a=[...Rag.answers];0==a.length&&(a=UaDb.readArray(ID_RESPONSES));0!=a.length&&(a=a.map((b,c)=>`\n[${c+1}]\n ${b.trim()}`).join("\n"),wnds.wpre.show(a))}function showContesto(a){wnds.wpre.show(`${Rag.ragContext}`)}function elencoDati(a){var b=UaDb.getAllIds();a=[];for(var c of b)b=UaDb.read(c).length,a.push(`${c} (${b})`);c=a.join("\n ");wnds.wpre.show(c)}const showT=a=>{wnds.wpre.show(DataMgr.docs[a])};
|
181 |
function elencoDocs(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=DataMgr.doc_names,b=UaJtfh();let c=0;b.append("<ul>");for(const g of a){a=b;var d=a.append,e=g,f=c++;d.call(a,`
|
182 |
<li><a href="#" onCLick="showT(${f});">${f+1}.${e}</a></li>
|
183 |
`)}b.append("</ul>");b=b.html();wnds.wdiv.show(`<br><br>${b}`)}function calcQuery(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=[];let b=0,c=0;a.push("Documento Num.Parti");a.push("==================");for(const d of DataMgr.docs){const e=DataMgr.doc_names[c];c+=1;const f=Math.ceil(d.length/MAX_PROMPT_LENGTH);b+=f;a.push(`${e} [${f}]`)}a.push("==================");a.push(`Totale num. Parti: ${b}`);a=a.join("\n");wnds.wpre.show(a)}
|
|
|
207 |
<div class="div-text">${b}</div>
|
208 |
</div>
|
209 |
`;this.w.drag();this.w.setZ(12);this.w.vw_vh().setXY(16.5,10,-1);this.w.setHtml(b);this.w.show();this.w.getElement().querySelector(".btn-copy").addEventListener("click",()=>this.copy())},close(){this.w.close()},async copy(){const b=this.w.getElement().querySelector(".div-text").textContent;try{await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}}}),wnds={wdiv:null,wpre:null,wout:null,init(){this.wdiv=WndDiv("id_w0");this.wpre=WndPre("id_w1");this.wout=WndPre("id_out")},
|
210 |
+
closeAll(){UaWindowAdm.close("id_w0");UaWindowAdm.close("id_w1");UaWindowAdm.close("id_out")}},Menu={init(){const a=document.querySelector("#id-menu-btn");a.addEventListener("change",()=>{document.querySelector("body").classList.toggle("menu-open",a.checked)});const b=document.getElementById("id_log");UaLog.callHide=()=>{b.classList.contains("active")&&b.classList.remove("active")};UaLog.callShow=()=>{b.classList.contains("active")||b.classList.add("active")};UaLog.setXY(54,13).setZ(111).new()},close(){const a=
|
211 |
+
document.querySelector("#menu-toggle");document.querySelector("body").classList.remove("menu-open",a.checked);document.querySelector(".menu-btn").checked=!1},async help(){const a=await requestGet("./help0.html");wnds.wdiv.show(a)},upload(){RagUpload.open()},uploadDir(){RagUpload.openDir()},async load(){alert("load")},log(){UaLog.toggle()}},TextInput={wnd:null,init(){this.inp=document.querySelector(".text-input");document.addEventListener("keydown",a=>{document.activeElement!==this.inp&&("F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 Control Alt Shift Meta CapsLock Escape PrintScreen ScrollLock Pause Insert Delete Home End PageUp PageDown ArrowLeft ArrowRight ArrowUp ArrowDown".split(" ").includes(a.key)||
|
212 |
+
a.ctrlKey||a.metaKey||a.preventDefault())});document.querySelector(".clear-button").addEventListener("click",()=>{this.inp.value="";this.inp.focus()});this.inp.addEventListener("keydown",a=>this.handleEnter(a));document.querySelector(".send-input").addEventListener("click",()=>this.send());document.querySelector(".send2-input").addEventListener("click",()=>this.send2());document.querySelector(".clear-input").addEventListener("click",()=>this.clear())},handleEnter(a){"Enter"!==a.key||a.shiftKey||(a.preventDefault(),
|
213 |
+
this.send2())},async send(){if(this.inp.value){if(Rag.ragContext&&!confirm("Vuoi iniziare una nuova elabrazione ?"))return"";showSpinner();setOutText("");var a=this.inp.value.trim();try{let b=await Rag.requestDocsRAG(a);b=cleanOut(b);setOutText(b);this.inp.value="";UaLog.close()}catch(b){a=`send\n${b}`,console.error(a),alert(a),setOutText(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},async send2(){if(this.inp.value){showSpinner();ThreadMgr.isFirst()&&setOutText("");var a=this.inp.value.trim();
|
214 |
+
try{let b=await Rag.requestContext(a);if(""==b){hideSpinner();return}b=cleanOut(b);setOutText(b);this.inp.value=""}catch(b){a=`send2\n${b}`,console.error(a),alert(a),setOutText(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},clear(){confirm("Confermi cancellazione conversazione? ")&&(this.inp.value="",setOutText(""),ThreadMgr.init())}},setOutText=a=>{var b=document.getElementById("id-text-out");b.innerHTML='<pre class="pre-text"></pre>';b=b.querySelector(".pre-text");b.textContent=
|
215 |
+
a;b.scrollTop=b.scrollHeight};
|
216 |
TextOutput={init(){this.copyBtn=document.querySelector(".copy-output");this.copyBtn.addEventListener("click",()=>this.copy());document.querySelector(".clear-output").addEventListener("click",()=>this.clear());document.querySelector(".wnd-output").addEventListener("click",()=>this.openWnd())},openWnd(){const a=document.getElementById("id-text-out").textContent;wnds.wout.show(a)},async copy(){const a=document.getElementById("id-text-out").querySelector("pre");if(a){var b=a.textContent;a.classList.add("copied");
|
217 |
this.copyBtn.classList.add("copied");try{await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}setTimeout(()=>{this.copyBtn.classList.remove("copied");a.classList.remove("copied")},5E3)}},clear(){document.getElementById("id-text-out").textContent=""}};const RagUpload={open(){const a=UaWindowAdm.create("id_upload");a.drag();a.setZ(12);a.vw_vh().setXY(16.5,10,-1);a.setHtml('\n <div class="window-text">\n <div class="btn-wrapper">\n <button class="btn-close" title="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>\n </div> \n <div class="upload"> \n <h4>Upload file Text / PDF</h4> \n <form id="uploadForm">\n <input class="file" type="file" id="id_fileupload" > \n <button type="button" onclick="RagUpload.upload();">Upload and Convert</button>\n </form>\n <div id="result" class="result"></div>\n </div>\n </div>\n ');
|
218 |
a.show()},async upload(){const a=document.getElementById("id_fileupload").files[0];if(a){var b=a.name;if(DataMgr.doc_names.includes(b))alert("Il file \u00e8 gi\u00e0 in archivio");else{var c=document.getElementById("result"),d=a.name.split(".").pop().toLowerCase();showSpinner();try{let e;if("pdf"===d){const f=new PdfHandler;await f.loadPdfJs();e=await f.extractTextFromPDF(a);f.cleanup()}else if("txt"===d)e=await readTextFile(a);else{alert("Formato file non supportato.");return}DataMgr.addDoc(b,e);
|
|
|
223 |
document.body.appendChild(this.workerScriptElement);this.workerScriptElement.onload=a}}));this.pdfjsLib=window["pdfjs-dist/build/pdf"];this.pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js"}async extractTextFromPDF(a){a=await a.arrayBuffer();a=await this.pdfjsLib.getDocument({data:a}).promise;let b="";for(let c=1;c<=a.numPages;c++){const d=(await (await a.getPage(c)).getTextContent()).items.map(e=>e.str).join(" ");b+=d+"\n"}return b}cleanup(){this.scriptElement&&
|
224 |
(document.body.removeChild(this.scriptElement),this.scriptElement=null);this.workerScriptElement&&(document.body.removeChild(this.workerScriptElement),this.workerScriptElement=null);this.pdfjsLib=null;window.gc&&window.gc()}}
|
225 |
async function readTextFile(a){if(!a||"text/plain"!==a.type)throw Error("Invalid file type. Please select a text file.");return new Promise((b,c)=>{const d=new FileReader;d.onload=e=>b(e.target.result);d.onerror=e=>c(Error("Error reading file: "+e.message));d.readAsText(a)})};const nodrag_tds=["input","select","a"],nodrag_cls="nodrag";
|
226 |
+
var UaDrag=function(a){return function(b){let c=0,d=0,e=0,f=0;const g=function(h){h=h||window.event;h.preventDefault();c=e-h.clientX;d=f-h.clientY;e=h.clientX;f=h.clientY;b.style.top=b.offsetTop-d+"px";b.style.left=b.offsetLeft-c+"px"},k=function(){document.onmouseup=null;document.onmousemove=null};b.onmousedown=function(h){h=h||window.event;let l=h.target;!(l=l||null)||nodrag_tds.includes(l.tagName.toLowerCase())||l.classList.contains(nodrag_cls)||(h.preventDefault(),e=h.clientX,f=h.clientY,document.onmouseup=
|
227 |
+
k,document.onmousemove=g)}}(a)};const UaJtfh=()=>({rows:[],init(){this.rows=[];return this},insert(a){this.rows.unshift(a);return this},append(a){this.rows.push(a);return this},text(a=""){return this.rows.join(a)},html(a=""){return this.rows.join(a).replace(/\s+|\[rn\]/g," ")}});function formatRow(a,b){return a.map((c,d)=>{d=b[d];return 0>d?c.toString().padStart(Math.abs(d)," "):c.toString().padEnd(d," ")}).join(" ")}
|
228 |
+
var UaLog={callHide:function(){},callShow:function(){},active:!1,wind:null,x:null,y:null,z:null,max_length:2E3,msg_id:"ualogmsg_",new:function(){null==this.wind&&(this.wind=UaWindowAdm.create("ualog_"),this.wind.drag());this.wind.setHtml('\n <button type="button" class="clear" onclick="javascript:UaLog.cls();">Clear</button>\n <button type="button" class="close" onclick="javascript:UaLog.close();">Close</button>\n <pre id="ualogmsg_" ></pre>');this.x?this.wind.vw_vh().setXY(this.x,
|
229 |
this.y,-1):this.wind.setCenter(-1);this.z&&this.wind.setZ(this.z);return this},setXY(a,b){this.x=a;this.y=b;return this},setZ(a){this.z=a;return this},prn_(...a){a=a.join("\n");let b=document.getElementById(this.msg_id);b.textContent=b.textContent+a+"\n"},print(...a){null!=this.wind&&this.active&&this.prn_(...a)},log(...a){null!=this.wind&&this.prn_(...a)},log_show(...a){null!=this.wind&&(this.active||this.toggle(),this.prn_(...a))},cls(){if(null!=this.wind)return document.getElementById(this.msg_id).innerHTML=
|
230 |
"",this},close(){null!=this.wind&&(this.wind.hide(),this.active=!1,this.callHide())},toggle(){null!=this.wind&&(this.active?(this.active=!1,this.wind.hide(),this.callHide()):(this.active=!0,this.wind.show(),this.callShow()))}};var UaWindowAdm={ws:{},create(a,b=null){let c=document.getElementById(a);c||(c=document.createElement("div"),b?document.getElementById(b).appendChild(c):document.body.appendChild(c),c.id=a,c.setAttribute("data-name","ua-window"),b=this.newUaWindow(c),this.ws[a]=b);a=this.ws[a];c.style.display="none";return a},get(a){return this.ws[a]?this.ws[a]:null},show(a){this.ws[a]&&this.ws[a].show()},close(a){this.ws[a]&&this.ws[a].close()},toggle(a){this.ws[a]&&this.ws[a].toggle()},hide(a){this.ws[a]&&this.ws[a].hide()},
|
231 |
closeThis(a){a=a.closest('[data-name="ua-window"]').id;this.ws[a].close()},showAll(){for(let a in this.ws)this.ws[a].show()},hideAll(){for(let a in this.ws)this.ws[a].hide()},closeAll(){for(let a in this.ws)this.ws[a].close()},remove(a){this.ws[a]&&(document.getElementById(a).remove(),this.ws[a]=null,delete this.ws[a])},removeAll(){for(let a in this.ws)this.remove(a);this.ws={}},newUaWindow(a){let b={initialize(c){this.w=c;this.wy=this.wx="0px";this.isVisible=this.isOpen=!1;this.firstShow=!0;this.wz=
|
static/less/ragrqs.less
CHANGED
@@ -287,7 +287,7 @@ div.container {
|
|
287 |
word-wrap: break-word;
|
288 |
font-family: @fsans;
|
289 |
font-size: @fsize-out;
|
290 |
-
line-height: 1.
|
291 |
padding: 2px;
|
292 |
margin: 0;
|
293 |
height: 100%;
|
@@ -304,7 +304,7 @@ div.container {
|
|
304 |
word-wrap: break-word;
|
305 |
font-family: @fsans;
|
306 |
font-size: @fsize-out;
|
307 |
-
line-height: 1.
|
308 |
padding: 2px;
|
309 |
margin: 0;
|
310 |
height: 100%;
|
|
|
287 |
word-wrap: break-word;
|
288 |
font-family: @fsans;
|
289 |
font-size: @fsize-out;
|
290 |
+
line-height: 1.5;
|
291 |
padding: 2px;
|
292 |
margin: 0;
|
293 |
height: 100%;
|
|
|
304 |
word-wrap: break-word;
|
305 |
font-family: @fsans;
|
306 |
font-size: @fsize-out;
|
307 |
+
line-height: 1.5;
|
308 |
padding: 2px;
|
309 |
margin: 0;
|
310 |
height: 100%;
|
static/ragrqs_.html
CHANGED
@@ -7,15 +7,11 @@
|
|
7 |
<meta name="description" content="Author:M.Materni" />
|
8 |
<title>RagRqs</title>
|
9 |
|
10 |
-
<!--
|
11 |
-
<link rel="stylesheet" href="css/ragrqs.min.css" />
|
12 |
-
<script src="js/ragrqs.min.js"></script>
|
13 |
-
-->
|
14 |
<link rel="stylesheet" href="less/normalize.css" />
|
15 |
<link rel="stylesheet/less" href="less/ragrqs.less" />
|
16 |
<link rel="stylesheet/less" href="less/ualog3.less" />
|
17 |
<script src="less/less.js"></script>
|
18 |
-
|
19 |
<script src="javascript/uadrag.js"></script>
|
20 |
<script src="javascript/uawindow.js"></script>
|
21 |
<script src="javascript/uajtfh.js"></script>
|
|
|
7 |
<meta name="description" content="Author:M.Materni" />
|
8 |
<title>RagRqs</title>
|
9 |
|
|
|
|
|
|
|
|
|
10 |
<link rel="stylesheet" href="less/normalize.css" />
|
11 |
<link rel="stylesheet/less" href="less/ragrqs.less" />
|
12 |
<link rel="stylesheet/less" href="less/ualog3.less" />
|
13 |
<script src="less/less.js"></script>
|
14 |
+
|
15 |
<script src="javascript/uadrag.js"></script>
|
16 |
<script src="javascript/uawindow.js"></script>
|
17 |
<script src="javascript/uajtfh.js"></script>
|