Compare commits
692 Commits
7b4a699e2d
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 3bd9657041 | |||
| db8c92a96c | |||
| 8a95a4238c | |||
| 6d1c3f48d6 | |||
| 5a81190f76 | |||
| dd333d106b | |||
| ccfd9992c6 | |||
| 4225150bca | |||
| 62ae20e811 | |||
| a3c9d37b18 | |||
| fa0c98eb8d | |||
| e6b9a2db64 | |||
| 124581744c | |||
| adb7ba7f8e | |||
| 65277acd5e | |||
| 20c1e34136 | |||
| 396f644f33 | |||
| 0492231194 | |||
| d2323e4e88 | |||
| 2f4c2e9e40 | |||
| 77ba8aa771 | |||
| 14923a26e6 | |||
| 124e8793bb | |||
| f45a4d1a42 | |||
| 3a79004bdd | |||
| 96840911ce | |||
| e423bcee1b | |||
| 0c158a8ed6 | |||
| 887c74b5cb | |||
| 48cf1e9844 | |||
| c9b8c5d0f5 | |||
| 05e8b0296f | |||
| be7e1c7c49 | |||
| 872c94351d | |||
| 1803345957 | |||
| 07af68eb11 | |||
| 78de35b2cb | |||
| 57a73d4597 | |||
| c18117fb87 | |||
| abed82924b | |||
| ce21613905 | |||
| c46854a7b2 | |||
| f0ff7c894b | |||
| da0c694c91 | |||
| d174d28928 | |||
| 6622b4cce7 | |||
| 64089af5c3 | |||
| 9ea61d5e4f | |||
| 964b75d4b7 | |||
| 2aebadb774 | |||
| b5f90331e7 | |||
| 9ec66c3196 | |||
| 5da8b3ba6d | |||
| 60b32513cf | |||
| 854ee51861 | |||
| ebfa50bf03 | |||
| a5ad7ab261 | |||
| 4b0ed88176 | |||
| ebbc19c01d | |||
| c9a9253c8d | |||
| 1097ca46d8 | |||
| a0a103dacd | |||
| 5c578a7b84 | |||
| 76d066773a | |||
| 17e22ec4ef | |||
| a111624c36 | |||
| 767b45d334 | |||
| c0904d78f6 | |||
| 3294de9471 | |||
| d0c69a4f96 | |||
| 031588198d | |||
| d9e963ef74 | |||
| d3e7ec56ee | |||
| 8616c077cc | |||
| 13cfd7518b | |||
| ec28cc9bff | |||
| 63d0937754 | |||
| 1f482810fb | |||
| 117a16aca5 | |||
| d415dd7ead | |||
| 00fe48f04d | |||
| 7916fbf242 | |||
| fafd358890 | |||
| 58cdc17341 | |||
| 1609e39840 | |||
| a66db9fe71 | |||
| 8d53590e95 | |||
| 0e65dd3bd6 | |||
| c8930fdb70 | |||
| bb08eb4a93 | |||
| e2d86ff96a | |||
| 564623fa91 | |||
| 3ed74e7e8a | |||
| 36cd49d956 | |||
| 57ce5a4d1e | |||
| fb944223e9 | |||
| e35a29baef | |||
| d8c6dc06c6 | |||
| 631d632911 | |||
| 7e53c27115 | |||
| 8d70f37d16 | |||
| 2c5f4f71a3 | |||
| b3e1130f97 | |||
| 8ced33552e | |||
| 32e9e4478e | |||
| 077bf71aa8 | |||
| d9d696c22c | |||
| 93387e6cec | |||
| b3a33a9fb1 | |||
| 3e0b285764 | |||
| d6b8ee71f6 | |||
| 8787c2cf65 | |||
| 4da9b7faef | |||
| 5857c0f60c | |||
| 0270a65ab3 | |||
| 5dd5514fc4 | |||
| 505085fb87 | |||
| c5b8e5a087 | |||
| 9c368b97c5 | |||
| ba51bb9a1b | |||
| bb80610a3c | |||
| 7b07b344e9 | |||
| a3abc68d70 | |||
| 9aac9ccb2b | |||
| fb33c291ea | |||
| f45f9dbfe5 | |||
| 8f74205db6 | |||
| 6e951f6ec8 | |||
| 79c6cee413 | |||
| ebf90ecd8e | |||
| c904831bd6 | |||
| 8b37a8ef58 | |||
| 83cde1011a | |||
| 71d61931cd | |||
| 26eaac5d59 | |||
| 3e37697d12 | |||
| 33e829f6d8 | |||
| 3206613cc0 | |||
| 443b546ad5 | |||
| 8519b2feca | |||
| c3b572be0d | |||
| c420f018f4 | |||
| 983081eccd | |||
| bd2c003965 | |||
| 3fd2cf4910 | |||
| 236d2d8962 | |||
| f2644ce3cd | |||
| 3f23d22e6b | |||
| 0e7f54dbb6 | |||
| 043e40b0aa | |||
| 024bffecd1 | |||
| 43e329e599 | |||
| 7fbfe215af | |||
| 35b0c633c3 | |||
| ae7b78e12b | |||
| 65204cda5e | |||
| 2c219b3e0c | |||
| 2c2543b0d1 | |||
| fd1f31ee76 | |||
| 604a16d73c | |||
| 7cc9c07612 | |||
| 6257cf0912 | |||
| 6ebd8b869e | |||
| c7eed48fce | |||
| f0edcbccd5 | |||
| e274c09ae5 | |||
| 3a9eb10886 | |||
| 291f5fe5d0 | |||
| 0a42dc8a2d | |||
| 6450614c5b | |||
| b1eed9f1b6 | |||
| dae2ce0f9d | |||
| f562fd5c01 | |||
| 8a0d825274 | |||
| d3ddefdc27 | |||
| c1f3935cf5 | |||
| 2b29952835 | |||
| b04c3a8ac3 | |||
| 2271022378 | |||
| 31027a4c9c | |||
| 20e5ae68bd | |||
| 2c5a5048dc | |||
| 52b9daba19 | |||
| 7fbd3ed3c7 | |||
| 9122f82161 | |||
| 4e33a6961d | |||
| a76803df8c | |||
| 2c2e712ba8 | |||
| 920888b336 | |||
| 8207b1d2e1 | |||
| 84a845948b | |||
| e783885503 | |||
| c62152353c | |||
| 97729f4ce8 | |||
| efe4cc0875 | |||
| 0376ab8eed | |||
| 48cf63d535 | |||
| b2f1aeba42 | |||
| 97366bb8e0 | |||
| 0c04d5bf7d | |||
| 3593117736 | |||
| f8325e5458 | |||
| f43976f167 | |||
| a6ba0db6ff | |||
| a15e068f42 | |||
| e9e7df7e20 | |||
| 5df2871c6f | |||
| a07870c82c | |||
| 0fa4be73da | |||
| 14986260f0 | |||
| bb2e0c08e2 | |||
| 912c63468b | |||
| 88c4a5b0d4 | |||
| 36b6b84129 | |||
| 4db6fde9be | |||
| d0e5c9300c | |||
| 937cd3c6f4 | |||
| c4956fa69e | |||
| d3c4f45501 | |||
| bfb7f870c6 | |||
| 26ef19f4c6 | |||
| 730c6be2cb | |||
| 7b42e25135 | |||
| 90a994f72e | |||
| 74958a5336 | |||
| 32112ddbb6 | |||
| 55a4e7ce28 | |||
| d7cf6f3fc4 | |||
| d98bd71a5d | |||
| 973e8ba219 | |||
| 1758a27a31 | |||
| 1c7e5f0691 | |||
| e1f3aaeec1 | |||
| 7edccc90a3 | |||
| 4a624d2d30 | |||
| 9c84076a85 | |||
| b05562a2de | |||
| b45117c52d | |||
| fd84748450 | |||
| cbe30c6ccb | |||
| a5142e6dd0 | |||
| ec08af4640 | |||
| 9a4f4c7c2b | |||
| 3e35ea96ec | |||
| c7f904ed01 | |||
| 2254a2b7d6 | |||
| b9d59f531d | |||
| e4fb6a38eb | |||
| ce3a216242 | |||
| 45ea3f64ab | |||
| c918e61946 | |||
| 161d0c12aa | |||
| 0ab5011c22 | |||
| b65f82b48d | |||
| 20fd5ddc4b | |||
| caaf7e6c79 | |||
| dc8df4a8ab | |||
| ef1ecd463b | |||
| 0f0a82b798 | |||
| 17ab1fc236 | |||
| cb228ae7aa | |||
| 0f5aec3d1c | |||
| 8946f26813 | |||
| 514fde9cad | |||
| f2abb9121d | |||
| b085239fe5 | |||
| e61c91b69e | |||
| 0ab2c39d9b | |||
| cbc1c34ced | |||
| 7142cf6395 | |||
| 2e7b438b66 | |||
| 7e5238a3c8 | |||
| fe25e6184d | |||
| 07c74af3a2 | |||
| 25bb5b2be9 | |||
| 4767101595 | |||
| 76825289d7 | |||
| 570cc67725 | |||
| 3c4a49b38c | |||
| 2760380430 | |||
| fb3e498574 | |||
| b454810c85 | |||
| 456bb8de97 | |||
| ad552dc1ac | |||
| 8c5dfb3eac | |||
| 81daab141c | |||
| 08a7c78af6 | |||
| 906f731557 | |||
| 672b51a28d | |||
| bb2b929d27 | |||
| cfbae8378f | |||
| 15eba38375 | |||
| e2065b3231 | |||
| 4773f01a76 | |||
| 01b0763478 | |||
| a0989b5b3e | |||
| 789ef97404 | |||
| 46c1a85710 | |||
| a89dd5e13d | |||
| 54048acdcd | |||
| 3440b48c8c | |||
| 34da4bd6c5 | |||
| 4408a01126 | |||
| 5e616dd302 | |||
| 6f1a7383e9 | |||
| ace78e205a | |||
| 4cab0caa83 | |||
| c40bdb1223 | |||
| f8d215679a | |||
| cf591c91d1 | |||
| 2af1fee98a | |||
| 86bb1d0cf2 | |||
| f724bf764d | |||
| 3b3b613ed6 | |||
| ccfc67503b | |||
| eaf2831cd7 | |||
| 0b4f5b4066 | |||
| 39f885a1a9 | |||
| d53ec76560 | |||
| 826b4254bf | |||
| 39e0f3e899 | |||
| bd316e6805 | |||
| 82d7faabf3 | |||
| e27c95c32b | |||
| 672cd12a92 | |||
| e67f856143 | |||
| c4c256f7c4 | |||
| b142e58723 | |||
| 5e2b6eb57a | |||
| 8ac85274dc | |||
| 5268ec4607 | |||
| 4f6771e787 | |||
| b5e1bc9a68 | |||
| 43c6f6360b | |||
| 0ea3bfc14b | |||
| 7d82ef1acf | |||
| 47eaded702 | |||
| a9d75cc4b7 | |||
| b97108ed25 | |||
| b11953ef1e | |||
| aac254ec23 | |||
| cecbc24f26 | |||
| ab2424dbd8 | |||
| f34aa9b150 | |||
| 8f018ce17e | |||
| ab93e921d4 | |||
| 4de740ca62 | |||
| 599e0156df | |||
| 9ba5380705 | |||
| d7cbc57563 | |||
| 7c3c746fac | |||
| 40945a1a5e | |||
| cb8c364b6f | |||
| b627c51f7d | |||
| d5a4ab8417 | |||
| 4b3d510bcf | |||
| 67195af4c1 | |||
| 1c80ca4a06 | |||
| 8459ab1837 | |||
| 473ea4ac85 | |||
| 729fa419d7 | |||
| 82f89c9211 | |||
| 604025efb5 | |||
| 791af40503 | |||
| e368d21128 | |||
| 0b71e9eb3a | |||
| 4ea55457a5 | |||
| ccd930f11d | |||
| 50827fd8cf | |||
| 3f3377118c | |||
| 9849ba54ed | |||
| 5c00010b0a | |||
| cb872e0227 | |||
| 4857eee154 | |||
| 6e9ae778f1 | |||
| 363fb2aba1 | |||
| d85a68ed3c | |||
| 2cbb4544b0 | |||
| 89976f656d | |||
| 89a85a561f | |||
| 8091b054c1 | |||
| 8c5b8c404c | |||
| f06864c72b | |||
| b7f62ce884 | |||
| 088be29a8d | |||
| ac427bc99f | |||
| e332515585 | |||
| e9b96812f2 | |||
| d8a8e9be20 | |||
| 20e5527a22 | |||
| b24d29c694 | |||
| 826fd29278 | |||
| 7aa433b182 | |||
| 6d1a8788fa | |||
| 950a00d84e | |||
| 549ea2d02e | |||
| a44240f02e | |||
| e7ee53ddb0 | |||
| c6a13687ee | |||
| ae0ec60400 | |||
| c03a8d1bd7 | |||
| ecec4d09ea | |||
| 9607f2192a | |||
| 84f0bc7a4d | |||
| 2e3855cfa3 | |||
| 3dbe3fa790 | |||
| 9ee177d47c | |||
| 22d45c4537 | |||
| d20508649c | |||
| b51e0ab891 | |||
| 218834982e | |||
| 246348e28b | |||
| 9e94b3a7df | |||
| 0d1541d64c | |||
| a83486107c | |||
| 3f4f0c9475 | |||
| 896d3be27f | |||
| 2cb4fe4b41 | |||
| 48c35698cb | |||
| 67d9f41f17 | |||
| a0c2b28591 | |||
| 7225980fb9 | |||
| 4447749439 | |||
| 86936dcb96 | |||
| d5cdb85629 | |||
| 9301c65a93 | |||
| 7d744cf7b0 | |||
| 91cfac9fcf | |||
| 00b2d5875a | |||
| aaa3a1c02d | |||
| c3af5ccc72 | |||
| 0d0b52b5d0 | |||
| 5585f9d2f2 | |||
| 1a250c8c2d | |||
| 88c5e5c5dd | |||
| 20a8af0e0e | |||
| 2f73fabda2 | |||
| 477c6f275a | |||
| 553b742d40 | |||
| fcfc34d382 | |||
| 603db28967 | |||
| 2e116b8701 | |||
| 972263d523 | |||
| c2c5385f66 | |||
| 4f9799f6fd | |||
| bc28b56d0b | |||
| e88ac88840 | |||
| d8784463b5 | |||
| d58ed8bead | |||
| c5b2c17370 | |||
| 68bf3a7c8e | |||
| 3019336ad2 | |||
| 7bbdd1ac6d | |||
| 9cda0d8577 | |||
| 5b45b29420 | |||
| 3d06ba9083 | |||
| f9cc3d8c51 | |||
| e77ce7c286 | |||
| f7a86948ba | |||
| 490c58f528 | |||
| af39c0af7f | |||
| 913cf3d39f | |||
| 55974b90fd | |||
| 13f2fb9306 | |||
| 776a3c11b4 | |||
| d89080116e | |||
| 049f1ef4e7 | |||
| cbe50e998d | |||
| 645190405f | |||
| d86d581021 | |||
| 9acd8574be | |||
| a17abdcfdb | |||
| 010b0950f2 | |||
| 52e03d1627 | |||
| 01b56c943e | |||
| 6be438519c | |||
| afaaa1cfb2 | |||
| 8baa34e961 | |||
| fecd101fd0 | |||
| b13f670798 | |||
| c4ee51d05d | |||
| d86cb8d0fd | |||
| fbe9b68518 | |||
| 4cf388139a | |||
| 0dead6a233 | |||
| b5d4085a4b | |||
| b813e88634 | |||
| 98fed0d7be | |||
| 818b08b662 | |||
| f76474280d | |||
| 63b164dafc | |||
| 29b339b2b6 | |||
| 228e75039f | |||
| ce8a13e8d6 | |||
| bc3532ce2c | |||
| 674a01b90a | |||
| 3baab9feaf | |||
| 629719eb26 | |||
| 27e9202e25 | |||
| 66c1678d34 | |||
| d24ea89ed1 | |||
| 9787917d11 | |||
| 24174dbf98 | |||
| 7c699dc273 | |||
| 7b8fa22b0e | |||
| 5923dd002a | |||
| 5b76f56a54 | |||
| d994a67b9c | |||
| c4ce39d78b | |||
| c2ce1585a5 | |||
| 1dd21643c8 | |||
| c7e2d88aa7 | |||
| 041895dbf7 | |||
| f01df5005c | |||
| bcd6a5aa4a | |||
| 556b559b44 | |||
| 6464d54ca4 | |||
| fe97d634fe | |||
| 8e283afb7d | |||
| ec7bc4f626 | |||
| eaad1362cf | |||
| a35e7bc8a6 | |||
| 3111b37dc5 | |||
| e384af86dc | |||
| 65d0ee9132 | |||
| 908d720d8b | |||
| 8846b94634 | |||
| 304ebb7698 | |||
| ceffe6fd0c | |||
| 9426e83fa6 | |||
| 25ae774ec3 | |||
| 88fec4ffdb | |||
| 01d90cfb2c | |||
| ea1aec1250 | |||
| 97e627221c | |||
| 7c02044f4d | |||
| e58b466b2c | |||
| 6260f5082e | |||
| c5afab85ae | |||
| 0935a41174 | |||
| 1cacc6e119 | |||
| 1e50fcedac | |||
| 0a9b90d44e | |||
| 1bd5f669ec | |||
| dbd245ca6c | |||
| 6c149172cc | |||
| e03f5d469e | |||
| e045d9e64f | |||
| 171bf21084 | |||
| f03b64d91b | |||
| 0fe4eaae0c | |||
| 76f8774d28 | |||
| 4af35c04d7 | |||
| aaf6e3560e | |||
| 6685814ddb | |||
| fb37f8cc00 | |||
| 7bec9cdc67 | |||
| a924f11f05 | |||
| faf4d4e845 | |||
| fa026991c3 | |||
| 2976f30056 | |||
| c03deca3a7 | |||
| 1013dd2c86 | |||
| 8e34a7236c | |||
| 2ee1f1caed | |||
| 9d324120ed | |||
| 7bca943849 | |||
| 92759e41d7 | |||
| 1ba6e3be61 | |||
| 3e74dd711b | |||
| 6000fabfc0 | |||
| a25dd93be2 | |||
| f2c018d993 | |||
| b772c4bcc2 | |||
| 09589bf37f | |||
| 927f2033bf | |||
| 47f1e165da | |||
| 6e808bf367 | |||
| e0649ebac6 | |||
| 85073ebbad | |||
| aa4d719fb2 | |||
| 5cd7702ae8 | |||
| ac2e48557e | |||
| a8f985768f | |||
| ba8232bcef | |||
| 8f969d8a44 | |||
| db848ca86e | |||
| dad1e54b34 | |||
| 51ada7f094 | |||
| 3f5a60a560 | |||
| 5e62c8d053 | |||
| f53f3f29b2 | |||
| 727fb2112b | |||
| f86989e722 | |||
| b2e487262c | |||
| c462585543 | |||
| 49f6b14c24 | |||
| aff44c76b8 | |||
| e8b9a437d5 | |||
| dce97b45cb | |||
| 785a46e5a3 | |||
| b05f167b01 | |||
| b3c00e3e5c | |||
| 9a92344387 | |||
| c5c3209d21 | |||
| 47299cc4b6 | |||
| fbefbda31f | |||
| 9f95b68687 | |||
| fa7a32d913 | |||
| 1c3a8edfa3 | |||
| 43e90f8162 | |||
| da520af8d2 | |||
| 70e083f031 | |||
| 15f1729772 | |||
| 8accf4f3b9 | |||
| 9abf7b25e6 | |||
| 8cd785d1ac | |||
| a95b4c8226 | |||
| 0fdebb9100 | |||
| b079d53841 | |||
| 10ff10dce6 | |||
| 7012998923 | |||
| d68b3d284e | |||
| b7ab016f8e | |||
| cfcd0f070e | |||
| e2abff960f | |||
| c3ae71ad76 | |||
| 6a8bf6f762 | |||
| a3a229d958 | |||
| d4858ad9f1 | |||
| 469f76fda5 | |||
| ade78d6456 | |||
| afc6b73015 | |||
| d28445113c | |||
| 4ccdfeb9f9 | |||
| 74100a5aaf | |||
| 33de143501 | |||
| a6be13fd8a | |||
| cbc9ea42b3 | |||
| fca0075730 | |||
| 3f3d41a5a8 | |||
| 71d94dda5e | |||
| 31f38e2aee | |||
| b50803bba5 | |||
| ee4dd3a2ac | |||
| 9826746705 | |||
| c415246a5f | |||
| 3169f13540 | |||
| 5be64f28f3 | |||
| ced973d01b | |||
| 4ad4fa15eb | |||
| f83f419eec | |||
| f45910e1ca | |||
| 4d84e203c8 | |||
| 075ccbf2b7 | |||
| ea261db04b | |||
| 26624423b7 | |||
| 174fd0d4f3 | |||
| adc07c5027 | |||
| 68cb83d32a | |||
| b253f9f44c | |||
| 3e69cc5e35 | |||
| b10a2b4cdb | |||
| c52ac00cd5 | |||
| db34d2c377 | |||
| 9c49298272 | |||
| 35e9f046f3 | |||
| 95e8c6ec15 | |||
| 3a8d71c2b5 | |||
| d24d5a87e1 | |||
| 7289dcc22c | |||
| b045c6a006 | |||
| 041e5cd294 | |||
| 0188ccb117 | |||
| c5d1510423 | |||
| 4c2ff3c875 | |||
| d4662d2416 | |||
| d94a692cce | |||
| c1e8a25aae | |||
| 74fd88fb3d | |||
| cf48fae376 | |||
| bc66329f3f | |||
| 3399661809 | |||
| 3694704470 | |||
| 1caed7f2c2 | |||
| 795f4d272a | |||
| 9c6143a55a | |||
| 728c7763e2 | |||
| e262e4b4fe | |||
| eb753582c1 | |||
| f5d383ec94 | |||
| 7358c924ad |
120
AGENTS.md
Normal file
120
AGENTS.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Project Overview
|
||||
|
||||
Heimgeist is a local desktop chat app for Ollama. It uses a React/Vite renderer, a Tauri desktop shell, a FastAPI backend, SQLite chat storage, Whisper transcription, optional SearXNG web search, and local RAG libraries under the backend.
|
||||
|
||||
## Important Directories and Entry Points
|
||||
|
||||
- `src/` - React renderer code.
|
||||
- `src/main.jsx` mounts the app.
|
||||
- `src/App.jsx` owns most chat UI state, session flow, model startup checks, and library/sidebar orchestration.
|
||||
- `src/chatApi.js`, `src/chatGeneration.js`, and `src/backendApi.js` contain backend request and streaming helpers.
|
||||
- `src/desktop/desktopApi.js` is the renderer platform abstraction for desktop APIs.
|
||||
- `src/styles.css` contains the main UI styling.
|
||||
- `src-tauri/` - Tauri desktop shell.
|
||||
- `src-tauri/src/main.rs` owns Tauri commands for the renderer `desktopApi` surface, settings persistence, dialogs, path opening, external links, focus events, and update placeholders.
|
||||
- `src-tauri/tauri.conf.json` points Tauri at the existing Vite renderer.
|
||||
- `src-tauri/capabilities/` contains Tauri permission grants for enabled plugins.
|
||||
- `backend/` - FastAPI backend and local processing.
|
||||
- `backend/main.py` defines chat, session, model, audio, Ollama, and web search routes.
|
||||
- `backend/sidecar_main.py` is the PyInstaller entrypoint used by packaged Tauri builds to start `backend.main:app`.
|
||||
- `backend/local_rag.py` defines library, file registration, job, and local context routes.
|
||||
- `backend/paths.py` centralizes backend runtime data paths for SQLite and local RAG libraries.
|
||||
- `backend/schemas.py` and `backend/models.py` define API and database data shapes.
|
||||
- `backend/rag/` contains corpus, enrichment, embedding, indexing, and retrieval helpers.
|
||||
- `backend/database.py` gets the SQLite path from `backend/paths.py`.
|
||||
- `scripts/` - development wrappers used by npm scripts.
|
||||
- `scripts/run-backend.cjs` starts Uvicorn from `backend/.venv`.
|
||||
- `scripts/run-tauri-dev.cjs` starts or reuses FastAPI, then launches the Tauri dev shell.
|
||||
- `scripts/build-backend-sidecar.cjs` builds the PyInstaller backend sidecar and helper binaries for Tauri packaging.
|
||||
- `run.sh` - bootstrap script for local development dependencies and dev startup.
|
||||
- `vite.config.js` - Vite dev/build configuration. Tauri dev uses the strict Vite port `127.0.0.1:5174`.
|
||||
|
||||
## Run and Build Commands
|
||||
|
||||
- `./run.sh` - bootstrap/update Python and npm dependencies, then start the full dev stack.
|
||||
- `npm run dev` - start or reuse FastAPI on `127.0.0.1:8000`, start the Vite renderer on `127.0.0.1:5174`, then launch Tauri.
|
||||
- `npm run dev:tauri` - alias for the primary Tauri development workflow.
|
||||
- `npm run dev:backend` - start FastAPI on `127.0.0.1:8000` with reload. Requires `backend/.venv`.
|
||||
- `npm run dev:renderer` - start Vite on `127.0.0.1:5174` for Tauri.
|
||||
- `npm run dev:tauri:shell` - launch the raw Tauri shell when backend lifecycle is managed separately.
|
||||
- `npm run build` - build the renderer into `dist/`.
|
||||
- `npm run build:sidecar` - build the PyInstaller backend sidecar and helper binaries into `src-tauri/binaries/`.
|
||||
- `npm run package:mac` - build the sidecar and produce `src-tauri/target/release/bundle/macos/Heimgeist.app`.
|
||||
- `npm run build:app` - alias for `npm run package:mac`.
|
||||
- `npm start` - alias for `npm run dev`.
|
||||
|
||||
There are currently no npm `test` or `lint` scripts in `package.json`.
|
||||
|
||||
## Architectural Boundaries
|
||||
|
||||
- Renderer code should remain platform-neutral where practical. It may call backend HTTP APIs and may call `desktopApi`, but it should not import or call Tauri APIs directly.
|
||||
- `src/desktop/desktopApi.js` is the renderer's platform abstraction. Add desktop capabilities there first, then back them with Tauri commands/events.
|
||||
- `src-tauri/src/main.rs` owns desktop concerns: windows, menus, dialogs, shell opening, settings persistence, update placeholders, focus events, and Tauri command implementations.
|
||||
- `src-tauri/src/main.rs` also starts the packaged backend sidecar in release builds, waits for `/health`, passes app-managed data-path environment, and shuts the sidecar down when the app exits.
|
||||
- `backend/paths.py` owns backend runtime path resolution. Default development paths must remain `backend/app.db` and `backend/libraries`; packaged launchers pass app-managed paths through internal environment hooks.
|
||||
- Backend code owns chat/session persistence, Ollama integration, Whisper transcription, web search enrichment, and RAG library processing.
|
||||
- Backend API contracts should stay stable unless intentionally coordinated with renderer changes. If a response/request shape changes in `backend/schemas.py` or route handlers, update the renderer callers in the same change.
|
||||
- Keep local RAG job orchestration and generated library state in the backend. Renderer code should use backend endpoints rather than reading library files directly.
|
||||
|
||||
## Generated and Runtime Data
|
||||
|
||||
Do not edit or commit generated/runtime data unless the task explicitly requires it:
|
||||
|
||||
- `backend/app.db` and any `*.db` files - local SQLite runtime data.
|
||||
- `backend/libraries/` - local RAG library metadata, corpora, enrichment outputs, embeddings, indexes, and job state.
|
||||
- `backend/.venv/` and `.venv/` - Python virtual environments.
|
||||
- `node_modules/` - npm dependencies.
|
||||
- `dist/` - Vite build output.
|
||||
- `__pycache__/`, `*.pyc`, `.DS_Store`, and similar machine-generated files.
|
||||
- Local app settings files under the Tauri app config directory or `HEIMGEIST_SETTINGS_FILE`.
|
||||
- Packaged-build backend data directories supplied through internal deployment hooks such as `HEIMGEIST_DATA_DIR`, `HEIMGEIST_DB_PATH`, or `HEIMGEIST_LIB_ROOT`.
|
||||
- Tauri-generated `src-tauri/target/`, `src-tauri/gen/`, and local `src-tauri/Cargo.lock` if generated by local verification.
|
||||
- Generated sidecar binaries in `src-tauri/binaries/` except `src-tauri/binaries/.gitignore`.
|
||||
|
||||
Avoid broad file operations that traverse these directories. Use ignore patterns with search tools when inspecting the repo.
|
||||
|
||||
## Verification Expectations
|
||||
|
||||
- Frontend changes: run `npm run build` at minimum. For UI or interaction changes, also run the dev stack and exercise the affected flow in Tauri.
|
||||
- Backend changes: run a targeted syntax/import check such as `backend/.venv/bin/python -m py_compile backend/main.py backend/local_rag.py` for touched modules, then start `npm run dev:backend` or the full dev stack and check `GET /health`.
|
||||
- Desktop bridge/Tauri changes: run `cargo check --manifest-path src-tauri/Cargo.toml` with a temp `CARGO_TARGET_DIR` when useful, run `npm run build`, and if practical run `npm run dev`. Use a temporary `HEIMGEIST_SETTINGS_FILE` when testing ordinary shared settings behavior; use a temporary `HOME` with a fake legacy settings file when testing first-run import, because `HEIMGEIST_SETTINGS_FILE` intentionally bypasses import.
|
||||
- Tauri packaging changes: run `npm run build:sidecar`, then `npm run package:mac` on macOS. Verify `src-tauri/target/release/bundle/macos/Heimgeist.app` exists, launches, starts or reuses a compatible backend on `127.0.0.1:8000`, uses app-managed data outside the app bundle, and stops its sidecar processes on quit.
|
||||
- API contract changes: verify both sides together. Update backend schemas/routes and renderer callers in the same change, then exercise the affected request path.
|
||||
- RAG, Whisper, Ollama, or SearXNG changes: note any external services or local models required for verification, and test graceful failure paths when those services are unavailable.
|
||||
|
||||
## Tauri Guidance
|
||||
|
||||
- Keep renderer desktop calls behind `src/desktop/desktopApi.js`; do not import Tauri APIs directly in React components.
|
||||
- When adding desktop capabilities, prefer method names and payloads that stay stable for renderer callers.
|
||||
- Preserve `HEIMGEIST_SETTINGS_FILE` as an explicit shared settings override.
|
||||
- Keep first-run legacy settings import available when Tauri settings do not already exist.
|
||||
- Do not move or rewrite `backend/app.db` or `backend/libraries`; the development backend must keep using the existing backend working directory.
|
||||
- Treat `HEIMGEIST_DATA_DIR`, `HEIMGEIST_DB_PATH`, and `HEIMGEIST_LIB_ROOT` as internal app/sidecar deployment hooks only. Do not expose them in the UI or document them as normal user configuration.
|
||||
- Packaged Tauri builds use `backend/sidecar_main.py` and `scripts/build-backend-sidecar.cjs` to bundle the FastAPI backend. Do not move or migrate development data into the packaged app data directory as part of packaging.
|
||||
- Production-release work still needs signed updater/changelog parity, final bundle metadata, signing/notarization, full Windows/Linux packaging scripts, and installer behavior.
|
||||
- Avoid refactors that mix migration prep with unrelated feature work. Migration work should be explicit and reviewable.
|
||||
|
||||
## Coding and Refactor Guidelines
|
||||
|
||||
- Keep changes scoped to the request. Do not refactor large files such as `src/App.jsx`, `src/styles.css`, `backend/main.py`, or `backend/local_rag.py` unless the task needs it.
|
||||
- Prefer existing helper modules and patterns over new abstractions.
|
||||
- Preserve stable backend contracts and persisted data compatibility. Add small migration helpers when changing database-backed fields.
|
||||
- Keep settings keys backward compatible where possible. Existing settings migrations live in Tauri and backend settings helpers.
|
||||
- Use structured JSON/schema changes rather than ad hoc string parsing for API payloads.
|
||||
- Add comments only where they explain non-obvious control flow, concurrency, migration, or integration behavior.
|
||||
- Do not silently swallow errors in user-facing flows; surface useful messages while preserving graceful degradation for optional services.
|
||||
- Do not mix formatting churn with behavior changes.
|
||||
|
||||
## Known Fragile Areas
|
||||
|
||||
- The Tauri bridge is intentionally narrow. Direct `window.__TAURI__` use outside `src/desktop/desktopApi.js` makes desktop behavior harder to reason about.
|
||||
- `src/App.jsx`, `src/chatGeneration.js`, and backend chat routes share assumptions about streaming, regeneration, attachments, source metadata, and session state.
|
||||
- `backend/main.py` creates/migrates SQLite tables at import/startup. Schema changes need care because they run against local user data.
|
||||
- `backend/paths.py` controls where chat and local RAG data are stored. Preserve development defaults unless the task explicitly concerns packaged app data paths.
|
||||
- `backend/local_rag.py` coordinates asynchronous jobs, file registration, generated artifacts, and per-library locks. Avoid changes that can start duplicate jobs or corrupt `backend/libraries/`.
|
||||
- RAG builders under `backend/rag/` run heavier file processing and subprocess/threaded work. Test with small inputs before broader runs.
|
||||
- Whisper depends on ffmpeg/ffprobe paths supplied by the Node backend runner when available.
|
||||
- Web search depends on an optional SearXNG instance, usually `http://127.0.0.1:8888`; features should fail gracefully when it is absent.
|
||||
- Ollama availability, model names, embedding model choices, and vision capability checks are runtime-dependent. Keep related UI and backend paths tolerant of missing models.
|
||||
142
README.md
Normal file
142
README.md
Normal file
@@ -0,0 +1,142 @@
|
||||
# Heimgeist
|
||||
|
||||
Heimgeist is a local desktop chat client for Ollama. It combines a Tauri + React renderer with a FastAPI backend, stores chat history in SQLite, supports optional SearXNG-backed web search, and can enrich prompts with context from local library indexes.
|
||||
|
||||
## Features
|
||||
|
||||
- Local desktop chat UI with Tauri
|
||||
- Ollama-backed chat with streaming and non-streaming replies
|
||||
- Persistent chat sessions and automatic title generation
|
||||
- Edit-and-regenerate flow for earlier user messages
|
||||
- Optional web search enrichment with source chips
|
||||
- Local library management for RAG-style prompt enrichment
|
||||
- Theme selection and UI scale controls
|
||||
|
||||
## Local Libraries
|
||||
|
||||
The `DBs` tab is no longer a placeholder. You can:
|
||||
|
||||
- create and rename libraries
|
||||
- register files
|
||||
- let Heimgeist rebuild retrieval automatically when files change
|
||||
- open or remove registered files from the UI
|
||||
|
||||
When files are added or removed, Heimgeist automatically rebuilds the local RAG pipeline for that database: corpus, enrichment, embeddings, and indexes. In the chat composer, you can select which database the current chat should use. For each chat turn, Heimgeist queries the selected database, turns the top results into a local context block, appends that block to the user prompt, and sends the enriched prompt to Ollama.
|
||||
|
||||
## Local Data
|
||||
|
||||
Heimgeist stores chat history and local library indexes on the local machine. During development, the backend keeps using `backend/app.db` and `backend/libraries` so existing local data remains available.
|
||||
|
||||
Packaged Tauri builds launch the bundled backend with app-managed data paths so chats and local libraries live under the operating system's normal application data location, such as Application Support on macOS, LocalAppData on Windows, or the XDG data directory on Linux. These paths are managed by the app and are not exposed as normal user settings.
|
||||
|
||||
## Stack
|
||||
|
||||
- Frontend: Tauri, React, Vite
|
||||
- Backend: FastAPI, SQLAlchemy, SQLite
|
||||
- Search enrichment: SearXNG + page fetching/reranking
|
||||
- Local RAG pipeline: corpus build, enrichment, embedding, and retrieval helpers under `backend/rag/`
|
||||
|
||||
## Development
|
||||
|
||||
Requirements:
|
||||
|
||||
- Ollama running locally
|
||||
- Optional: SearXNG on `http://127.0.0.1:8888`
|
||||
|
||||
Quick start:
|
||||
|
||||
```bash
|
||||
./run.sh
|
||||
```
|
||||
|
||||
This bootstraps the development environment and starts the dev stack. On a fresh machine it installs:
|
||||
|
||||
- the native Tauri prerequisites through `pacman` on Arch/SteamOS or `apt-get` on Debian/Ubuntu
|
||||
- stable Rust and Cargo through `rustup`
|
||||
- Python 3.13 through `uv`
|
||||
- Node.js 22 LTS and npm from the official Node.js binaries
|
||||
- the project's Python and npm dependencies
|
||||
|
||||
SteamOS temporarily requires a writable root filesystem while native packages are installed. `run.sh` disables the read-only mode only around `pacman`, restores it afterward, and may ask for the user's sudo password. It also initializes and populates the SteamOS pacman keyring before installing packages, because a fresh or updated Steam Deck can otherwise reject valid packages with "unknown trust" / PGP signature errors. If that keyring repair is still insufficient and SteamOS provides `steamos-devmode`, `run.sh` uses it as a final SteamOS bootstrap fallback. Set `HEIMGEIST_STEAMOS_DEVMODE=0` to skip that fallback. SteamOS system updates can remove manually installed system packages; rerunning `./run.sh` restores any missing prerequisites.
|
||||
|
||||
Downloads and package installation are skipped when usable dependencies already exist. Node.js archives are verified with their published SHA-256 checksum. Use `HEIMGEIST_BOOTSTRAP_ONLY=1 ./run.sh` to install/check dependencies without launching Heimgeist, or `HEIMGEIST_SKIP_SYSTEM_DEPS=1 ./run.sh` when native Tauri dependencies are managed externally. If the package manager succeeds but the native dependency preflight still cannot verify a `pkg-config` module, `run.sh` prints a preflight report and continues so the real Tauri build can produce the authoritative compiler/linker error. Set `HEIMGEIST_STRICT_SYSTEM_DEPS=1` to make that preflight warning fatal. `HEIMGEIST_NODE_MAJOR`, `HEIMGEIST_NODE_DIR`, `HEIMGEIST_TOOL_BIN_DIR`, `CARGO_HOME`, `RUSTUP_HOME`, `PYTHON_BIN`, `HEIMGEIST_STEAMOS_DEVMODE`, and `HEIMGEIST_STRICT_SYSTEM_DEPS` provide explicit runtime overrides.
|
||||
|
||||
On Linux `x86_64`, `run.sh` now selects a PyTorch flavor before installing `openai-whisper`:
|
||||
|
||||
- Steam Deck / SteamOS and other non-NVIDIA Linux hosts default to CPU-only PyTorch, which avoids downloading NVIDIA CUDA runtime wheels that Whisper does not need there.
|
||||
- NVIDIA Linux hosts keep the default PyTorch install path.
|
||||
- Override with `HEIMGEIST_TORCH_FLAVOR=default`, `HEIMGEIST_TORCH_FLAVOR=cpu`, or `HEIMGEIST_TORCH_FLAVOR=rocm6.4`.
|
||||
- Use `HEIMGEIST_TORCH_INDEX_URL=...` if you need a custom PyTorch wheel index.
|
||||
|
||||
Manual startup:
|
||||
|
||||
```bash
|
||||
python3.13 -m venv backend/.venv
|
||||
backend/.venv/bin/python -m pip install --upgrade pip
|
||||
# Steam Deck / SteamOS / CPU-only Linux:
|
||||
# backend/.venv/bin/python -m pip install --index-url https://download.pytorch.org/whl/cpu torch
|
||||
backend/.venv/bin/python -m pip install -r backend/requirements.txt
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## Local macOS Packaging
|
||||
|
||||
Requirements:
|
||||
|
||||
- `backend/.venv` with backend dependencies installed
|
||||
- Rust/Tauri build prerequisites
|
||||
- Ollama installed and running separately
|
||||
- Optional: SearXNG on `http://127.0.0.1:8888`
|
||||
|
||||
Build a local macOS app bundle:
|
||||
|
||||
```bash
|
||||
npm run package:mac
|
||||
```
|
||||
|
||||
This builds the React renderer, creates a PyInstaller backend sidecar from `backend/.venv`, bundles ffmpeg/ffprobe helpers when available from npm dependencies, and runs `tauri build --bundles app`.
|
||||
|
||||
The `.app` is written to:
|
||||
|
||||
```text
|
||||
src-tauri/target/release/bundle/macos/Heimgeist.app
|
||||
```
|
||||
|
||||
The packaged app starts its own FastAPI backend sidecar on `127.0.0.1:8000`. Ollama remains an external requirement, and SearXNG remains optional.
|
||||
|
||||
## File Tree
|
||||
|
||||
```text
|
||||
.
|
||||
├── backend/
|
||||
│ ├── main.py
|
||||
│ ├── sidecar_main.py
|
||||
│ ├── local_rag.py
|
||||
│ ├── rag/
|
||||
│ ├── websearch.py
|
||||
│ ├── ollama_client.py
|
||||
│ ├── models.py
|
||||
│ ├── database.py
|
||||
│ ├── paths.py
|
||||
│ ├── schemas.py
|
||||
│ └── requirements.txt
|
||||
├── src-tauri/
|
||||
│ ├── src/main.rs
|
||||
│ ├── tauri.conf.json
|
||||
│ ├── binaries/
|
||||
│ └── capabilities/
|
||||
├── src/
|
||||
│ ├── App.jsx
|
||||
│ ├── LibraryManager.jsx
|
||||
│ ├── GeneralSettings.jsx
|
||||
│ ├── InterfaceSettings.jsx
|
||||
│ ├── WebsearchSettings.jsx
|
||||
│ ├── markdown.js
|
||||
│ ├── colorSchemes.js
|
||||
│ └── styles.css
|
||||
├── package.json
|
||||
├── run.sh
|
||||
├── scripts/
|
||||
└── vite.config.js
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
# The macOS wheels for PyTorch (used by Whisper) and FAISS bundle different
|
||||
# libomp copies. FAISS aborts the process when its copy initializes second.
|
||||
if sys.platform == "darwin":
|
||||
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
||||
|
||||
5
backend/agent/__init__.py
Normal file
5
backend/agent/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Native Heimgeist tools and validated workflow execution."""
|
||||
|
||||
from .registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
__all__ = ["NativeToolProvider", "ToolDefinition", "ToolExecutionContext"]
|
||||
642
backend/agent/api.py
Normal file
642
backend/agent/api.py
Normal file
@@ -0,0 +1,642 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import models as chat_models
|
||||
from ..chat_memory import safe_sync_chat_memory_for_session
|
||||
from ..database import Base, SessionLocal, engine
|
||||
from ..local_rag import ensure_global_knowledge_store, global_library_slug
|
||||
from .events import EventWriter
|
||||
from .models import (
|
||||
WorkflowConfirmation,
|
||||
WorkflowDefinition,
|
||||
WorkflowEvent,
|
||||
WorkflowNodeRun,
|
||||
WorkflowRevision,
|
||||
WorkflowRun,
|
||||
)
|
||||
from .registry import NativeToolProvider
|
||||
from .router import select_workflow
|
||||
from .runtime import WorkflowRuntime
|
||||
from .schemas import (
|
||||
ConfirmationResponseRequest,
|
||||
RouterSelectRequest,
|
||||
WorkflowCreateRequest,
|
||||
WorkflowRevisionRequest,
|
||||
WorkflowRunRequest,
|
||||
WorkflowUpdateRequest,
|
||||
WorkflowValidateRequest,
|
||||
)
|
||||
from .tools import register_native_tools
|
||||
from .validation import validate_workflow_graph
|
||||
from .workflows import seed_builtin_workflows
|
||||
|
||||
|
||||
router = APIRouter(tags=["agent-workflows"])
|
||||
registry = NativeToolProvider()
|
||||
register_native_tools(registry)
|
||||
runtime = WorkflowRuntime(registry, SessionLocal)
|
||||
|
||||
|
||||
def _json(value: Optional[str], fallback: Any) -> Any:
|
||||
try:
|
||||
return json.loads(value) if value else fallback
|
||||
except Exception:
|
||||
return fallback
|
||||
|
||||
|
||||
def _checksum(graph: Dict[str, Any]) -> str:
|
||||
canonical = json.dumps(graph, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _slugify(value: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", str(value or "").strip().lower()).strip("-")
|
||||
return slug[:90] or f"workflow-{uuid.uuid4().hex[:8]}"
|
||||
|
||||
|
||||
_REMEMBER_CONTENT_PATTERNS = [
|
||||
re.compile(r"^\s*(?:please\s+)?remember\s+this\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r"^\s*(?:please\s+)?remember\s+that\s+(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r"^\s*(?:please\s+)?save\s+this\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r"^\s*(?:please\s+)?save\s+that\s+(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r"^\s*(?:bitte\s+)?merk\s+dir\s+das\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r"^\s*(?:bitte\s+)?merk\s+dir\s+(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
re.compile(r"^\s*(?:bitte\s+)?speicher(?:e)?\s+(?:das|dies|diese|diesen)\s*[:\-–—]\s*(.+)$", re.IGNORECASE | re.DOTALL),
|
||||
]
|
||||
|
||||
|
||||
def _extract_remember_content(message: str) -> Optional[str]:
|
||||
text = str(message or "").strip()
|
||||
for pattern in _REMEMBER_CONTENT_PATTERNS:
|
||||
match = pattern.match(text)
|
||||
if match:
|
||||
content = match.group(1).strip()
|
||||
return content or None
|
||||
return None
|
||||
|
||||
|
||||
def _clean_search_queries(raw: Any, fallback: str) -> list[str]:
|
||||
values = raw if isinstance(raw, list) else [raw]
|
||||
cleaned: list[str] = []
|
||||
seen = set()
|
||||
for item in values:
|
||||
text = " ".join(str(item or "").split()).strip()
|
||||
if not text:
|
||||
continue
|
||||
key = text.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
cleaned.append(text[:300])
|
||||
if len(cleaned) >= 5:
|
||||
break
|
||||
fallback_text = " ".join(str(fallback or "").split()).strip()
|
||||
if fallback_text and not cleaned:
|
||||
cleaned.append(fallback_text[:300])
|
||||
return cleaned
|
||||
|
||||
|
||||
def _resolve_web_search_inputs(sample_inputs: Dict[str, Any], message: str) -> tuple[str, list[str]]:
|
||||
raw_queries = sample_inputs.get("web_search_queries")
|
||||
if raw_queries is None:
|
||||
raw_queries = sample_inputs.get("search_queries")
|
||||
raw_query = sample_inputs.get("web_search_query") or sample_inputs.get("search_query")
|
||||
queries = _clean_search_queries(raw_queries if raw_queries is not None else raw_query, message)
|
||||
if raw_query:
|
||||
raw_query_text = " ".join(str(raw_query).split()).strip()
|
||||
if raw_query_text and raw_query_text.casefold() not in {item.casefold() for item in queries}:
|
||||
queries.insert(0, raw_query_text[:300])
|
||||
queries = queries[:5]
|
||||
query = queries[0] if queries else str(message or "")[:300]
|
||||
return query, queries or [query]
|
||||
|
||||
|
||||
def initialize_agent_system() -> None:
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db.query(WorkflowRun).filter(WorkflowRun.status.in_(["queued", "running", "waiting_confirmation"])).update(
|
||||
{
|
||||
WorkflowRun.status: "interrupted",
|
||||
WorkflowRun.error_json: json.dumps({"message": "Backend restarted before the workflow completed."}),
|
||||
WorkflowRun.finished_at: datetime.utcnow(),
|
||||
},
|
||||
synchronize_session=False,
|
||||
)
|
||||
db.commit()
|
||||
seed_builtin_workflows(db)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _workflow_payload(workflow: WorkflowDefinition, db: Session, *, include_graph: bool = False) -> Dict[str, Any]:
|
||||
revision = None
|
||||
if workflow.current_revision_id:
|
||||
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == workflow.current_revision_id).first()
|
||||
payload = {
|
||||
"id": workflow.id,
|
||||
"slug": workflow.slug,
|
||||
"name": workflow.name,
|
||||
"description": workflow.description,
|
||||
"current_revision_id": workflow.current_revision_id,
|
||||
"current_version": revision.version if revision else None,
|
||||
"built_in": workflow.built_in,
|
||||
"enabled": workflow.enabled,
|
||||
"routing_description": workflow.routing_description,
|
||||
"routing_examples": _json(workflow.routing_examples_json, []),
|
||||
"estimated_cost_class": workflow.estimated_cost_class,
|
||||
"required_capabilities": _json(workflow.required_capabilities_json, []),
|
||||
"created_at": workflow.created_at.isoformat() if workflow.created_at else None,
|
||||
"updated_at": workflow.updated_at.isoformat() if workflow.updated_at else None,
|
||||
}
|
||||
if include_graph:
|
||||
payload["graph"] = _json(revision.graph_json if revision else None, {})
|
||||
payload["revisions"] = [
|
||||
{
|
||||
"id": item.id, "version": item.version, "created_at": item.created_at.isoformat(),
|
||||
"created_by": item.created_by, "trusted": item.trusted, "checksum": item.checksum,
|
||||
}
|
||||
for item in db.query(WorkflowRevision).filter(WorkflowRevision.workflow_id == workflow.id).order_by(WorkflowRevision.version.desc()).all()
|
||||
]
|
||||
return payload
|
||||
|
||||
|
||||
def _find_workflow(db: Session, workflow_id: str) -> WorkflowDefinition:
|
||||
workflow = db.query(WorkflowDefinition).filter(
|
||||
(WorkflowDefinition.id == workflow_id) | (WorkflowDefinition.slug == workflow_id)
|
||||
).first()
|
||||
if workflow is None:
|
||||
raise HTTPException(status_code=404, detail="Workflow not found.")
|
||||
return workflow
|
||||
|
||||
|
||||
def _run_payload(run: WorkflowRun, db: Session) -> Dict[str, Any]:
|
||||
node_runs = db.query(WorkflowNodeRun).filter(WorkflowNodeRun.workflow_run_id == run.id).order_by(WorkflowNodeRun.started_at.asc()).all()
|
||||
confirmations = db.query(WorkflowConfirmation).filter(WorkflowConfirmation.workflow_run_id == run.id).order_by(WorkflowConfirmation.created_at.asc()).all()
|
||||
return {
|
||||
"id": run.id, "workflow_id": run.workflow_id, "workflow_revision_id": run.workflow_revision_id,
|
||||
"session_id": run.session_id, "user_message_id": run.user_message_id, "status": run.status,
|
||||
"selection_mode": run.selection_mode, "inputs": _json(run.inputs_json, {}), "outputs": _json(run.outputs_json, None),
|
||||
"error": _json(run.error_json, None), "metrics": _json(run.metrics_json, {}),
|
||||
"started_at": run.started_at.isoformat() if run.started_at else None,
|
||||
"finished_at": run.finished_at.isoformat() if run.finished_at else None,
|
||||
"cancellation_requested": run.cancellation_requested,
|
||||
"node_runs": [{
|
||||
"id": item.id, "node_id": item.node_id, "attempt": item.attempt, "status": item.status,
|
||||
"resolved_inputs": _json(item.resolved_inputs_json, None), "outputs": _json(item.outputs_json, None),
|
||||
"error": _json(item.error_json, None), "metrics": _json(item.metrics_json, {}),
|
||||
"started_at": item.started_at.isoformat() if item.started_at else None,
|
||||
"finished_at": item.finished_at.isoformat() if item.finished_at else None,
|
||||
} for item in node_runs],
|
||||
"confirmations": [{
|
||||
"id": item.id, "node_id": item.node_id, "tool_name": item.tool_name, "status": item.status,
|
||||
"request": _json(item.request_json, {}), "response": _json(item.response_json, None),
|
||||
"created_at": item.created_at.isoformat() if item.created_at else None,
|
||||
"resolved_at": item.resolved_at.isoformat() if item.resolved_at else None,
|
||||
} for item in confirmations],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/tools")
|
||||
def list_tools():
|
||||
return {"tools": list(registry.list_tools())}
|
||||
|
||||
|
||||
@router.get("/workflows")
|
||||
def list_workflows():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
workflows = db.query(WorkflowDefinition).order_by(WorkflowDefinition.built_in.desc(), WorkflowDefinition.name.asc()).all()
|
||||
return {"workflows": [_workflow_payload(item, db) for item in workflows]}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/workflows")
|
||||
def create_workflow(request: WorkflowCreateRequest):
|
||||
validation = validate_workflow_graph(request.graph, registry)
|
||||
if not validation.valid:
|
||||
raise HTTPException(status_code=422, detail={"message": "Invalid workflow graph.", "errors": [item.model_dump() for item in validation.errors]})
|
||||
db = SessionLocal()
|
||||
try:
|
||||
slug = _slugify(request.slug or request.name)
|
||||
if db.query(WorkflowDefinition).filter(WorkflowDefinition.slug == slug).first():
|
||||
slug = f"{slug}-{uuid.uuid4().hex[:6]}"
|
||||
workflow = WorkflowDefinition(
|
||||
slug=slug, name=request.name.strip() or "Untitled Workflow", description=request.description,
|
||||
built_in=False, enabled=request.enabled, routing_description=request.routing_description,
|
||||
routing_examples_json=json.dumps(request.routing_examples),
|
||||
)
|
||||
db.add(workflow)
|
||||
db.flush()
|
||||
revision = WorkflowRevision(
|
||||
workflow_id=workflow.id, version=1, graph_json=json.dumps(request.graph, ensure_ascii=False),
|
||||
created_by="user", trusted=False, checksum=_checksum(request.graph),
|
||||
)
|
||||
db.add(revision)
|
||||
db.flush()
|
||||
workflow.current_revision_id = revision.id
|
||||
db.commit()
|
||||
db.refresh(workflow)
|
||||
return _workflow_payload(workflow, db, include_graph=True)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.get("/workflows/{workflow_id}")
|
||||
def get_workflow(workflow_id: str):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
return _workflow_payload(_find_workflow(db, workflow_id), db, include_graph=True)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/duplicate")
|
||||
def duplicate_workflow(workflow_id: str):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
source = _find_workflow(db, workflow_id)
|
||||
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == source.current_revision_id).first()
|
||||
workflow = WorkflowDefinition(
|
||||
slug=f"{_slugify(source.slug)}-copy-{uuid.uuid4().hex[:6]}", name=f"{source.name} Copy",
|
||||
description=source.description, built_in=False, enabled=True,
|
||||
routing_description=source.routing_description, routing_examples_json=source.routing_examples_json,
|
||||
estimated_cost_class=source.estimated_cost_class, required_capabilities_json=source.required_capabilities_json,
|
||||
)
|
||||
db.add(workflow)
|
||||
db.flush()
|
||||
copy_revision = WorkflowRevision(
|
||||
workflow_id=workflow.id, version=1, graph_json=revision.graph_json, created_by="user",
|
||||
trusted=False, checksum=revision.checksum,
|
||||
)
|
||||
db.add(copy_revision)
|
||||
db.flush()
|
||||
workflow.current_revision_id = copy_revision.id
|
||||
db.commit()
|
||||
return _workflow_payload(workflow, db, include_graph=True)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.put("/workflows/{workflow_id}")
|
||||
def update_workflow(workflow_id: str, request: WorkflowUpdateRequest):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
workflow = _find_workflow(db, workflow_id)
|
||||
updates = request.model_dump(exclude_unset=True)
|
||||
if "name" in updates:
|
||||
workflow.name = updates["name"].strip() or workflow.name
|
||||
if "description" in updates: workflow.description = updates["description"]
|
||||
if "routing_description" in updates: workflow.routing_description = updates["routing_description"]
|
||||
if "routing_examples" in updates: workflow.routing_examples_json = json.dumps(updates["routing_examples"])
|
||||
if "enabled" in updates: workflow.enabled = bool(updates["enabled"])
|
||||
workflow.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
return _workflow_payload(workflow, db, include_graph=True)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/revisions")
|
||||
def create_revision(workflow_id: str, request: WorkflowRevisionRequest):
|
||||
validation = validate_workflow_graph(request.graph, registry)
|
||||
if not validation.valid:
|
||||
raise HTTPException(status_code=422, detail={"message": "Invalid workflow graph.", "errors": [item.model_dump() for item in validation.errors]})
|
||||
db = SessionLocal()
|
||||
try:
|
||||
workflow = _find_workflow(db, workflow_id)
|
||||
if workflow.built_in:
|
||||
raise HTTPException(status_code=409, detail="Built-in workflows are read-only. Duplicate the workflow first.")
|
||||
latest = db.query(WorkflowRevision).filter(WorkflowRevision.workflow_id == workflow.id).order_by(WorkflowRevision.version.desc()).first()
|
||||
revision = WorkflowRevision(
|
||||
workflow_id=workflow.id, version=(latest.version + 1) if latest else 1,
|
||||
graph_json=json.dumps(request.graph, ensure_ascii=False), created_by=request.created_by,
|
||||
trusted=False, checksum=_checksum(request.graph),
|
||||
)
|
||||
db.add(revision)
|
||||
db.flush()
|
||||
workflow.current_revision_id = revision.id
|
||||
workflow.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
return _workflow_payload(workflow, db, include_graph=True)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/workflows/validate")
|
||||
def validate_workflow(request: WorkflowValidateRequest):
|
||||
return validate_workflow_graph(request.graph, registry).model_dump()
|
||||
|
||||
|
||||
@router.delete("/workflows/{workflow_id}")
|
||||
def delete_workflow(workflow_id: str):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
workflow = _find_workflow(db, workflow_id)
|
||||
if workflow.built_in:
|
||||
raise HTTPException(status_code=409, detail="Built-in workflows cannot be deleted.")
|
||||
db.delete(workflow)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
async def _select_for_run(
|
||||
db: Session,
|
||||
request: WorkflowRunRequest,
|
||||
) -> tuple[WorkflowDefinition, Optional[Dict[str, Any]]]:
|
||||
router_result = None
|
||||
if request.selection_mode == "automatic":
|
||||
ensure_global_knowledge_store()
|
||||
router_library_slug = request.library_slug or global_library_slug()
|
||||
recent_messages = []
|
||||
if request.session_id:
|
||||
session = db.query(chat_models.ChatSession).filter(chat_models.ChatSession.session_id == request.session_id).first()
|
||||
if session:
|
||||
rows = db.query(chat_models.ChatMessage).filter(chat_models.ChatMessage.session_pk == session.id).order_by(chat_models.ChatMessage.id.desc()).limit(4).all()
|
||||
recent_messages = [{"role": row.role, "content": row.content} for row in reversed(rows)]
|
||||
router_result = await select_workflow(
|
||||
db, message=request.message, recent_messages=recent_messages, attachments=request.attachments,
|
||||
library_slug=router_library_slug, router_model=request.router_model, chat_model=request.model,
|
||||
web_search_enabled=request.web_search_enabled,
|
||||
)
|
||||
workflow = _find_workflow(db, router_result["workflow_id"])
|
||||
elif request.selection_mode == "explicit":
|
||||
if not request.workflow_id:
|
||||
raise HTTPException(status_code=422, detail="Explicit workflow mode requires workflow_id.")
|
||||
workflow = _find_workflow(db, request.workflow_id)
|
||||
if not workflow.enabled:
|
||||
raise HTTPException(status_code=409, detail="The selected workflow is disabled.")
|
||||
else:
|
||||
workflow = _find_workflow(db, "input-output")
|
||||
return workflow, router_result
|
||||
|
||||
|
||||
@router.post("/workflow-runs")
|
||||
async def create_workflow_run(request: WorkflowRunRequest):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
workflow, router_result = await _select_for_run(db, request)
|
||||
revision_id = request.workflow_revision_id or workflow.current_revision_id
|
||||
if (
|
||||
request.workflow_revision_id
|
||||
and request.workflow_revision_id != workflow.current_revision_id
|
||||
and request.regenerate_index is None
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="The requested workflow revision is stale.")
|
||||
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == revision_id).first()
|
||||
if revision is None or revision.workflow_id != workflow.id:
|
||||
raise HTTPException(status_code=409, detail="The selected workflow has no current revision.")
|
||||
graph = _json(revision.graph_json, {})
|
||||
validation = validate_workflow_graph(graph, registry)
|
||||
if not validation.valid:
|
||||
raise HTTPException(status_code=422, detail={"message": "Invalid workflow graph.", "errors": [item.model_dump() for item in validation.errors]})
|
||||
|
||||
session = None
|
||||
user_message = None
|
||||
run_attachments = request.attachments
|
||||
sample_inputs = dict(request.sample_inputs)
|
||||
router_inputs = router_result.get("inputs") if isinstance(router_result, dict) else None
|
||||
if isinstance(router_inputs, dict):
|
||||
merged_inputs = dict(router_inputs)
|
||||
merged_inputs.update(sample_inputs)
|
||||
sample_inputs = merged_inputs
|
||||
target_message_id = sample_inputs.get("target_message_id") or sample_inputs.get("message_id")
|
||||
target_message_content = sample_inputs.get("target_message_content") or sample_inputs.get("edited_content")
|
||||
target_url = sample_inputs.get("target_url") or sample_inputs.get("url")
|
||||
if not target_url:
|
||||
url_match = re.search(r"https?://[^\s<>'\"]+", request.message or "")
|
||||
target_url = url_match.group(0).rstrip(".,);]") if url_match else None
|
||||
if request.session_id:
|
||||
session = db.query(chat_models.ChatSession).filter(chat_models.ChatSession.session_id == request.session_id).first()
|
||||
if session is None and request.regenerate_index is not None:
|
||||
raise HTTPException(status_code=404, detail="Chat session not found.")
|
||||
if session is None:
|
||||
session = chat_models.ChatSession(session_id=request.session_id)
|
||||
db.add(session)
|
||||
db.flush()
|
||||
previous_assistant_message_id = None
|
||||
if not target_message_id:
|
||||
previous_assistant = db.query(chat_models.ChatMessage).filter(
|
||||
chat_models.ChatMessage.session_pk == session.id,
|
||||
chat_models.ChatMessage.role == "assistant",
|
||||
).order_by(chat_models.ChatMessage.created_at.desc(), chat_models.ChatMessage.id.desc()).first()
|
||||
if previous_assistant:
|
||||
previous_assistant_message_id = previous_assistant.message_id
|
||||
from .. import main as main_module
|
||||
if request.regenerate_index is not None:
|
||||
rows = db.query(chat_models.ChatMessage).filter(
|
||||
chat_models.ChatMessage.session_pk == session.id
|
||||
).order_by(chat_models.ChatMessage.created_at.asc(), chat_models.ChatMessage.id.asc()).all()
|
||||
if request.regenerate_index >= len(rows):
|
||||
raise HTTPException(status_code=400, detail="Invalid regeneration message index.")
|
||||
user_index = request.regenerate_index
|
||||
while user_index >= 0 and rows[user_index].role != "user":
|
||||
user_index -= 1
|
||||
if user_index < 0:
|
||||
raise HTTPException(status_code=400, detail="No user message is available for regeneration.")
|
||||
user_message = rows[user_index]
|
||||
user_message.content = request.message
|
||||
for stale_message in rows[user_index + 1:]:
|
||||
db.delete(stale_message)
|
||||
stored_attachments = _json(user_message.attachments_json, [])
|
||||
run_attachments = request.attachments or stored_attachments
|
||||
db.flush()
|
||||
if not target_message_id and workflow.slug == "remember-this":
|
||||
target_message_id = user_message.message_id
|
||||
target_message_content = target_message_content or _extract_remember_content(request.message)
|
||||
else:
|
||||
attachments = [main_module._normalize_chat_attachment_or_raise(item, include_text=True) for item in request.attachments]
|
||||
run_attachments = attachments
|
||||
user_message = chat_models.ChatMessage(
|
||||
session_pk=session.id, role="user", content=request.message,
|
||||
attachments_json=json.dumps(attachments, ensure_ascii=False),
|
||||
)
|
||||
db.add(user_message)
|
||||
db.flush()
|
||||
if not target_message_id:
|
||||
if workflow.slug == "remember-this":
|
||||
target_message_id = user_message.message_id
|
||||
target_message_content = target_message_content or _extract_remember_content(request.message)
|
||||
elif previous_assistant_message_id:
|
||||
target_message_id = previous_assistant_message_id
|
||||
|
||||
messages = []
|
||||
if session:
|
||||
rows = db.query(chat_models.ChatMessage).filter(chat_models.ChatMessage.session_pk == session.id).order_by(chat_models.ChatMessage.id.asc()).all()[-20:]
|
||||
messages = [{"role": row.role, "content": row.content} for row in rows]
|
||||
else:
|
||||
messages = [{"role": "user", "content": request.message}]
|
||||
sample_inputs.setdefault("prompt", request.message)
|
||||
sample_inputs.setdefault("session_id", request.session_id)
|
||||
web_search_query, web_search_queries = _resolve_web_search_inputs(sample_inputs, request.message)
|
||||
try:
|
||||
required_capabilities = set(json.loads(workflow.required_capabilities_json or "[]"))
|
||||
except Exception:
|
||||
required_capabilities = set()
|
||||
knowledge_required = bool({"rag", "knowledge_write"} & required_capabilities)
|
||||
effective_library_slug = request.library_slug
|
||||
if knowledge_required:
|
||||
ensure_global_knowledge_store()
|
||||
effective_library_slug = effective_library_slug or global_library_slug()
|
||||
run_values = {
|
||||
"session_id": request.session_id,
|
||||
"chat_model": request.model,
|
||||
"router_model": request.router_model or request.model,
|
||||
"vision_model": request.vision_model,
|
||||
"transcription_model": request.transcription_model,
|
||||
"library_slug": effective_library_slug,
|
||||
"searx_url": request.searx_url,
|
||||
"searx_engines": request.searx_engines,
|
||||
"messages": messages,
|
||||
"attachments": run_attachments,
|
||||
"generation_options": request.generation_options,
|
||||
"context_blocks": [],
|
||||
"manual_library_enabled": bool(request.library_slug),
|
||||
"web_search_enabled": request.web_search_enabled,
|
||||
"compatibility_rag_enabled": bool(request.library_slug and "rag" not in required_capabilities),
|
||||
"compatibility_web_enabled": bool(request.web_search_enabled and "web" not in required_capabilities),
|
||||
"web_search_query": web_search_query,
|
||||
"web_search_queries": web_search_queries,
|
||||
"show_thinking": request.show_thinking,
|
||||
"target_message_id": target_message_id,
|
||||
"target_message_content": target_message_content,
|
||||
"target_url": target_url,
|
||||
}
|
||||
run = WorkflowRun(
|
||||
workflow_id=workflow.id, workflow_revision_id=revision.id, session_id=request.session_id,
|
||||
user_message_id=user_message.message_id if user_message else None, selection_mode=request.selection_mode,
|
||||
inputs_json=json.dumps({"input": sample_inputs, "run": run_values, "explicit_user_action": request.explicit_user_action}, ensure_ascii=False),
|
||||
)
|
||||
db.add(run)
|
||||
db.commit()
|
||||
db.refresh(run)
|
||||
if request.regenerate_index is not None and request.session_id:
|
||||
safe_sync_chat_memory_for_session(db, request.session_id)
|
||||
run_id = run.id
|
||||
workflow_payload = {"id": workflow.id, "slug": workflow.slug, "name": workflow.name, "revision_id": revision.id}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
writer = EventWriter(run_id, workflow_payload["id"], SessionLocal)
|
||||
if router_result:
|
||||
await writer.emit("router_completed", router_result)
|
||||
await writer.emit("workflow_selected", workflow_payload)
|
||||
runtime.start(run_id)
|
||||
return {"run_id": run_id, "status": "queued", "workflow": workflow_payload, "router": router_result}
|
||||
|
||||
|
||||
@router.get("/workflow-runs/{run_id}")
|
||||
def get_workflow_run(run_id: str):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if not run:
|
||||
raise HTTPException(status_code=404, detail="Workflow run not found.")
|
||||
return _run_payload(run, db)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.get("/workflow-runs/{run_id}/events")
|
||||
def get_workflow_events(run_id: str, after_sequence: int = Query(0, ge=0), follow: bool = True):
|
||||
async def stream():
|
||||
sequence = after_sequence
|
||||
idle_after_terminal = 0
|
||||
emitted_interrupted = False
|
||||
while True:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
events = db.query(WorkflowEvent).filter(
|
||||
WorkflowEvent.workflow_run_id == run_id,
|
||||
WorkflowEvent.sequence > sequence,
|
||||
).order_by(WorkflowEvent.sequence.asc()).all()
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if run is None:
|
||||
yield json.dumps({"type": "error", "payload": {"message": "Workflow run not found."}}) + "\n"
|
||||
return
|
||||
for item in events:
|
||||
sequence = item.sequence
|
||||
yield json.dumps({
|
||||
"run_id": item.workflow_run_id, "workflow_id": item.workflow_id, "node_id": item.node_id,
|
||||
"sequence": item.sequence, "timestamp": item.timestamp.isoformat(), "type": item.event_type,
|
||||
"payload": _json(item.payload_json, {}),
|
||||
}, ensure_ascii=False) + "\n"
|
||||
terminal = run.status in {"completed", "failed", "cancelled", "interrupted"}
|
||||
if run.status == "interrupted" and not emitted_interrupted:
|
||||
emitted_interrupted = True
|
||||
yield json.dumps({
|
||||
"run_id": run.id,
|
||||
"workflow_id": run.workflow_id,
|
||||
"node_id": None,
|
||||
"sequence": sequence + 1,
|
||||
"timestamp": (run.finished_at or datetime.utcnow()).isoformat(),
|
||||
"type": "run_interrupted",
|
||||
"payload": _json(run.error_json, {"message": "Workflow run was interrupted."}),
|
||||
}, ensure_ascii=False) + "\n"
|
||||
finally:
|
||||
db.close()
|
||||
if not follow:
|
||||
return
|
||||
if terminal:
|
||||
idle_after_terminal += 1
|
||||
if idle_after_terminal >= 2:
|
||||
return
|
||||
else:
|
||||
idle_after_terminal = 0
|
||||
await asyncio.sleep(0.15)
|
||||
return StreamingResponse(stream(), media_type="application/x-ndjson")
|
||||
|
||||
|
||||
@router.post("/workflow-runs/{run_id}/cancel")
|
||||
def cancel_workflow_run(run_id: str):
|
||||
if not runtime.cancel(run_id):
|
||||
raise HTTPException(status_code=404, detail="Workflow run not found.")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/workflow-runs/{run_id}/confirmations/{confirmation_id}")
|
||||
def respond_to_confirmation(run_id: str, confirmation_id: str, request: ConfirmationResponseRequest):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
confirmation = db.query(WorkflowConfirmation).filter(
|
||||
WorkflowConfirmation.id == confirmation_id,
|
||||
WorkflowConfirmation.workflow_run_id == run_id,
|
||||
).first()
|
||||
if not confirmation:
|
||||
raise HTTPException(status_code=404, detail="Confirmation request not found.")
|
||||
if confirmation.status != "pending":
|
||||
raise HTTPException(status_code=409, detail="Confirmation has already been resolved.")
|
||||
finally:
|
||||
db.close()
|
||||
if not runtime.resolve_confirmation(confirmation_id, request.approved):
|
||||
raise HTTPException(status_code=409, detail="The workflow is no longer waiting for this confirmation.")
|
||||
return {"ok": True, "approved": request.approved}
|
||||
|
||||
|
||||
@router.post("/workflow-router/select")
|
||||
async def route_workflow(request: RouterSelectRequest):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
ensure_global_knowledge_store()
|
||||
return await select_workflow(
|
||||
db, message=request.message, recent_messages=request.recent_messages[-4:], attachments=request.attachments,
|
||||
library_slug=request.library_slug or global_library_slug(), router_model=request.model, chat_model=request.chat_model,
|
||||
web_search_enabled=request.web_search_enabled,
|
||||
confidence_threshold=request.confidence_threshold,
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
67
backend/agent/bindings.py
Normal file
67
backend/agent/bindings.py
Normal file
@@ -0,0 +1,67 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Dict, Iterable, List, Tuple
|
||||
|
||||
|
||||
REFERENCE_RE = re.compile(r"\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}")
|
||||
|
||||
|
||||
class BindingError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def lookup_reference(reference: str, values: Dict[str, Any]) -> Any:
|
||||
parts = [part for part in str(reference or "").split(".") if part]
|
||||
if not parts or parts[0] not in {"input", "run", "nodes"}:
|
||||
raise BindingError(f"Invalid reference root: {reference}")
|
||||
current: Any = values
|
||||
traversed: List[str] = []
|
||||
for part in parts:
|
||||
traversed.append(part)
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
continue
|
||||
if isinstance(current, list) and part.isdigit() and int(part) < len(current):
|
||||
current = current[int(part)]
|
||||
continue
|
||||
raise BindingError(f"Missing reference: {'.'.join(traversed)}")
|
||||
return current
|
||||
|
||||
|
||||
def resolve_bindings(value: Any, values: Dict[str, Any]) -> Any:
|
||||
if isinstance(value, dict):
|
||||
if set(value) == {"$ref"}:
|
||||
return lookup_reference(str(value["$ref"]), values)
|
||||
return {key: resolve_bindings(item, values) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [resolve_bindings(item, values) for item in value]
|
||||
if not isinstance(value, str) or "{{" not in value:
|
||||
return value
|
||||
matches = list(REFERENCE_RE.finditer(value))
|
||||
if len(matches) == 1 and matches[0].span() == (0, len(value)):
|
||||
return lookup_reference(matches[0].group(1), values)
|
||||
output = value
|
||||
for match in reversed(matches):
|
||||
resolved = lookup_reference(match.group(1), values)
|
||||
replacement = "" if resolved is None else str(resolved)
|
||||
output = output[:match.start()] + replacement + output[match.end():]
|
||||
if "{{" in output or "}}" in output:
|
||||
raise BindingError("Malformed template expression")
|
||||
return output
|
||||
|
||||
|
||||
def iter_references(value: Any, path: str = "") -> Iterable[Tuple[str, str]]:
|
||||
if isinstance(value, dict):
|
||||
if set(value) == {"$ref"}:
|
||||
yield path or "$", str(value["$ref"])
|
||||
return
|
||||
for key, item in value.items():
|
||||
child = f"{path}.{key}" if path else key
|
||||
yield from iter_references(item, child)
|
||||
elif isinstance(value, list):
|
||||
for index, item in enumerate(value):
|
||||
yield from iter_references(item, f"{path}[{index}]")
|
||||
elif isinstance(value, str):
|
||||
for match in REFERENCE_RE.finditer(value):
|
||||
yield path or "$", match.group(1)
|
||||
52
backend/agent/events.py
Normal file
52
backend/agent/events.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from .models import WorkflowEvent
|
||||
|
||||
|
||||
class EventWriter:
|
||||
def __init__(self, run_id: str, workflow_id: str, db_factory) -> None:
|
||||
self.run_id = run_id
|
||||
self.workflow_id = workflow_id
|
||||
self.db_factory = db_factory
|
||||
self._lock = asyncio.Lock()
|
||||
db = db_factory()
|
||||
try:
|
||||
self._sequence = int(db.query(func.max(WorkflowEvent.sequence)).filter(WorkflowEvent.workflow_run_id == run_id).scalar() or 0)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
async def emit(self, event_type: str, payload: Dict[str, Any], node_id: Optional[str] = None) -> Dict[str, Any]:
|
||||
async with self._lock:
|
||||
self._sequence += 1
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
event = {
|
||||
"run_id": self.run_id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"node_id": node_id,
|
||||
"sequence": self._sequence,
|
||||
"timestamp": timestamp.isoformat(),
|
||||
"type": event_type,
|
||||
"payload": payload,
|
||||
}
|
||||
db = self.db_factory()
|
||||
try:
|
||||
db.add(WorkflowEvent(
|
||||
workflow_run_id=self.run_id,
|
||||
workflow_id=self.workflow_id,
|
||||
node_id=node_id,
|
||||
sequence=self._sequence,
|
||||
event_type=event_type,
|
||||
timestamp=timestamp.replace(tzinfo=None),
|
||||
payload_json=json.dumps(payload, ensure_ascii=False, default=str),
|
||||
))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
return event
|
||||
116
backend/agent/models.py
Normal file
116
backend/agent/models.py
Normal file
@@ -0,0 +1,116 @@
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from ..database import Base
|
||||
|
||||
|
||||
def _uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
class WorkflowDefinition(Base):
|
||||
__tablename__ = "workflow_definitions"
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
slug = Column(String(100), unique=True, nullable=False, index=True)
|
||||
name = Column(String(160), nullable=False)
|
||||
description = Column(Text, nullable=False, default="")
|
||||
current_revision_id = Column(String(36), nullable=True)
|
||||
built_in = Column(Boolean, nullable=False, default=False)
|
||||
enabled = Column(Boolean, nullable=False, default=True)
|
||||
routing_description = Column(Text, nullable=False, default="")
|
||||
routing_examples_json = Column(Text, nullable=False, default="[]")
|
||||
estimated_cost_class = Column(String(32), nullable=False, default="low")
|
||||
required_capabilities_json = Column(Text, nullable=False, default="[]")
|
||||
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
revisions = relationship(
|
||||
"WorkflowRevision",
|
||||
back_populates="workflow",
|
||||
foreign_keys="WorkflowRevision.workflow_id",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class WorkflowRevision(Base):
|
||||
__tablename__ = "workflow_revisions"
|
||||
__table_args__ = (UniqueConstraint("workflow_id", "version", name="uq_workflow_revision_version"),)
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
workflow_id = Column(String(36), ForeignKey("workflow_definitions.id"), nullable=False, index=True)
|
||||
version = Column(Integer, nullable=False)
|
||||
graph_json = Column(Text, nullable=False)
|
||||
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
created_by = Column(String(64), nullable=False, default="user")
|
||||
trusted = Column(Boolean, nullable=False, default=False)
|
||||
checksum = Column(String(64), nullable=False, index=True)
|
||||
|
||||
workflow = relationship("WorkflowDefinition", back_populates="revisions", foreign_keys=[workflow_id])
|
||||
|
||||
|
||||
class WorkflowRun(Base):
|
||||
__tablename__ = "workflow_runs"
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
workflow_id = Column(String(36), ForeignKey("workflow_definitions.id"), nullable=False, index=True)
|
||||
workflow_revision_id = Column(String(36), ForeignKey("workflow_revisions.id"), nullable=False)
|
||||
session_id = Column(String(64), nullable=True, index=True)
|
||||
user_message_id = Column(String(36), nullable=True)
|
||||
status = Column(String(32), nullable=False, default="queued", index=True)
|
||||
selection_mode = Column(String(24), nullable=False, default="direct")
|
||||
inputs_json = Column(Text, nullable=False, default="{}")
|
||||
outputs_json = Column(Text, nullable=True)
|
||||
error_json = Column(Text, nullable=True)
|
||||
metrics_json = Column(Text, nullable=False, default="{}")
|
||||
started_at = Column(DateTime, nullable=True)
|
||||
finished_at = Column(DateTime, nullable=True)
|
||||
cancellation_requested = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class WorkflowNodeRun(Base):
|
||||
__tablename__ = "workflow_node_runs"
|
||||
__table_args__ = (UniqueConstraint("workflow_run_id", "node_id", "attempt", name="uq_node_run_attempt"),)
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
workflow_run_id = Column(String(36), ForeignKey("workflow_runs.id"), nullable=False, index=True)
|
||||
node_id = Column(String(120), nullable=False)
|
||||
attempt = Column(Integer, nullable=False, default=1)
|
||||
status = Column(String(32), nullable=False, default="queued")
|
||||
resolved_inputs_json = Column(Text, nullable=True)
|
||||
outputs_json = Column(Text, nullable=True)
|
||||
error_json = Column(Text, nullable=True)
|
||||
started_at = Column(DateTime, nullable=True)
|
||||
finished_at = Column(DateTime, nullable=True)
|
||||
metrics_json = Column(Text, nullable=False, default="{}")
|
||||
|
||||
|
||||
class WorkflowEvent(Base):
|
||||
__tablename__ = "workflow_events"
|
||||
__table_args__ = (UniqueConstraint("workflow_run_id", "sequence", name="uq_workflow_event_sequence"),)
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
workflow_run_id = Column(String(36), ForeignKey("workflow_runs.id"), nullable=False, index=True)
|
||||
workflow_id = Column(String(36), nullable=False)
|
||||
node_id = Column(String(120), nullable=True)
|
||||
sequence = Column(Integer, nullable=False)
|
||||
event_type = Column(String(64), nullable=False)
|
||||
timestamp = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
payload_json = Column(Text, nullable=False, default="{}")
|
||||
|
||||
|
||||
class WorkflowConfirmation(Base):
|
||||
__tablename__ = "workflow_confirmations"
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
workflow_run_id = Column(String(36), ForeignKey("workflow_runs.id"), nullable=False, index=True)
|
||||
node_id = Column(String(120), nullable=False)
|
||||
tool_name = Column(String(160), nullable=False)
|
||||
status = Column(String(24), nullable=False, default="pending")
|
||||
request_json = Column(Text, nullable=False, default="{}")
|
||||
response_json = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
resolved_at = Column(DateTime, nullable=True)
|
||||
101
backend/agent/ollama_runtime.py
Normal file
101
backend/agent/ollama_runtime.py
Normal file
@@ -0,0 +1,101 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from ..ollama_client import chat_typed
|
||||
from .registry import NativeToolProvider, ToolExecutionContext
|
||||
|
||||
|
||||
def _usage_dict(usage: Any) -> Dict[str, int]:
|
||||
return {
|
||||
"prompt_eval_count": usage.prompt_eval_count,
|
||||
"eval_count": usage.eval_count,
|
||||
"total_duration": usage.total_duration,
|
||||
"load_duration": usage.load_duration,
|
||||
"prompt_eval_duration": usage.prompt_eval_duration,
|
||||
"eval_duration": usage.eval_duration,
|
||||
}
|
||||
|
||||
|
||||
async def run_agent_loop(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
registry = context.registry
|
||||
if registry is None:
|
||||
raise RuntimeError("Agent tool registry is unavailable.")
|
||||
|
||||
allowed_names = []
|
||||
for name in arguments.get("allowed_tool_names") or []:
|
||||
if name == "heimgeist.agent":
|
||||
continue
|
||||
registry.get_tool(name)
|
||||
allowed_names.append(name)
|
||||
tools = [registry.get_tool(name).ollama_manifest() for name in allowed_names]
|
||||
messages: List[Dict[str, Any]] = [dict(item) for item in arguments.get("messages") or []]
|
||||
maximum_rounds = max(1, min(int(arguments.get("maximum_rounds") or 4), 8))
|
||||
maximum_output_chars = max(1000, min(int(arguments.get("maximum_output_chars") or 60_000), 120_000))
|
||||
tool_summary: List[Dict[str, Any]] = []
|
||||
usage_totals: Dict[str, int] = {}
|
||||
|
||||
for round_index in range(maximum_rounds):
|
||||
if context.cancellation_event.is_set():
|
||||
raise RuntimeError("Agent execution was cancelled.")
|
||||
if context.consume_llm_call:
|
||||
context.consume_llm_call()
|
||||
result = await chat_typed(
|
||||
arguments["model"],
|
||||
messages,
|
||||
options=arguments.get("generation_options") or {},
|
||||
tools=tools or None,
|
||||
think=bool(arguments.get("reasoning")),
|
||||
cancellation_event=context.cancellation_event,
|
||||
)
|
||||
for key, value in _usage_dict(result.usage).items():
|
||||
usage_totals[key] = usage_totals.get(key, 0) + int(value or 0)
|
||||
if result.thinking and context.show_thinking:
|
||||
await context.emit("model_thinking", {"text": result.thinking, "round": round_index + 1})
|
||||
|
||||
if not result.tool_calls:
|
||||
content = result.content[:maximum_output_chars]
|
||||
return {
|
||||
"content": content,
|
||||
"tool_summary": tool_summary,
|
||||
"usage": usage_totals,
|
||||
"rounds": round_index + 1,
|
||||
}
|
||||
|
||||
assistant_message: Dict[str, Any] = {
|
||||
"role": "assistant",
|
||||
"content": result.content or "",
|
||||
"tool_calls": [call.raw for call in result.tool_calls],
|
||||
}
|
||||
messages.append(assistant_message)
|
||||
for call in result.tool_calls:
|
||||
if call.name not in allowed_names:
|
||||
tool_result = {"error": f"Tool is not allowed: {call.name}"}
|
||||
else:
|
||||
definition = registry.get_tool(call.name)
|
||||
approved = True
|
||||
if definition.requires_confirmation and context.request_confirmation:
|
||||
approved = await context.request_confirmation(definition, call.arguments)
|
||||
if approved:
|
||||
await context.emit("tool_started", {"tool": call.name, "arguments": call.arguments, "agent_round": round_index + 1})
|
||||
try:
|
||||
tool_result = await registry.call_tool(call.name, call.arguments, context)
|
||||
except Exception as exc:
|
||||
tool_result = {"error": f"{type(exc).__name__}: {exc}"}
|
||||
await context.emit("tool_result", {"tool": call.name, "result": tool_result, "agent_round": round_index + 1})
|
||||
else:
|
||||
tool_result = {"status": "rejected", "confirmed": False}
|
||||
tool_summary.append({"tool": call.name, "arguments": call.arguments, "result": tool_result})
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_name": call.name,
|
||||
"content": json.dumps(tool_result, ensure_ascii=False, default=str),
|
||||
})
|
||||
|
||||
return {
|
||||
"content": "I could not complete the task within the configured agent round limit.",
|
||||
"tool_summary": tool_summary,
|
||||
"usage": usage_totals,
|
||||
"rounds": maximum_rounds,
|
||||
}
|
||||
241
backend/agent/registry.py
Normal file
241
backend/agent/registry.py
Normal file
@@ -0,0 +1,241 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
from typing import Any, Awaitable, Callable, Dict, Iterable, Optional, Protocol
|
||||
|
||||
|
||||
class SchemaValidationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _type_matches(value: Any, expected: str) -> bool:
|
||||
if expected == "null":
|
||||
return value is None
|
||||
if expected == "object":
|
||||
return isinstance(value, dict)
|
||||
if expected == "array":
|
||||
return isinstance(value, list)
|
||||
if expected == "string":
|
||||
return isinstance(value, str)
|
||||
if expected == "boolean":
|
||||
return isinstance(value, bool)
|
||||
if expected == "integer":
|
||||
return isinstance(value, int) and not isinstance(value, bool)
|
||||
if expected == "number":
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||
return True
|
||||
|
||||
|
||||
def validate_json_schema(value: Any, schema: Dict[str, Any], path: str = "$", *, partial: bool = False) -> None:
|
||||
if not isinstance(schema, dict):
|
||||
raise SchemaValidationError(f"{path}: schema must be an object")
|
||||
if "const" in schema and value != schema["const"]:
|
||||
raise SchemaValidationError(f"{path}: must equal {schema['const']!r}")
|
||||
if "enum" in schema and value not in schema["enum"]:
|
||||
raise SchemaValidationError(f"{path}: must be one of {schema['enum']!r}")
|
||||
for union_key in ("oneOf", "anyOf"):
|
||||
if union_key in schema:
|
||||
matches = 0
|
||||
errors = []
|
||||
for candidate in schema[union_key]:
|
||||
try:
|
||||
validate_json_schema(value, candidate, path, partial=partial)
|
||||
matches += 1
|
||||
except SchemaValidationError as exc:
|
||||
errors.append(str(exc))
|
||||
if (union_key == "oneOf" and matches != 1) or (union_key == "anyOf" and matches == 0):
|
||||
raise SchemaValidationError(f"{path}: does not match {union_key}: {'; '.join(errors[:3])}")
|
||||
return
|
||||
|
||||
expected = schema.get("type")
|
||||
if isinstance(expected, list):
|
||||
if not any(_type_matches(value, item) for item in expected):
|
||||
raise SchemaValidationError(f"{path}: expected one of {expected}, got {type(value).__name__}")
|
||||
elif expected and not _type_matches(value, expected):
|
||||
raise SchemaValidationError(f"{path}: expected {expected}, got {type(value).__name__}")
|
||||
|
||||
if isinstance(value, dict):
|
||||
properties = schema.get("properties") or {}
|
||||
if not partial:
|
||||
for required in schema.get("required") or []:
|
||||
if required not in value:
|
||||
raise SchemaValidationError(f"{path}.{required}: required value is missing")
|
||||
if schema.get("additionalProperties") is False:
|
||||
unknown = [key for key in value if key not in properties]
|
||||
if unknown:
|
||||
raise SchemaValidationError(f"{path}: unknown properties: {', '.join(unknown)}")
|
||||
for key, item in value.items():
|
||||
if key in properties:
|
||||
validate_json_schema(item, properties[key], f"{path}.{key}", partial=partial)
|
||||
minimum = schema.get("minProperties")
|
||||
if minimum is not None and len(value) < minimum:
|
||||
raise SchemaValidationError(f"{path}: expected at least {minimum} properties")
|
||||
elif isinstance(value, list):
|
||||
if "minItems" in schema and len(value) < int(schema["minItems"]):
|
||||
raise SchemaValidationError(f"{path}: expected at least {schema['minItems']} items")
|
||||
if "maxItems" in schema and len(value) > int(schema["maxItems"]):
|
||||
raise SchemaValidationError(f"{path}: expected at most {schema['maxItems']} items")
|
||||
item_schema = schema.get("items")
|
||||
if item_schema:
|
||||
for index, item in enumerate(value):
|
||||
validate_json_schema(item, item_schema, f"{path}[{index}]", partial=partial)
|
||||
elif isinstance(value, str):
|
||||
if "minLength" in schema and len(value) < int(schema["minLength"]):
|
||||
raise SchemaValidationError(f"{path}: string is too short")
|
||||
if "maxLength" in schema and len(value) > int(schema["maxLength"]):
|
||||
raise SchemaValidationError(f"{path}: string is too long")
|
||||
elif isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
if "minimum" in schema and value < schema["minimum"]:
|
||||
raise SchemaValidationError(f"{path}: must be at least {schema['minimum']}")
|
||||
if "maximum" in schema and value > schema["maximum"]:
|
||||
raise SchemaValidationError(f"{path}: must be at most {schema['maximum']}")
|
||||
|
||||
|
||||
def validate_schema_definition(schema: Dict[str, Any], path: str = "$schema") -> None:
|
||||
if not isinstance(schema, dict):
|
||||
raise SchemaValidationError(f"{path}: schema must be an object")
|
||||
expected = schema.get("type")
|
||||
allowed = {"object", "array", "string", "boolean", "integer", "number", "null"}
|
||||
if isinstance(expected, str) and expected not in allowed:
|
||||
raise SchemaValidationError(f"{path}.type: unsupported type {expected!r}")
|
||||
if isinstance(expected, list) and any(item not in allowed for item in expected):
|
||||
raise SchemaValidationError(f"{path}.type: contains an unsupported type")
|
||||
if expected == "object":
|
||||
properties = schema.get("properties", {})
|
||||
if not isinstance(properties, dict):
|
||||
raise SchemaValidationError(f"{path}.properties: must be an object")
|
||||
for key, child in properties.items():
|
||||
validate_schema_definition(child, f"{path}.properties.{key}")
|
||||
required = schema.get("required", [])
|
||||
if not isinstance(required, list) or any(not isinstance(item, str) for item in required):
|
||||
raise SchemaValidationError(f"{path}.required: must be a string array")
|
||||
missing = [item for item in required if item not in properties]
|
||||
if missing:
|
||||
raise SchemaValidationError(f"{path}.required: unknown properties: {', '.join(missing)}")
|
||||
if expected == "array" and "items" in schema:
|
||||
validate_schema_definition(schema["items"], f"{path}.items")
|
||||
for key in ("oneOf", "anyOf"):
|
||||
if key in schema:
|
||||
if not isinstance(schema[key], list) or not schema[key]:
|
||||
raise SchemaValidationError(f"{path}.{key}: must be a non-empty array")
|
||||
for index, child in enumerate(schema[key]):
|
||||
validate_schema_definition(child, f"{path}.{key}[{index}]")
|
||||
|
||||
|
||||
ToolHandler = Callable[[Dict[str, Any], "ToolExecutionContext"], Awaitable[Dict[str, Any]]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ToolDefinition:
|
||||
name: str
|
||||
description: str
|
||||
input_schema: Dict[str, Any]
|
||||
output_schema: Dict[str, Any]
|
||||
handler: ToolHandler
|
||||
risk_level: str = "low"
|
||||
timeout_seconds: float = 120.0
|
||||
result_size_limit: int = 120_000
|
||||
requires_confirmation: bool = False
|
||||
llm_call: bool = False
|
||||
|
||||
def manifest(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"inputSchema": self.input_schema,
|
||||
"outputSchema": self.output_schema,
|
||||
"riskLevel": self.risk_level,
|
||||
"timeoutSeconds": self.timeout_seconds,
|
||||
"resultSizeLimit": self.result_size_limit,
|
||||
"requiresConfirmation": self.requires_confirmation,
|
||||
}
|
||||
|
||||
def ollama_manifest(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"parameters": self.input_schema,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ToolExecutionContext:
|
||||
run_id: str
|
||||
workflow_id: str
|
||||
node_id: str
|
||||
session_id: Optional[str]
|
||||
selection_mode: str
|
||||
explicit_user_action: bool
|
||||
emit: Callable[[str, Dict[str, Any]], Awaitable[None]]
|
||||
cancellation_event: asyncio.Event
|
||||
db_factory: Callable[[], Any]
|
||||
registry: Optional["NativeToolProvider"] = None
|
||||
run_values: Dict[str, Any] = field(default_factory=dict)
|
||||
request_confirmation: Optional[Callable[[ToolDefinition, Dict[str, Any]], Awaitable[bool]]] = None
|
||||
consume_llm_call: Optional[Callable[[], None]] = None
|
||||
show_thinking: bool = False
|
||||
|
||||
|
||||
class ToolProvider(Protocol):
|
||||
def list_tools(self) -> Iterable[Dict[str, Any]]: ...
|
||||
def get_tool(self, name: str) -> ToolDefinition: ...
|
||||
async def call_tool(self, name: str, arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]: ...
|
||||
|
||||
|
||||
class NativeToolProvider:
|
||||
def __init__(self) -> None:
|
||||
self._tools: Dict[str, ToolDefinition] = {}
|
||||
|
||||
def register(self, definition: ToolDefinition) -> None:
|
||||
if definition.name in self._tools:
|
||||
raise ValueError(f"Duplicate tool name: {definition.name}")
|
||||
validate_schema_definition(definition.input_schema, f"{definition.name}.inputSchema")
|
||||
validate_schema_definition(definition.output_schema, f"{definition.name}.outputSchema")
|
||||
self._tools[definition.name] = definition
|
||||
|
||||
def list_tools(self) -> Iterable[Dict[str, Any]]:
|
||||
return [tool.manifest() for tool in sorted(self._tools.values(), key=lambda item: item.name)]
|
||||
|
||||
def get_tool(self, name: str) -> ToolDefinition:
|
||||
try:
|
||||
return self._tools[name]
|
||||
except KeyError as exc:
|
||||
raise KeyError(f"Unknown tool: {name}") from exc
|
||||
|
||||
async def call_tool(self, name: str, arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
definition = self.get_tool(name)
|
||||
validate_json_schema(arguments, definition.input_schema)
|
||||
if context.cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
if definition.llm_call and context.consume_llm_call:
|
||||
context.consume_llm_call()
|
||||
handler_task = asyncio.create_task(definition.handler(arguments, context))
|
||||
cancellation_task = asyncio.create_task(context.cancellation_event.wait())
|
||||
try:
|
||||
done, _pending = await asyncio.wait(
|
||||
{handler_task, cancellation_task},
|
||||
timeout=definition.timeout_seconds,
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
if cancellation_task in done and cancellation_task.result():
|
||||
handler_task.cancel()
|
||||
await asyncio.gather(handler_task, return_exceptions=True)
|
||||
raise asyncio.CancelledError()
|
||||
if handler_task not in done:
|
||||
handler_task.cancel()
|
||||
await asyncio.gather(handler_task, return_exceptions=True)
|
||||
raise TimeoutError(f"Tool {name} exceeded {definition.timeout_seconds:g}s")
|
||||
result = handler_task.result()
|
||||
finally:
|
||||
cancellation_task.cancel()
|
||||
await asyncio.gather(cancellation_task, return_exceptions=True)
|
||||
validate_json_schema(result, definition.output_schema)
|
||||
size = len(json.dumps(result, ensure_ascii=False, default=str))
|
||||
if size > definition.result_size_limit:
|
||||
raise ValueError(f"Tool {name} result exceeded {definition.result_size_limit} characters")
|
||||
return result
|
||||
477
backend/agent/router.py
Normal file
477
backend/agent/router.py
Normal file
@@ -0,0 +1,477 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_settings import get_workflow_router_model_preference
|
||||
from ..ollama_client import chat_typed, list_model_catalog
|
||||
from .models import WorkflowDefinition
|
||||
|
||||
|
||||
ROUTER_FORMAT = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"workflow_id": {"type": "string"},
|
||||
"confidence": {"type": "number"},
|
||||
"reason": {"type": "string"},
|
||||
"inputs": {"type": "object"},
|
||||
},
|
||||
"required": ["workflow_id", "confidence", "reason", "inputs"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
MESSAGE_DIGEST_THRESHOLD = 2600
|
||||
MESSAGE_DIGEST_HEAD_CHARS = 900
|
||||
MESSAGE_DIGEST_MIDDLE_CHARS = 500
|
||||
MESSAGE_DIGEST_TAIL_CHARS = 900
|
||||
MESSAGE_DIGEST_MAX_SAMPLE_LINES = 6
|
||||
MESSAGE_DIGEST_SAMPLE_LINE_CHARS = 180
|
||||
ATTACHMENT_SUMMARY_LIMIT = 8
|
||||
|
||||
|
||||
def workflow_manifests(db: Session) -> List[Dict[str, Any]]:
|
||||
workflows = db.query(WorkflowDefinition).filter(WorkflowDefinition.enabled.is_(True)).order_by(WorkflowDefinition.name.asc()).all()
|
||||
manifests = []
|
||||
for item in workflows:
|
||||
manifests.append({
|
||||
"workflow_id": item.id,
|
||||
"slug": item.slug,
|
||||
"name": item.name,
|
||||
"routing_description": item.routing_description,
|
||||
"examples": json.loads(item.routing_examples_json or "[]"),
|
||||
"estimated_cost_class": item.estimated_cost_class,
|
||||
"required_capabilities": json.loads(item.required_capabilities_json or "[]"),
|
||||
})
|
||||
return manifests
|
||||
|
||||
|
||||
def _fallback_result(fallback: WorkflowDefinition, reason: str = "Router fallback to direct chat.") -> Dict[str, Any]:
|
||||
return {
|
||||
"workflow_id": fallback.id,
|
||||
"workflow_slug": fallback.slug,
|
||||
"confidence": 0.0,
|
||||
"reason": reason,
|
||||
"inputs": {},
|
||||
"fallback": True,
|
||||
}
|
||||
|
||||
|
||||
def _manifest_by_slug(manifests: List[Dict[str, Any]], slug: str) -> Optional[Dict[str, Any]]:
|
||||
return next((item for item in manifests if item["slug"] == slug), None)
|
||||
|
||||
|
||||
def _workflow_result(item: Dict[str, Any], *, confidence: float, reason: str, inputs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
return {
|
||||
"workflow_id": item["workflow_id"],
|
||||
"workflow_slug": item["slug"],
|
||||
"confidence": max(0.0, min(float(confidence), 1.0)),
|
||||
"reason": reason,
|
||||
"inputs": inputs or {},
|
||||
"fallback": False,
|
||||
}
|
||||
|
||||
|
||||
def _capability_enabled(capability: str, *, library_slug: Optional[str], web_search_enabled: bool, has_attachments: bool) -> bool:
|
||||
if capability in {"chat", "chat_memory"}:
|
||||
return True
|
||||
if capability == "web":
|
||||
return True
|
||||
if capability in {"rag", "knowledge_write"}:
|
||||
return bool(library_slug)
|
||||
if capability == "vision":
|
||||
return has_attachments
|
||||
return False
|
||||
|
||||
|
||||
def _allowed_manifests(
|
||||
manifests: List[Dict[str, Any]],
|
||||
*,
|
||||
library_slug: Optional[str],
|
||||
web_search_enabled: bool,
|
||||
has_attachments: bool,
|
||||
) -> List[Dict[str, Any]]:
|
||||
allowed = []
|
||||
for item in manifests:
|
||||
capabilities = item.get("required_capabilities") or []
|
||||
if all(_capability_enabled(str(capability), library_slug=library_slug, web_search_enabled=web_search_enabled, has_attachments=has_attachments) for capability in capabilities):
|
||||
allowed.append(item)
|
||||
return allowed
|
||||
|
||||
|
||||
def _filter_for_interface_settings(
|
||||
manifests: List[Dict[str, Any]],
|
||||
*,
|
||||
web_search_enabled: bool,
|
||||
) -> List[Dict[str, Any]]:
|
||||
if not web_search_enabled:
|
||||
return manifests
|
||||
web_capable = [item for item in manifests if "web" in (item.get("required_capabilities") or [])]
|
||||
return web_capable or manifests
|
||||
|
||||
|
||||
_REMEMBER_RE = re.compile(
|
||||
r"\b(remember\s+(this|that)|save\s+(this|that)|merk\s+dir\s+(das|:)?|speicher(e)?\s+(das|dies|diese|diesen)?)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_KNOWLEDGE_RE = re.compile(
|
||||
r"\b(my\s+(notes|documents|files|database|knowledge)|meine[nr]?\s+(notizen|dokumente|dateien|datenbank|daten)|rag|knowledge\s+base|datenbank)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_GREETING_RE = re.compile(r"^\s*(hi|hello|hey|hallo|moin|servus|danke|thanks|thank\s+you)[!.?\s]*$", re.IGNORECASE)
|
||||
|
||||
|
||||
def _fast_path(
|
||||
manifests: List[Dict[str, Any]],
|
||||
*,
|
||||
message: str,
|
||||
library_slug: Optional[str],
|
||||
web_search_enabled: bool,
|
||||
has_attachments: bool,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
text = str(message or "").strip()
|
||||
if not text and not has_attachments:
|
||||
return None
|
||||
|
||||
if has_attachments:
|
||||
vision = _manifest_by_slug(manifests, "vision-answer")
|
||||
if vision:
|
||||
return _workflow_result(vision, confidence=1.0, reason="The request includes attachments.")
|
||||
|
||||
mentions_knowledge = bool(_KNOWLEDGE_RE.search(text))
|
||||
|
||||
if _REMEMBER_RE.search(text):
|
||||
remember = _manifest_by_slug(manifests, "remember-this")
|
||||
if remember:
|
||||
return _workflow_result(remember, confidence=1.0, reason="The user explicitly asked Heimgeist to remember or save this.")
|
||||
|
||||
if web_search_enabled:
|
||||
return None
|
||||
|
||||
if library_slug and mentions_knowledge:
|
||||
knowledge = _manifest_by_slug(manifests, "knowledge-answer")
|
||||
if knowledge:
|
||||
return _workflow_result(knowledge, confidence=0.95, reason="The request explicitly refers to local knowledge.")
|
||||
|
||||
if _GREETING_RE.match(text):
|
||||
direct = _manifest_by_slug(manifests, "input-output")
|
||||
if direct:
|
||||
return _workflow_result(direct, confidence=1.0, reason="Simple conversational prompt.")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _clean_router_queries(raw: Any, fallback: str) -> List[str]:
|
||||
values = raw if isinstance(raw, list) else [raw]
|
||||
cleaned: List[str] = []
|
||||
seen = set()
|
||||
for item in values:
|
||||
text = " ".join(str(item or "").split()).strip()
|
||||
if not text:
|
||||
continue
|
||||
key = text.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
cleaned.append(text[:300])
|
||||
if len(cleaned) >= 5:
|
||||
break
|
||||
fallback_text = " ".join(str(fallback or "").split()).strip()
|
||||
if fallback_text and not cleaned:
|
||||
cleaned.append(fallback_text[:300])
|
||||
return cleaned
|
||||
|
||||
|
||||
def _normalize_router_inputs(selected: Dict[str, Any], inputs: Any, message: str) -> Dict[str, Any]:
|
||||
normalized = dict(inputs) if isinstance(inputs, dict) else {}
|
||||
if "web" not in (selected.get("required_capabilities") or []):
|
||||
return normalized
|
||||
raw_queries = normalized.get("web_search_queries")
|
||||
if raw_queries is None:
|
||||
raw_queries = normalized.get("search_queries")
|
||||
raw_query = normalized.get("web_search_query") or normalized.get("search_query")
|
||||
queries = _clean_router_queries(raw_queries if raw_queries is not None else raw_query, message)
|
||||
if raw_query:
|
||||
raw_query_text = " ".join(str(raw_query).split()).strip()
|
||||
if raw_query_text and raw_query_text.casefold() not in {item.casefold() for item in queries}:
|
||||
queries.insert(0, raw_query_text[:300])
|
||||
queries = queries[:5]
|
||||
normalized["web_search_query"] = queries[0] if queries else str(message or "")[:300]
|
||||
normalized["web_search_queries"] = queries or [normalized["web_search_query"]]
|
||||
return normalized
|
||||
|
||||
|
||||
def _forced_web_manifest(manifests: List[Dict[str, Any]], *, library_slug: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
if library_slug:
|
||||
combined = _manifest_by_slug(manifests, "knowledge-web-answer")
|
||||
if combined:
|
||||
return combined
|
||||
return _manifest_by_slug(manifests, "web-answer")
|
||||
|
||||
|
||||
def _format_recent_messages(recent_messages: List[Dict[str, Any]], *, char_limit: int) -> str:
|
||||
rows: List[str] = []
|
||||
for index, item in enumerate(recent_messages[-4:], 1):
|
||||
role = str(item.get("role") or "message").strip().title()
|
||||
content = " ".join(str(item.get("content") or "").split())
|
||||
if len(content) > char_limit:
|
||||
content = content[:char_limit].rstrip() + "..."
|
||||
rows.append(f"{index}. {role}: {content}")
|
||||
return "\n".join(rows) if rows else "(none)"
|
||||
|
||||
|
||||
def _normalize_message_text(message: str) -> str:
|
||||
return str(message or "").replace("\r\n", "\n").replace("\r", "\n").replace("\x00", "")
|
||||
|
||||
|
||||
def _short_line(line: str, limit: int = MESSAGE_DIGEST_SAMPLE_LINE_CHARS) -> str:
|
||||
text = " ".join(str(line or "").split()).strip()
|
||||
if len(text) > limit:
|
||||
text = text[:limit].rstrip() + "..."
|
||||
return text
|
||||
|
||||
|
||||
def _sample_representative_lines(text: str, *, max_lines: int = MESSAGE_DIGEST_MAX_SAMPLE_LINES) -> List[str]:
|
||||
candidates = []
|
||||
seen = set()
|
||||
for line_number, line in enumerate(text.splitlines(), 1):
|
||||
compact = _short_line(line)
|
||||
if not compact:
|
||||
continue
|
||||
if compact in seen:
|
||||
continue
|
||||
seen.add(compact)
|
||||
candidates.append((line_number, compact))
|
||||
if len(candidates) <= max_lines:
|
||||
return [f"L{line_number}: {compact}" for line_number, compact in candidates]
|
||||
if max_lines <= 1:
|
||||
line_number, compact = candidates[0]
|
||||
return [f"L{line_number}: {compact}"]
|
||||
selected = []
|
||||
last_index = len(candidates) - 1
|
||||
for index in range(max_lines):
|
||||
selected_index = round(index * last_index / (max_lines - 1))
|
||||
line_number, compact = candidates[selected_index]
|
||||
selected.append(f"L{line_number}: {compact}")
|
||||
return selected
|
||||
|
||||
|
||||
def _count_substrings(text: str, values: List[str]) -> int:
|
||||
lowered = text.casefold()
|
||||
return sum(lowered.count(value.casefold()) for value in values)
|
||||
|
||||
|
||||
def _format_message_for_router(message: str) -> str:
|
||||
text = _normalize_message_text(message)
|
||||
if len(text) <= MESSAGE_DIGEST_THRESHOLD:
|
||||
return text
|
||||
|
||||
lines = text.splitlines()
|
||||
middle_start = max(0, (len(text) - MESSAGE_DIGEST_MIDDLE_CHARS) // 2)
|
||||
middle_end = min(len(text), middle_start + MESSAGE_DIGEST_MIDDLE_CHARS)
|
||||
samples = _sample_representative_lines(text)
|
||||
sections = [
|
||||
"<long_user_message_digest>",
|
||||
f"Original length: {len(text)} characters, {len(lines)} lines.",
|
||||
f"Detected structure: {_count_substrings(text, ['http://', 'https://'])} URL marker(s), {text.count('```')} code-fence marker(s).",
|
||||
"This is a routing digest, not the full message. Use the visible beginning/end and structural summary to route; do not infer omitted content.",
|
||||
"",
|
||||
"<beginning_excerpt>",
|
||||
text[:MESSAGE_DIGEST_HEAD_CHARS].rstrip(),
|
||||
"</beginning_excerpt>",
|
||||
"",
|
||||
"<middle_excerpt>",
|
||||
text[middle_start:middle_end].strip(),
|
||||
"</middle_excerpt>",
|
||||
"",
|
||||
"<ending_excerpt>",
|
||||
text[-MESSAGE_DIGEST_TAIL_CHARS:].lstrip(),
|
||||
"</ending_excerpt>",
|
||||
]
|
||||
if samples:
|
||||
sections.extend([
|
||||
"",
|
||||
"<representative_short_lines>",
|
||||
*samples,
|
||||
"</representative_short_lines>",
|
||||
])
|
||||
sections.append("</long_user_message_digest>")
|
||||
return "\n".join(sections)
|
||||
|
||||
|
||||
def _format_attachment_summary(attachments: List[Dict[str, Any]]) -> str:
|
||||
if not attachments:
|
||||
return "No attachments."
|
||||
rows = [f"{len(attachments)} attachment(s) are present."]
|
||||
for index, attachment in enumerate(attachments[:ATTACHMENT_SUMMARY_LIMIT], 1):
|
||||
if not isinstance(attachment, dict):
|
||||
rows.append(f"{index}. Attachment")
|
||||
continue
|
||||
kind = str(attachment.get("kind") or ("image" if attachment.get("data_url") else "file") or "attachment")
|
||||
name = str(attachment.get("name") or attachment.get("source_path") or f"attachment-{index}")
|
||||
mime_type = str(attachment.get("mime_type") or "").strip()
|
||||
size = attachment.get("size")
|
||||
text_length = len(str(attachment.get("text") or ""))
|
||||
parts = [f"{index}. {kind}: {name}"]
|
||||
if mime_type:
|
||||
parts.append(f"mime={mime_type}")
|
||||
if size is not None:
|
||||
parts.append(f"size={size}")
|
||||
if text_length:
|
||||
parts.append(f"text_chars={text_length}")
|
||||
rows.append("; ".join(parts))
|
||||
if len(attachments) > ATTACHMENT_SUMMARY_LIMIT:
|
||||
rows.append(f"... {len(attachments) - ATTACHMENT_SUMMARY_LIMIT} more attachment(s) omitted from routing summary.")
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
def _format_workflow_choices(manifests: List[Dict[str, Any]]) -> str:
|
||||
rows: List[str] = []
|
||||
for item in manifests:
|
||||
examples = "; ".join(str(value) for value in (item.get("examples") or [])[:2])
|
||||
capabilities = ", ".join(str(value) for value in (item.get("required_capabilities") or []))
|
||||
suffix = f" Examples: {examples}." if examples else ""
|
||||
rows.append(
|
||||
f"- {item['name']} ({item['slug']}, id: {item['workflow_id']}): "
|
||||
f"Capabilities: {capabilities or 'none'}. "
|
||||
f"Routing contract: {item.get('routing_description') or 'No description.'}{suffix}"
|
||||
)
|
||||
return "\n".join(rows)
|
||||
|
||||
|
||||
def _router_prompt(
|
||||
*,
|
||||
message: str,
|
||||
recent_messages: List[Dict[str, Any]],
|
||||
attachments: List[Dict[str, Any]],
|
||||
manifests: List[Dict[str, Any]],
|
||||
) -> str:
|
||||
message_excerpt = _format_message_for_router(message)
|
||||
history_chars = 250 if len(message_excerpt) > MESSAGE_DIGEST_THRESHOLD else 500
|
||||
attachment_line = _format_attachment_summary(attachments)
|
||||
return (
|
||||
"You are Heimgeist's workflow router. Choose exactly one allowed workflow for the current user message.\n\n"
|
||||
"Decision method:\n"
|
||||
"1. Resolve the current message into a standalone request using recent conversation. Do this before choosing a workflow.\n"
|
||||
"2. Identify which capabilities are required to answer faithfully: ordinary chat, local knowledge retrieval, web evidence, attachment analysis, or saving knowledge.\n"
|
||||
"3. Choose the lowest-complexity allowed workflow whose capabilities cover the required work. If two workflows can answer faithfully, choose the simpler one. Do not choose a workflow because an example sounds similar; use the routing contract and capabilities.\n"
|
||||
"4. Choose a direct chat workflow only when the answer can be produced from the conversation, stable model knowledge, writing/reasoning ability, or already-supplied context. If the request needs information from outside those sources, choose a workflow with the needed capability.\n"
|
||||
"5. Choose a web-answer workflow when the missing capability is external facts or source grounding and one search-and-answer pass should be enough. Needing web evidence by itself is not a reason to choose Research.\n"
|
||||
"6. Choose the research workflow only when the standalone request asks for or truly requires investigation, comparison, dispute resolution, claim validation, broad synthesis, or a second search pass. If unsure between Web Answer and Research, choose Web Answer.\n\n"
|
||||
"Context resolution rules:\n"
|
||||
"- Short follow-ups usually inherit the previous subject, place, entity, file, source, or task unless the user clearly changes topic.\n"
|
||||
"- Resolve pronouns and fragments such as 'that', 'it', 'there', 'also', 'and', 'politically', or 'what about' into the standalone request.\n"
|
||||
"- For web workflows, write search queries for the standalone factual request, not the literal fragment the user typed.\n\n"
|
||||
"Long-message routing rule:\n"
|
||||
"- If the current user message is shown as a digest, route from the user's explicit request and the required capabilities. A long pasted payload alone does not require web search or research.\n\n"
|
||||
f"Recent conversation:\n{_format_recent_messages(recent_messages, char_limit=history_chars)}\n\n"
|
||||
f"Current user message or routing digest:\n{message_excerpt}\n\n"
|
||||
f"Attachments:\n{attachment_line}\n\n"
|
||||
"Allowed workflows. This list is already filtered by interface settings and available capabilities; choose only from this list:\n"
|
||||
f"{_format_workflow_choices(manifests)}\n\n"
|
||||
"Return JSON only with this shape:\n"
|
||||
"{\n"
|
||||
' "workflow_id": "<id or slug from allowed workflows>",\n'
|
||||
' "confidence": 0.0,\n'
|
||||
' "reason": "<brief reason>",\n'
|
||||
' "inputs": {\n'
|
||||
' "resolved_request": "<standalone interpretation of the current request>",\n'
|
||||
' "web_search_query": "<required for web workflows>",\n'
|
||||
' "web_search_queries": ["<required for web workflows, 1-5 concise queries>"]\n'
|
||||
" }\n"
|
||||
"}\n"
|
||||
"For non-web workflows, inputs may be empty unless useful. For web workflows, web_search_query and web_search_queries are required."
|
||||
)
|
||||
|
||||
|
||||
async def select_workflow(
|
||||
db: Session,
|
||||
*,
|
||||
message: str,
|
||||
recent_messages: List[Dict[str, Any]],
|
||||
attachments: List[Dict[str, Any]],
|
||||
library_slug: Optional[str],
|
||||
router_model: Optional[str],
|
||||
chat_model: Optional[str],
|
||||
web_search_enabled: bool = False,
|
||||
confidence_threshold: float = 0.55,
|
||||
) -> Dict[str, Any]:
|
||||
fallback = db.query(WorkflowDefinition).filter(WorkflowDefinition.slug == "input-output").first()
|
||||
if fallback is None:
|
||||
raise RuntimeError("The built-in input-output workflow is missing.")
|
||||
fallback_result = _fallback_result(fallback)
|
||||
has_attachments = bool(attachments)
|
||||
manifests = _allowed_manifests(
|
||||
workflow_manifests(db),
|
||||
library_slug=library_slug,
|
||||
web_search_enabled=web_search_enabled,
|
||||
has_attachments=has_attachments,
|
||||
)
|
||||
fast = _fast_path(
|
||||
manifests,
|
||||
message=message,
|
||||
library_slug=library_slug,
|
||||
web_search_enabled=web_search_enabled,
|
||||
has_attachments=has_attachments,
|
||||
)
|
||||
if fast:
|
||||
return fast
|
||||
manifests = _filter_for_interface_settings(manifests, web_search_enabled=web_search_enabled)
|
||||
if not manifests:
|
||||
return fallback_result
|
||||
|
||||
preferred = str(router_model or get_workflow_router_model_preference() or "").strip()
|
||||
model = preferred or str(chat_model or "").strip()
|
||||
if not model:
|
||||
return fallback_result
|
||||
if preferred:
|
||||
try:
|
||||
catalog = await list_model_catalog()
|
||||
if preferred not in (catalog.get("chat_models") or []):
|
||||
model = str(chat_model or "").strip()
|
||||
except Exception:
|
||||
model = str(chat_model or "").strip() or preferred
|
||||
if not model:
|
||||
return fallback_result
|
||||
|
||||
prompt = _router_prompt(message=message, recent_messages=recent_messages, attachments=attachments, manifests=manifests)
|
||||
try:
|
||||
result = await chat_typed(
|
||||
model,
|
||||
[{"role": "user", "content": prompt}],
|
||||
format=ROUTER_FORMAT,
|
||||
options={"temperature": 0, "num_ctx": 4096},
|
||||
)
|
||||
parsed = json.loads(result.content)
|
||||
workflow_id = str(parsed.get("workflow_id") or "")
|
||||
selected = next((item for item in manifests if item["workflow_id"] == workflow_id or item["slug"] == workflow_id), None)
|
||||
confidence = float(parsed.get("confidence") or 0)
|
||||
forced_web = _forced_web_manifest(manifests, library_slug=library_slug) if web_search_enabled else None
|
||||
forced = False
|
||||
if selected is None and forced_web:
|
||||
selected = forced_web
|
||||
confidence = max(confidence, 0.95)
|
||||
forced = True
|
||||
elif selected is not None and forced_web and "web" not in (selected.get("required_capabilities") or []):
|
||||
selected = forced_web
|
||||
confidence = max(confidence, 0.95)
|
||||
forced = True
|
||||
if selected is None or (confidence < confidence_threshold and not forced):
|
||||
return fallback_result
|
||||
if "rag" in selected["required_capabilities"] and not library_slug:
|
||||
return fallback_result
|
||||
inputs = _normalize_router_inputs(selected, parsed.get("inputs"), message)
|
||||
return {
|
||||
"workflow_id": selected["workflow_id"],
|
||||
"workflow_slug": selected["slug"],
|
||||
"confidence": max(0.0, min(confidence, 1.0)),
|
||||
"reason": (str(parsed.get("reason") or "") + (" Forced web search is enabled." if forced else "")).strip(),
|
||||
"inputs": inputs,
|
||||
"fallback": False,
|
||||
"model": model,
|
||||
}
|
||||
except Exception as exc:
|
||||
return {**fallback_result, "reason": f"Router failed: {type(exc).__name__}: {exc}"}
|
||||
644
backend/agent/runtime.py
Normal file
644
backend/agent/runtime.py
Normal file
@@ -0,0 +1,644 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import models as chat_models
|
||||
from ..chat_memory import safe_sync_chat_memory_for_session
|
||||
from ..ollama_client import chat_typed
|
||||
from .bindings import BindingError, resolve_bindings
|
||||
from .events import EventWriter
|
||||
from .models import WorkflowConfirmation, WorkflowNodeRun, WorkflowRevision, WorkflowRun
|
||||
from .registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
from .schemas import WorkflowGraph, WorkflowNode
|
||||
from .validation import validate_workflow_graph
|
||||
|
||||
|
||||
TERMINAL_NODE_STATUSES = {"completed", "failed", "skipped", "cancelled"}
|
||||
|
||||
|
||||
def json_size(value: Any) -> int:
|
||||
return len(json.dumps(value, ensure_ascii=False, default=str))
|
||||
|
||||
|
||||
def collect_sources(value: Any) -> List[Any]:
|
||||
output: List[Any] = []
|
||||
seen = set()
|
||||
|
||||
def visit(item: Any) -> None:
|
||||
if isinstance(item, dict):
|
||||
if isinstance(item.get("sources"), list):
|
||||
for source in item["sources"]:
|
||||
key = json.dumps(source, sort_keys=True, ensure_ascii=False, default=str)
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
output.append(source)
|
||||
for child in item.values():
|
||||
visit(child)
|
||||
elif isinstance(item, list):
|
||||
for child in item:
|
||||
visit(child)
|
||||
|
||||
visit(value)
|
||||
return output
|
||||
|
||||
|
||||
def _merge_values(values: List[Any], deduplicate_by: Optional[str]) -> Dict[str, Any]:
|
||||
context_parts: List[str] = []
|
||||
sources: List[Any] = []
|
||||
items: List[Any] = []
|
||||
seen = set()
|
||||
for value in values:
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, dict):
|
||||
text = str(value.get("context_block") or value.get("content") or "").strip()
|
||||
if text:
|
||||
context_parts.append(text)
|
||||
candidates = value.get("sources") if isinstance(value.get("sources"), list) else []
|
||||
items.append(value)
|
||||
elif isinstance(value, list):
|
||||
candidates = value
|
||||
items.extend(value)
|
||||
else:
|
||||
candidates = []
|
||||
context_parts.append(str(value))
|
||||
for source in candidates:
|
||||
if deduplicate_by and isinstance(source, dict):
|
||||
key = str(source.get(deduplicate_by) or json.dumps(source, sort_keys=True, default=str))
|
||||
else:
|
||||
key = json.dumps(source, sort_keys=True, ensure_ascii=False, default=str)
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
sources.append(source)
|
||||
return {"context_block": "\n\n".join(context_parts), "sources": sources, "items": items}
|
||||
|
||||
|
||||
class WorkflowRuntime:
|
||||
def __init__(self, registry: NativeToolProvider, db_factory) -> None:
|
||||
self.registry = registry
|
||||
self.db_factory = db_factory
|
||||
self.active_runs: Dict[str, asyncio.Task] = {}
|
||||
self.cancellation_events: Dict[str, asyncio.Event] = {}
|
||||
self.confirmation_futures: Dict[str, asyncio.Future] = {}
|
||||
|
||||
def start(self, run_id: str) -> None:
|
||||
if run_id in self.active_runs and not self.active_runs[run_id].done():
|
||||
return
|
||||
task = asyncio.create_task(self.execute(run_id))
|
||||
self.active_runs[run_id] = task
|
||||
task.add_done_callback(lambda _task: self.active_runs.pop(run_id, None))
|
||||
|
||||
def cancel(self, run_id: str) -> bool:
|
||||
event = self.cancellation_events.get(run_id)
|
||||
if event:
|
||||
event.set()
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if not run:
|
||||
return False
|
||||
run.cancellation_requested = True
|
||||
db.commit()
|
||||
return True
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def resolve_confirmation(self, confirmation_id: str, approved: bool) -> bool:
|
||||
future = self.confirmation_futures.get(confirmation_id)
|
||||
if future and not future.done():
|
||||
future.set_result(bool(approved))
|
||||
return True
|
||||
return False
|
||||
|
||||
async def execute(self, run_id: str) -> None:
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if run is None:
|
||||
return
|
||||
revision = db.query(WorkflowRevision).filter(WorkflowRevision.id == run.workflow_revision_id).first()
|
||||
if revision is None:
|
||||
run.status = "failed"
|
||||
run.error_json = json.dumps({"message": "Workflow revision not found."})
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.commit()
|
||||
return
|
||||
graph_raw = json.loads(revision.graph_json)
|
||||
inputs = json.loads(run.inputs_json or "{}")
|
||||
workflow_id = run.workflow_id
|
||||
selection_mode = run.selection_mode
|
||||
session_id = run.session_id
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
writer = EventWriter(run_id, workflow_id, self.db_factory)
|
||||
cancellation_event = asyncio.Event()
|
||||
self.cancellation_events[run_id] = cancellation_event
|
||||
graph = WorkflowGraph.model_validate(graph_raw)
|
||||
validation = validate_workflow_graph(graph_raw, self.registry)
|
||||
if not validation.valid:
|
||||
await self._fail_run(run_id, writer, "Workflow validation failed.", {"errors": [item.model_dump() for item in validation.errors]})
|
||||
return
|
||||
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
run.status = "running"
|
||||
run.started_at = datetime.utcnow()
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
await writer.emit("run_started", {"inputs": inputs})
|
||||
|
||||
started = time.monotonic()
|
||||
counters = {"tool_calls": 0, "llm_calls": 0, "nodes": 0}
|
||||
counter_lock = asyncio.Lock()
|
||||
node_outputs: Dict[str, Any] = {}
|
||||
run_values = dict(inputs.get("run") or {})
|
||||
run_values["maximum_tool_calls_override"] = graph.limits.maximum_tool_calls
|
||||
workflow_inputs = dict(inputs.get("input") or {})
|
||||
values = {"input": workflow_inputs, "run": run_values, "nodes": {}}
|
||||
|
||||
def consume_llm_call() -> None:
|
||||
counters["llm_calls"] += 1
|
||||
if counters["llm_calls"] > graph.limits.maximum_llm_calls:
|
||||
raise RuntimeError("Workflow exceeded maximum_llm_calls.")
|
||||
|
||||
try:
|
||||
if (
|
||||
selection_mode == "direct"
|
||||
or run_values.get("compatibility_rag_enabled")
|
||||
or run_values.get("compatibility_web_enabled")
|
||||
):
|
||||
existing_context_blocks = list(run_values.get("context_blocks") or [])
|
||||
compatibility_context_blocks = await self._prepare_compatibility_context(
|
||||
run_id, workflow_id, run_values, workflow_inputs, writer, cancellation_event, counters, consume_llm_call
|
||||
)
|
||||
run_values["context_blocks"] = [*compatibility_context_blocks, *existing_context_blocks]
|
||||
await asyncio.wait_for(
|
||||
self._execute_graph(
|
||||
run_id, workflow_id, session_id, selection_mode, graph, values, node_outputs,
|
||||
writer, cancellation_event, counters, counter_lock, consume_llm_call,
|
||||
explicit_user_action=bool(inputs.get("explicit_user_action")),
|
||||
),
|
||||
timeout=graph.limits.maximum_runtime_seconds,
|
||||
)
|
||||
if cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
output_nodes = [node for node in graph.nodes if node.type == "output" and node.id in node_outputs]
|
||||
if not output_nodes:
|
||||
raise RuntimeError("Workflow completed without an output node result.")
|
||||
final_output = node_outputs[output_nodes[-1].id]
|
||||
if json_size(final_output) > graph.limits.maximum_result_chars:
|
||||
raise RuntimeError("Workflow final output exceeded maximum_result_chars.")
|
||||
await self._persist_assistant_message(run_id, final_output, counters, time.monotonic() - started)
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
run.status = "completed"
|
||||
run.outputs_json = json.dumps(final_output, ensure_ascii=False, default=str)
|
||||
run.metrics_json = json.dumps({**counters, "duration_seconds": time.monotonic() - started})
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
await writer.emit("run_completed", {"output": final_output, "metrics": {**counters, "duration_seconds": time.monotonic() - started}})
|
||||
except asyncio.CancelledError:
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
run.status = "cancelled"
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.metrics_json = json.dumps({**counters, "duration_seconds": time.monotonic() - started})
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
await writer.emit("run_cancelled", {"metrics": counters})
|
||||
except Exception as exc:
|
||||
await self._fail_run(run_id, writer, f"{type(exc).__name__}: {exc}", {"metrics": counters})
|
||||
finally:
|
||||
self.cancellation_events.pop(run_id, None)
|
||||
|
||||
async def _prepare_compatibility_context(
|
||||
self, run_id: str, workflow_id: str, run_values: Dict[str, Any], workflow_inputs: Dict[str, Any],
|
||||
writer: EventWriter, cancellation_event: asyncio.Event, counters: Dict[str, int], consume_llm_call,
|
||||
) -> List[Any]:
|
||||
blocks: List[Any] = []
|
||||
context = ToolExecutionContext(
|
||||
run_id=run_id, workflow_id=workflow_id, node_id="compatibility", session_id=run_values.get("session_id"),
|
||||
selection_mode="direct", explicit_user_action=True,
|
||||
emit=lambda event_type, payload: writer.emit(event_type, payload, "compatibility"),
|
||||
cancellation_event=cancellation_event, db_factory=self.db_factory, registry=self.registry,
|
||||
run_values=run_values, consume_llm_call=consume_llm_call,
|
||||
)
|
||||
prompt = str(workflow_inputs.get("prompt") or "")
|
||||
rag_enabled = bool(run_values.get("compatibility_rag_enabled", run_values.get("manual_library_enabled")))
|
||||
web_enabled = bool(run_values.get("compatibility_web_enabled", run_values.get("web_search_enabled")))
|
||||
if run_values.get("library_slug") and rag_enabled and prompt:
|
||||
try:
|
||||
counters["tool_calls"] += 1
|
||||
await writer.emit("tool_started", {"tool": "heimgeist.knowledge_search"}, "compatibility")
|
||||
result = await self.registry.call_tool("heimgeist.knowledge_search", {
|
||||
"prompt": prompt, "library_slug": run_values["library_slug"], "top_k": 5,
|
||||
"context_character_budget": 12000, "embedding_model": None,
|
||||
}, context)
|
||||
blocks.append(result)
|
||||
await writer.emit("tool_result", {"tool": "heimgeist.knowledge_search", "result": result}, "compatibility")
|
||||
except Exception as exc:
|
||||
await writer.emit("tool_result", {"tool": "heimgeist.knowledge_search", "error": str(exc)}, "compatibility")
|
||||
if web_enabled and prompt:
|
||||
try:
|
||||
query_args = {"prompt": prompt, "model": run_values["chat_model"], "messages": run_values.get("messages") or []}
|
||||
counters["tool_calls"] += 1
|
||||
queries = await self.registry.call_tool("heimgeist.web_generate_queries", query_args, context)
|
||||
counters["tool_calls"] += 1
|
||||
search = await self.registry.call_tool("heimgeist.web_search", {
|
||||
"query": None, "queries": queries["queries"], "engines": run_values.get("searx_engines") or [],
|
||||
"maximum_results": 14, "searx_url": run_values.get("searx_url"),
|
||||
}, context)
|
||||
counters["tool_calls"] += 1
|
||||
fetched = await self.registry.call_tool("heimgeist.web_fetch", {"url": None, "urls": search["results"], "maximum_pages": 6}, context)
|
||||
counters["tool_calls"] += 1
|
||||
ranked = await self.registry.call_tool("heimgeist.web_rerank", {
|
||||
"prompt": prompt, "pages": fetched["pages"], "model": run_values["chat_model"], "rerank_model": None,
|
||||
"context_excerpt": "", "maximum_results": 6, "minimum_score": 55,
|
||||
}, context)
|
||||
blocks.append(ranked)
|
||||
await writer.emit("tool_result", {"tool": "compatibility_web", "result": ranked}, "compatibility")
|
||||
except Exception as exc:
|
||||
await writer.emit("tool_result", {"tool": "compatibility_web", "error": str(exc)}, "compatibility")
|
||||
return blocks
|
||||
|
||||
async def _execute_graph(
|
||||
self, run_id: str, workflow_id: str, session_id: Optional[str], selection_mode: str,
|
||||
graph: WorkflowGraph, values: Dict[str, Any], node_outputs: Dict[str, Any], writer: EventWriter,
|
||||
cancellation_event: asyncio.Event, counters: Dict[str, int], counter_lock: asyncio.Lock, consume_llm_call,
|
||||
explicit_user_action: bool,
|
||||
) -> None:
|
||||
nodes = {node.id: node for node in graph.nodes}
|
||||
incoming = defaultdict(list)
|
||||
outgoing = defaultdict(list)
|
||||
for edge in graph.edges:
|
||||
incoming[edge.target].append(edge)
|
||||
outgoing[edge.source].append(edge)
|
||||
statuses = {node_id: "pending" for node_id in nodes}
|
||||
semaphore = asyncio.Semaphore(graph.limits.maximum_concurrency)
|
||||
|
||||
def edge_active(edge) -> bool:
|
||||
source_node = nodes[edge.source]
|
||||
if statuses[edge.source] != "completed":
|
||||
return False
|
||||
if source_node.type != "condition":
|
||||
return True
|
||||
result = bool((node_outputs.get(edge.source) or {}).get("result"))
|
||||
return edge.source_handle in {"output", "true" if result else "false"}
|
||||
|
||||
async def execute_one(node: WorkflowNode) -> None:
|
||||
async with semaphore:
|
||||
if cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
statuses[node.id] = "running"
|
||||
counters["nodes"] += 1
|
||||
await self._create_node_run(run_id, node.id, "running")
|
||||
await writer.emit("node_started", {"type": node.type}, node.id)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
output, resolved_inputs = await self._execute_node(
|
||||
run_id, workflow_id, session_id, selection_mode, node, values, writer,
|
||||
cancellation_event, counters, counter_lock, consume_llm_call, explicit_user_action,
|
||||
)
|
||||
if json_size(output) > graph.limits.maximum_result_chars:
|
||||
raise RuntimeError(f"Node {node.id} output exceeded maximum_result_chars.")
|
||||
statuses[node.id] = "completed"
|
||||
node_outputs[node.id] = output
|
||||
values["nodes"][node.id] = {"output": output}
|
||||
await self._finish_node_run(run_id, node.id, "completed", resolved_inputs, output, None, time.monotonic() - started)
|
||||
for source in collect_sources(output):
|
||||
await writer.emit("source_found", {"source": source}, node.id)
|
||||
await writer.emit("node_completed", {"output": output, "duration_seconds": time.monotonic() - started}, node.id)
|
||||
except Exception as exc:
|
||||
statuses[node.id] = "failed"
|
||||
error = {"type": type(exc).__name__, "message": str(exc), "node_id": node.id}
|
||||
await self._finish_node_run(run_id, node.id, "failed", None, None, error, time.monotonic() - started)
|
||||
await writer.emit("node_failed", error, node.id)
|
||||
raise
|
||||
|
||||
while True:
|
||||
if cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
pending = [node_id for node_id, status in statuses.items() if status == "pending"]
|
||||
if not pending:
|
||||
break
|
||||
progressed = False
|
||||
ready: List[WorkflowNode] = []
|
||||
for node_id in pending:
|
||||
dependencies = incoming[node_id]
|
||||
if any(statuses[edge.source] not in TERMINAL_NODE_STATUSES for edge in dependencies):
|
||||
continue
|
||||
if dependencies and not any(edge_active(edge) for edge in dependencies):
|
||||
statuses[node_id] = "skipped"
|
||||
await self._create_node_run(run_id, node_id, "skipped")
|
||||
await writer.emit("node_completed", {"skipped": True}, node_id)
|
||||
progressed = True
|
||||
continue
|
||||
ready.append(nodes[node_id])
|
||||
if ready:
|
||||
progressed = True
|
||||
for node in ready:
|
||||
statuses[node.id] = "queued"
|
||||
await writer.emit("node_queued", {"type": node.type}, node.id)
|
||||
await asyncio.gather(*(execute_one(node) for node in ready))
|
||||
if not progressed:
|
||||
raise RuntimeError("Workflow scheduler could not resolve remaining nodes.")
|
||||
|
||||
async def _execute_node(
|
||||
self, run_id: str, workflow_id: str, session_id: Optional[str], selection_mode: str,
|
||||
node: WorkflowNode, values: Dict[str, Any], writer: EventWriter, cancellation_event: asyncio.Event,
|
||||
counters: Dict[str, int], counter_lock: asyncio.Lock, consume_llm_call, explicit_user_action: bool,
|
||||
) -> tuple[Any, Any]:
|
||||
if node.type == "input":
|
||||
return dict(values["input"]), dict(values["input"])
|
||||
if node.type == "output":
|
||||
resolved = resolve_bindings(node.config.get("value", {}), values)
|
||||
return resolved, resolved
|
||||
if node.type == "template":
|
||||
template = str(node.config.get("template") or "")
|
||||
resolved = resolve_bindings(template, values)
|
||||
return resolved, {"template": resolved}
|
||||
if node.type == "select":
|
||||
resolved = resolve_bindings(node.config.get("value"), values)
|
||||
return resolved, {"value": resolved}
|
||||
if node.type == "merge":
|
||||
resolved_values = []
|
||||
for item in node.config.get("values") or []:
|
||||
try:
|
||||
resolved_values.append(resolve_bindings(item, values))
|
||||
except BindingError:
|
||||
if not node.config.get("allow_missing"):
|
||||
raise
|
||||
output = _merge_values(resolved_values, node.config.get("deduplicate_by"))
|
||||
return output, {"values": resolved_values}
|
||||
if node.type == "limit":
|
||||
resolved = resolve_bindings(node.config.get("value"), values)
|
||||
maximum = max(1, int(node.config.get("maximum_chars") or 12000))
|
||||
output = self._limit_value(resolved, maximum)
|
||||
return output, {"value": resolved, "maximum_chars": maximum}
|
||||
if node.type == "condition":
|
||||
left = resolve_bindings(node.config.get("value"), values)
|
||||
right = resolve_bindings(node.config.get("compare_to"), values)
|
||||
result = self._condition(node.config.get("operation"), left, right)
|
||||
return {"result": result, "value": left}, {"value": left, "compare_to": right}
|
||||
if node.type == "prompt":
|
||||
return await self._execute_prompt(node, values, writer, consume_llm_call, cancellation_event)
|
||||
if node.type in {"tool", "agent"}:
|
||||
tool_name = "heimgeist.agent" if node.type == "agent" else str(node.config.get("tool") or "")
|
||||
arguments_config = node.config.get("arguments") or node.config
|
||||
arguments = resolve_bindings(arguments_config, values)
|
||||
if tool_name == "heimgeist.chat":
|
||||
run_context_blocks = values["run"].get("context_blocks") or []
|
||||
node_context_blocks = arguments.get("context_blocks") or []
|
||||
if run_context_blocks:
|
||||
arguments["context_blocks"] = [*node_context_blocks, *run_context_blocks]
|
||||
async with counter_lock:
|
||||
counters["tool_calls"] += 1
|
||||
maximum = int(values.get("run", {}).get("maximum_tool_calls_override") or 0)
|
||||
if maximum and counters["tool_calls"] > maximum:
|
||||
raise RuntimeError("Workflow exceeded maximum tool calls.")
|
||||
definition = self.registry.get_tool(tool_name)
|
||||
|
||||
async def request_confirmation(tool: ToolDefinition, tool_arguments: Dict[str, Any]) -> bool:
|
||||
if explicit_user_action or selection_mode != "automatic":
|
||||
return True
|
||||
return await self._request_confirmation(run_id, workflow_id, node.id, tool, tool_arguments, writer)
|
||||
|
||||
context = ToolExecutionContext(
|
||||
run_id=run_id, workflow_id=workflow_id, node_id=node.id, session_id=session_id,
|
||||
selection_mode=selection_mode, explicit_user_action=explicit_user_action,
|
||||
emit=lambda event_type, payload: writer.emit(event_type, payload, node.id),
|
||||
cancellation_event=cancellation_event, db_factory=self.db_factory, registry=self.registry,
|
||||
run_values=values["run"], request_confirmation=request_confirmation,
|
||||
consume_llm_call=consume_llm_call, show_thinking=bool(values["run"].get("show_thinking")),
|
||||
)
|
||||
if definition.requires_confirmation:
|
||||
approved = await request_confirmation(definition, arguments)
|
||||
if not approved:
|
||||
return {"status": "rejected", "confirmed": False, "result": {}}, arguments
|
||||
await writer.emit("tool_started", {"tool": tool_name, "arguments": arguments}, node.id)
|
||||
result = await self.registry.call_tool(tool_name, arguments, context)
|
||||
await writer.emit("tool_result", {"tool": tool_name, "result": result}, node.id)
|
||||
return result, arguments
|
||||
raise RuntimeError(f"Unsupported node type: {node.type}")
|
||||
|
||||
async def _execute_prompt(self, node: WorkflowNode, values: Dict[str, Any], writer: EventWriter, consume_llm_call, cancellation_event) -> tuple[Any, Any]:
|
||||
source = node.config.get("model_source")
|
||||
if source == "fixed":
|
||||
model = str(node.config.get("model") or "")
|
||||
elif source == "router_model":
|
||||
model = str(values["run"].get("router_model") or values["run"].get("chat_model") or "")
|
||||
elif source == "workflow_variable":
|
||||
model = str(resolve_bindings(node.config.get("model"), values) or "")
|
||||
else:
|
||||
model = str(values["run"].get("chat_model") or "")
|
||||
if not model:
|
||||
raise RuntimeError(f"Prompt node {node.id} has no available model.")
|
||||
system = resolve_bindings(str(node.config.get("system_template") or ""), values)
|
||||
user = resolve_bindings(str(node.config.get("user_template") or ""), values)
|
||||
messages = []
|
||||
if system:
|
||||
messages.append({"role": "system", "content": system})
|
||||
messages.append({"role": "user", "content": user})
|
||||
output_mode = node.config.get("output_mode") or "text"
|
||||
format_schema = node.config.get("json_schema") if output_mode in {"json", "score", "decision"} else None
|
||||
consume_llm_call()
|
||||
result = await chat_typed(
|
||||
model, messages,
|
||||
format=format_schema,
|
||||
options={"temperature": float(node.config.get("temperature") or 0), **(node.config.get("generation_options") or {})},
|
||||
cancellation_event=cancellation_event,
|
||||
)
|
||||
if result.thinking and values["run"].get("show_thinking"):
|
||||
await writer.emit("model_thinking", {"text": result.thinking}, node.id)
|
||||
if result.content:
|
||||
await writer.emit("model_token", {"text": result.content}, node.id)
|
||||
if output_mode == "text":
|
||||
output: Any = {"content": result.content}
|
||||
else:
|
||||
try:
|
||||
output = json.loads(result.content)
|
||||
except Exception:
|
||||
if not node.config.get("json_repair"):
|
||||
raise RuntimeError(f"Prompt node {node.id} returned invalid JSON.")
|
||||
consume_llm_call()
|
||||
repair = await chat_typed(
|
||||
model,
|
||||
[{"role": "user", "content": f"Repair this into valid JSON matching the schema. Return JSON only.\n{result.content}"}],
|
||||
format=format_schema,
|
||||
options={"temperature": 0},
|
||||
cancellation_event=cancellation_event,
|
||||
)
|
||||
output = json.loads(repair.content)
|
||||
return output, {"model": model, "messages": messages, "output_mode": output_mode}
|
||||
|
||||
async def _request_confirmation(
|
||||
self, run_id: str, workflow_id: str, node_id: str, definition: ToolDefinition,
|
||||
arguments: Dict[str, Any], writer: EventWriter,
|
||||
) -> bool:
|
||||
confirmation_id = str(uuid.uuid4())
|
||||
db = self.db_factory()
|
||||
try:
|
||||
db.add(WorkflowConfirmation(
|
||||
id=confirmation_id, workflow_run_id=run_id, node_id=node_id, tool_name=definition.name,
|
||||
request_json=json.dumps(arguments, ensure_ascii=False, default=str),
|
||||
))
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
run.status = "waiting_confirmation"
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
await writer.emit("confirmation_required", {
|
||||
"confirmation_id": confirmation_id, "tool": definition.name, "risk_level": definition.risk_level,
|
||||
"arguments": arguments,
|
||||
}, node_id)
|
||||
future = asyncio.get_running_loop().create_future()
|
||||
self.confirmation_futures[confirmation_id] = future
|
||||
try:
|
||||
approved = bool(await future)
|
||||
finally:
|
||||
self.confirmation_futures.pop(confirmation_id, None)
|
||||
db = self.db_factory()
|
||||
try:
|
||||
confirmation = db.query(WorkflowConfirmation).filter(WorkflowConfirmation.id == confirmation_id).first()
|
||||
if confirmation:
|
||||
confirmation.status = "approved" if approved else "rejected"
|
||||
confirmation.response_json = json.dumps({"approved": approved})
|
||||
confirmation.resolved_at = datetime.utcnow()
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if run:
|
||||
run.status = "running"
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
return approved
|
||||
|
||||
@staticmethod
|
||||
def _condition(operation: str, left: Any, right: Any) -> bool:
|
||||
if operation == "equals": return left == right
|
||||
if operation == "not_equals": return left != right
|
||||
if operation == "exists": return left not in (None, "", [], {})
|
||||
if operation == "greater_than": return left > right
|
||||
if operation == "less_than": return left < right
|
||||
if operation == "contains": return right in left
|
||||
if operation == "array_not_empty": return isinstance(left, list) and bool(left)
|
||||
if operation == "score_at_least": return float(left or 0) >= float(right or 0)
|
||||
raise RuntimeError(f"Unsupported condition operation: {operation}")
|
||||
|
||||
@staticmethod
|
||||
def _limit_value(value: Any, maximum: int) -> Any:
|
||||
if isinstance(value, str):
|
||||
return value[:maximum]
|
||||
if isinstance(value, dict):
|
||||
result = dict(value)
|
||||
if "context_block" in result:
|
||||
result["context_block"] = str(result["context_block"])[:maximum]
|
||||
result.pop("items", None)
|
||||
return result
|
||||
if isinstance(value, list):
|
||||
result = []
|
||||
for item in value:
|
||||
if json_size(result + [item]) > maximum:
|
||||
break
|
||||
result.append(item)
|
||||
return result
|
||||
return value
|
||||
|
||||
async def _create_node_run(self, run_id: str, node_id: str, status: str) -> None:
|
||||
db = self.db_factory()
|
||||
try:
|
||||
row = db.query(WorkflowNodeRun).filter(
|
||||
WorkflowNodeRun.workflow_run_id == run_id,
|
||||
WorkflowNodeRun.node_id == node_id,
|
||||
WorkflowNodeRun.attempt == 1,
|
||||
).first()
|
||||
if row is None:
|
||||
row = WorkflowNodeRun(workflow_run_id=run_id, node_id=node_id, attempt=1)
|
||||
db.add(row)
|
||||
row.status = status
|
||||
if status == "running":
|
||||
row.started_at = datetime.utcnow()
|
||||
if status == "skipped":
|
||||
row.finished_at = datetime.utcnow()
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
async def _finish_node_run(self, run_id: str, node_id: str, status: str, resolved: Any, output: Any, error: Any, duration: float) -> None:
|
||||
db = self.db_factory()
|
||||
try:
|
||||
row = db.query(WorkflowNodeRun).filter(
|
||||
WorkflowNodeRun.workflow_run_id == run_id,
|
||||
WorkflowNodeRun.node_id == node_id,
|
||||
WorkflowNodeRun.attempt == 1,
|
||||
).first()
|
||||
if row:
|
||||
row.status = status
|
||||
row.resolved_inputs_json = json.dumps(resolved, ensure_ascii=False, default=str) if resolved is not None else None
|
||||
row.outputs_json = json.dumps(output, ensure_ascii=False, default=str) if output is not None else None
|
||||
row.error_json = json.dumps(error, ensure_ascii=False, default=str) if error is not None else None
|
||||
row.finished_at = datetime.utcnow()
|
||||
row.metrics_json = json.dumps({"duration_seconds": duration})
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
async def _persist_assistant_message(self, run_id: str, output: Any, counters: Dict[str, int], duration: float) -> None:
|
||||
content = output.get("content") if isinstance(output, dict) else str(output)
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise RuntimeError("Workflow output did not contain assistant content.")
|
||||
sources = collect_sources(output)
|
||||
usage = output.get("usage") if isinstance(output, dict) and isinstance(output.get("usage"), dict) else {}
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if run is None or not run.session_id:
|
||||
return
|
||||
session = db.query(chat_models.ChatSession).filter(chat_models.ChatSession.session_id == run.session_id).first()
|
||||
if session is None:
|
||||
raise RuntimeError("Chat session no longer exists.")
|
||||
db.add(chat_models.ChatMessage(
|
||||
session_pk=session.id, role="assistant", content=content,
|
||||
sources_json=json.dumps(sources, ensure_ascii=False, default=str),
|
||||
workflow_id=run.workflow_id, workflow_revision_id=run.workflow_revision_id, workflow_run_id=run.id,
|
||||
agent_summary_json=json.dumps({
|
||||
"tool_calls": counters["tool_calls"],
|
||||
"llm_calls": counters["llm_calls"],
|
||||
"duration_seconds": duration,
|
||||
"selection_mode": run.selection_mode,
|
||||
}),
|
||||
usage_json=json.dumps(usage),
|
||||
))
|
||||
db.commit()
|
||||
safe_sync_chat_memory_for_session(db, run.session_id)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
async def _fail_run(self, run_id: str, writer: EventWriter, message: str, details: Dict[str, Any]) -> None:
|
||||
error = {"message": message, **details}
|
||||
db = self.db_factory()
|
||||
try:
|
||||
run = db.query(WorkflowRun).filter(WorkflowRun.id == run_id).first()
|
||||
if run:
|
||||
run.status = "failed"
|
||||
run.error_json = json.dumps(error, ensure_ascii=False, default=str)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
await writer.emit("run_failed", error)
|
||||
128
backend/agent/schemas.py
Normal file
128
backend/agent/schemas.py
Normal file
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class WorkflowPosition(BaseModel):
|
||||
x: float = 0
|
||||
y: float = 0
|
||||
|
||||
|
||||
class WorkflowNode(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
type: Literal["input", "output", "tool", "prompt", "agent", "condition", "merge", "template", "select", "limit"]
|
||||
position: WorkflowPosition = Field(default_factory=WorkflowPosition)
|
||||
config: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class WorkflowEdge(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str
|
||||
source: str
|
||||
source_handle: str = "output"
|
||||
target: str
|
||||
target_handle: str = "input"
|
||||
|
||||
|
||||
class WorkflowLimits(BaseModel):
|
||||
maximum_nodes: int = 40
|
||||
maximum_tool_calls: int = 20
|
||||
maximum_llm_calls: int = 8
|
||||
maximum_runtime_seconds: int = 300
|
||||
maximum_result_chars: int = 120_000
|
||||
maximum_concurrency: int = 4
|
||||
|
||||
|
||||
class WorkflowGraph(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
schema_version: int = 1
|
||||
inputs: Dict[str, Dict[str, Any]] = Field(default_factory=dict)
|
||||
outputs: Dict[str, Dict[str, Any]] = Field(default_factory=dict)
|
||||
nodes: List[WorkflowNode]
|
||||
edges: List[WorkflowEdge]
|
||||
limits: WorkflowLimits = Field(default_factory=WorkflowLimits)
|
||||
|
||||
|
||||
class ValidationIssue(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
node_id: Optional[str] = None
|
||||
field_path: Optional[str] = None
|
||||
|
||||
|
||||
class WorkflowValidationResult(BaseModel):
|
||||
valid: bool
|
||||
errors: List[ValidationIssue] = Field(default_factory=list)
|
||||
warnings: List[ValidationIssue] = Field(default_factory=list)
|
||||
|
||||
|
||||
class WorkflowCreateRequest(BaseModel):
|
||||
name: str
|
||||
slug: Optional[str] = None
|
||||
description: str = ""
|
||||
routing_description: str = ""
|
||||
routing_examples: List[str] = Field(default_factory=list)
|
||||
enabled: bool = True
|
||||
graph: Dict[str, Any]
|
||||
|
||||
|
||||
class WorkflowUpdateRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
routing_description: Optional[str] = None
|
||||
routing_examples: Optional[List[str]] = None
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
|
||||
class WorkflowRevisionRequest(BaseModel):
|
||||
graph: Dict[str, Any]
|
||||
created_by: str = "user"
|
||||
|
||||
|
||||
class WorkflowValidateRequest(BaseModel):
|
||||
graph: Dict[str, Any]
|
||||
|
||||
|
||||
class WorkflowRunRequest(BaseModel):
|
||||
session_id: Optional[str] = None
|
||||
message: str = ""
|
||||
model: str
|
||||
selection_mode: Literal["direct", "automatic", "explicit"] = "direct"
|
||||
workflow_id: Optional[str] = None
|
||||
workflow_revision_id: Optional[str] = None
|
||||
library_slug: Optional[str] = None
|
||||
web_search_enabled: bool = False
|
||||
searx_url: Optional[str] = None
|
||||
searx_engines: List[str] = Field(default_factory=list)
|
||||
attachments: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
vision_model: Optional[str] = None
|
||||
transcription_model: Optional[str] = None
|
||||
stream: bool = True
|
||||
router_model: Optional[str] = None
|
||||
show_thinking: bool = False
|
||||
generation_options: Dict[str, Any] = Field(default_factory=dict)
|
||||
sample_inputs: Dict[str, Any] = Field(default_factory=dict)
|
||||
explicit_user_action: bool = False
|
||||
regenerate_index: Optional[int] = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class ConfirmationResponseRequest(BaseModel):
|
||||
approved: bool
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
class RouterSelectRequest(BaseModel):
|
||||
message: str
|
||||
recent_messages: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
attachments: List[Dict[str, Any]] = Field(default_factory=list)
|
||||
library_slug: Optional[str] = None
|
||||
web_search_enabled: bool = False
|
||||
model: Optional[str] = None
|
||||
chat_model: Optional[str] = None
|
||||
confidence_threshold: float = 0.55
|
||||
15
backend/agent/tools/__init__.py
Normal file
15
backend/agent/tools/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from .chat import register_chat_tools
|
||||
from .knowledge import register_knowledge_tools
|
||||
from .memory import register_memory_tools
|
||||
from .saving import register_saving_tools
|
||||
from .vision import register_vision_tools
|
||||
from .web import register_web_tools
|
||||
|
||||
|
||||
def register_native_tools(registry) -> None:
|
||||
register_chat_tools(registry)
|
||||
register_knowledge_tools(registry)
|
||||
register_memory_tools(registry)
|
||||
register_web_tools(registry)
|
||||
register_vision_tools(registry)
|
||||
register_saving_tools(registry)
|
||||
269
backend/agent/tools/chat.py
Normal file
269
backend/agent/tools/chat.py
Normal file
@@ -0,0 +1,269 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from ... import models
|
||||
from ...ollama_client import chat_stream_typed
|
||||
from ..ollama_runtime import run_agent_loop
|
||||
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
|
||||
MESSAGE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"role": {"type": "string"},
|
||||
"content": {"type": "string"},
|
||||
"images": {"type": "array", "items": {"type": "string"}},
|
||||
},
|
||||
"required": ["role", "content"],
|
||||
"additionalProperties": True,
|
||||
}
|
||||
|
||||
|
||||
def _usage_dict(usage: Any) -> Dict[str, int]:
|
||||
return {
|
||||
"prompt_eval_count": usage.prompt_eval_count,
|
||||
"eval_count": usage.eval_count,
|
||||
"total_duration": usage.total_duration,
|
||||
"load_duration": usage.load_duration,
|
||||
"prompt_eval_duration": usage.prompt_eval_duration,
|
||||
"eval_duration": usage.eval_duration,
|
||||
}
|
||||
|
||||
|
||||
def _context_text(blocks: List[Any]) -> str:
|
||||
parts: List[str] = []
|
||||
for block in blocks or []:
|
||||
if isinstance(block, str):
|
||||
text = block
|
||||
elif isinstance(block, dict):
|
||||
text = str(block.get("context_block") or block.get("text") or block.get("content") or "")
|
||||
else:
|
||||
text = str(block or "")
|
||||
if text.strip():
|
||||
parts.append(text.strip())
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _collect_sources(blocks: List[Any]) -> List[Any]:
|
||||
sources: List[Any] = []
|
||||
seen = set()
|
||||
for block in blocks or []:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
for source in block.get("sources") or []:
|
||||
key = str(
|
||||
(source.get("url") or source.get("source_message_id") or source.get("doc_id") or source)
|
||||
if isinstance(source, dict) else source
|
||||
)
|
||||
if key and key not in seen:
|
||||
seen.add(key)
|
||||
sources.append(source)
|
||||
return sources
|
||||
|
||||
|
||||
def _model_error_summary(exc: Exception) -> str:
|
||||
message = str(exc).strip().splitlines()[0] if str(exc).strip() else type(exc).__name__
|
||||
return f"{type(exc).__name__}: {message}"
|
||||
|
||||
|
||||
def _fallback_content_from_context(model: str, exc: Exception, context_blocks: List[Any], context_text: str) -> str:
|
||||
sources = _collect_sources(context_blocks)
|
||||
if not sources and not context_text.strip():
|
||||
return ""
|
||||
|
||||
lines = [
|
||||
f"The selected chat model failed before it could compose an answer ({_model_error_summary(exc)}).",
|
||||
"Retrieved context is still available:",
|
||||
]
|
||||
if sources:
|
||||
for index, source in enumerate(sources[:6], 1):
|
||||
if isinstance(source, dict):
|
||||
title = str(source.get("title") or source.get("url") or f"Source {index}").strip()
|
||||
snippet = str(source.get("snippet") or source.get("text") or "").strip()
|
||||
url = str(source.get("url") or "").strip()
|
||||
lines.append(f"[{index}] {title}")
|
||||
if snippet:
|
||||
lines.append(snippet[:900])
|
||||
if url:
|
||||
lines.append(f"Source: {url}")
|
||||
else:
|
||||
lines.append(f"[{index}] {source}")
|
||||
return "\n\n".join(lines)
|
||||
|
||||
cleaned_context = (
|
||||
context_text
|
||||
.replace("<websearch_context>", "")
|
||||
.replace("</websearch_context>", "")
|
||||
.replace("<chat_memory_context>", "")
|
||||
.replace("</chat_memory_context>", "")
|
||||
.strip()
|
||||
)
|
||||
if cleaned_context:
|
||||
lines.append(cleaned_context[:5000])
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def _drop_superseded_trailing_user_rows(rows: List[Any]) -> List[Any]:
|
||||
if not rows or getattr(rows[-1], "role", None) != "user":
|
||||
return rows
|
||||
first_trailing_user = len(rows) - 1
|
||||
while first_trailing_user > 0 and getattr(rows[first_trailing_user - 1], "role", None) == "user":
|
||||
first_trailing_user -= 1
|
||||
if first_trailing_user == len(rows) - 1:
|
||||
return rows
|
||||
return [*rows[:first_trailing_user], rows[-1]]
|
||||
|
||||
|
||||
def _append_context_to_last_user_message(messages: List[Dict[str, Any]], context_text: str) -> None:
|
||||
if not context_text:
|
||||
return
|
||||
for index in range(len(messages) - 1, -1, -1):
|
||||
if str(messages[index].get("role") or "") == "user":
|
||||
content = str(messages[index].get("content") or "").strip()
|
||||
messages[index]["content"] = f"{content}\n\n{context_text}".strip()
|
||||
return
|
||||
|
||||
|
||||
async def chat_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
messages = [dict(item) for item in arguments.get("messages") or []]
|
||||
context_blocks = arguments.get("context_blocks") or []
|
||||
context_text = _context_text(context_blocks)
|
||||
context_applied = False
|
||||
if context.session_id:
|
||||
db = context.db_factory()
|
||||
try:
|
||||
session = db.query(models.ChatSession).filter(models.ChatSession.session_id == context.session_id).first()
|
||||
rows = [] if not session else (
|
||||
db.query(models.ChatMessage)
|
||||
.filter(models.ChatMessage.session_pk == session.id)
|
||||
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
|
||||
.all()
|
||||
)[-20:]
|
||||
finally:
|
||||
db.close()
|
||||
if rows:
|
||||
rows = _drop_superseded_trailing_user_rows(rows)
|
||||
from ... import main as main_module
|
||||
supports_vision = await main_module._model_supports_vision(arguments["model"])
|
||||
override_index = len(rows) - 1 if rows[-1].role == "user" else None
|
||||
prompt = rows[-1].content if override_index is not None else ""
|
||||
override_content = f"{prompt}\n\n{context_text}".strip() if context_text else None
|
||||
context_applied = bool(override_content)
|
||||
messages = await main_module._build_ollama_messages_from_rows(
|
||||
rows,
|
||||
request_model_supports_vision=supports_vision,
|
||||
vision_model=arguments.get("vision_model"),
|
||||
transcription_model=arguments.get("transcription_model"),
|
||||
override_user_row_index=override_index,
|
||||
override_user_content=override_content,
|
||||
)
|
||||
if context_text and not context_applied:
|
||||
_append_context_to_last_user_message(messages, context_text)
|
||||
system_prompt = str(arguments.get("system_prompt") or "").strip()
|
||||
if system_prompt:
|
||||
messages.insert(0, {"role": "system", "content": system_prompt})
|
||||
|
||||
full_content = ""
|
||||
full_thinking = ""
|
||||
usage: Dict[str, int] = {}
|
||||
try:
|
||||
async for chunk in chat_stream_typed(
|
||||
arguments["model"],
|
||||
messages,
|
||||
options=arguments.get("generation_options") or {},
|
||||
think=bool(arguments.get("reasoning")),
|
||||
cancellation_event=context.cancellation_event,
|
||||
):
|
||||
if chunk.thinking:
|
||||
full_thinking += chunk.thinking
|
||||
if context.show_thinking:
|
||||
await context.emit("model_thinking", {"text": chunk.thinking})
|
||||
if chunk.content:
|
||||
full_content += chunk.content
|
||||
await context.emit("model_token", {"text": chunk.content})
|
||||
if chunk.done:
|
||||
usage = _usage_dict(chunk.usage)
|
||||
except Exception as exc:
|
||||
fallback_content = _fallback_content_from_context(arguments["model"], exc, context_blocks, context_text)
|
||||
if not fallback_content:
|
||||
raise
|
||||
full_content = fallback_content
|
||||
await context.emit("model_token", {"text": full_content})
|
||||
return {
|
||||
"content": full_content,
|
||||
"sources": _collect_sources(context_blocks),
|
||||
"usage": usage,
|
||||
"thinking_available": bool(full_thinking),
|
||||
}
|
||||
|
||||
|
||||
def register_chat_tools(registry: NativeToolProvider) -> None:
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.chat",
|
||||
description="Generate an Ollama chat response from conversation history and supplied context blocks.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model": {"type": "string", "minLength": 1},
|
||||
"messages": {"type": "array", "items": MESSAGE_SCHEMA},
|
||||
"system_prompt": {"type": "string"},
|
||||
"context_blocks": {"type": "array"},
|
||||
"attachments": {"type": "array"},
|
||||
"vision_model": {"type": ["string", "null"]},
|
||||
"transcription_model": {"type": ["string", "null"]},
|
||||
"generation_options": {"type": "object"},
|
||||
"stream": {"type": "boolean"},
|
||||
"reasoning": {"type": "boolean"},
|
||||
},
|
||||
"required": ["model", "messages"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {"type": "string"},
|
||||
"sources": {"type": "array"},
|
||||
"usage": {"type": "object"},
|
||||
"thinking_available": {"type": "boolean"},
|
||||
},
|
||||
"required": ["content", "sources", "usage", "thinking_available"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=chat_handler,
|
||||
timeout_seconds=600,
|
||||
result_size_limit=180_000,
|
||||
llm_call=True,
|
||||
))
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.agent",
|
||||
description="Run a bounded Ollama tool-calling loop over an approved native-tool allowlist.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model": {"type": "string", "minLength": 1},
|
||||
"messages": {"type": "array", "items": MESSAGE_SCHEMA},
|
||||
"allowed_tool_names": {"type": "array", "items": {"type": "string"}, "maxItems": 12},
|
||||
"maximum_rounds": {"type": "integer", "minimum": 1, "maximum": 8},
|
||||
"maximum_output_chars": {"type": "integer", "minimum": 1000, "maximum": 120000},
|
||||
"reasoning": {"type": "boolean"},
|
||||
"generation_options": {"type": "object"},
|
||||
},
|
||||
"required": ["model", "messages", "allowed_tool_names", "maximum_rounds"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {"type": "string"},
|
||||
"tool_summary": {"type": "array"},
|
||||
"usage": {"type": "object"},
|
||||
"rounds": {"type": "integer"},
|
||||
},
|
||||
"required": ["content", "tool_summary", "usage", "rounds"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=run_agent_loop,
|
||||
timeout_seconds=600,
|
||||
result_size_limit=180_000,
|
||||
))
|
||||
114
backend/agent/tools/knowledge.py
Normal file
114
backend/agent/tools/knowledge.py
Normal file
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import multiprocessing
|
||||
import time
|
||||
from typing import Any, Dict
|
||||
|
||||
from ...local_rag import LibraryContextRequest, library_context
|
||||
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
|
||||
def _knowledge_source(source: Dict[str, Any], library_slug: str) -> Dict[str, Any]:
|
||||
return {
|
||||
"type": "knowledge",
|
||||
"library_slug": library_slug,
|
||||
"doc_id": source.get("doc_id"),
|
||||
"title": source.get("title"),
|
||||
"url": source.get("url"),
|
||||
"record_type": source.get("record_type"),
|
||||
"mime": source.get("mime"),
|
||||
"lang": source.get("lang"),
|
||||
"snippet": source.get("snippet"),
|
||||
"scores": source.get("scores") or {},
|
||||
}
|
||||
|
||||
|
||||
def _knowledge_search_worker(connection, arguments: Dict[str, Any]) -> None:
|
||||
try:
|
||||
request = LibraryContextRequest(
|
||||
prompt=arguments["prompt"],
|
||||
top_k=arguments.get("top_k", 5),
|
||||
embed_model=arguments.get("embedding_model"),
|
||||
)
|
||||
connection.send(("ok", library_context(arguments["library_slug"], request)))
|
||||
except BaseException as exc:
|
||||
detail = getattr(exc, "detail", None) or str(exc)
|
||||
connection.send(("error", f"{type(exc).__name__}: {detail}"))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
async def _isolated_library_context(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
process_context = multiprocessing.get_context("spawn")
|
||||
parent_connection, child_connection = process_context.Pipe(duplex=False)
|
||||
process = process_context.Process(target=_knowledge_search_worker, args=(child_connection, arguments), daemon=True)
|
||||
process.start()
|
||||
child_connection.close()
|
||||
deadline = time.monotonic() + 170
|
||||
try:
|
||||
while True:
|
||||
if context.cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
if parent_connection.poll():
|
||||
status, value = parent_connection.recv()
|
||||
if status == "ok":
|
||||
return value
|
||||
raise RuntimeError(value)
|
||||
if not process.is_alive():
|
||||
raise RuntimeError(f"Local retrieval process exited unexpectedly (exit code {process.exitcode}).")
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("Local retrieval exceeded its process timeout.")
|
||||
await asyncio.sleep(0.05)
|
||||
finally:
|
||||
parent_connection.close()
|
||||
if process.is_alive():
|
||||
process.terminate()
|
||||
process.join(timeout=2)
|
||||
|
||||
|
||||
async def knowledge_search_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
payload = await _isolated_library_context(arguments, context)
|
||||
raw_hits = (payload.get("result") or {}).get("sources") or []
|
||||
budget = int(arguments.get("context_character_budget") or 12_000)
|
||||
context_block = str(payload.get("context_block") or "")[:budget]
|
||||
sources = [_knowledge_source(item, arguments["library_slug"]) for item in raw_hits]
|
||||
return {
|
||||
"hits": sources,
|
||||
"context_block": context_block,
|
||||
"sources": sources,
|
||||
"scores": [item.get("scores") or {} for item in sources],
|
||||
}
|
||||
|
||||
|
||||
def register_knowledge_tools(registry: NativeToolProvider) -> None:
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.knowledge_search",
|
||||
description="Retrieve structured evidence from Heimgeist's indexed local Knowledge store.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "minLength": 1},
|
||||
"library_slug": {"type": "string", "minLength": 1},
|
||||
"top_k": {"type": "integer", "minimum": 1, "maximum": 20},
|
||||
"context_character_budget": {"type": "integer", "minimum": 500, "maximum": 60000},
|
||||
"embedding_model": {"type": ["string", "null"]},
|
||||
},
|
||||
"required": ["prompt", "library_slug"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"hits": {"type": "array"},
|
||||
"context_block": {"type": "string"},
|
||||
"sources": {"type": "array"},
|
||||
"scores": {"type": "array"},
|
||||
},
|
||||
"required": ["hits", "context_block", "sources", "scores"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=knowledge_search_handler,
|
||||
timeout_seconds=180,
|
||||
result_size_limit=100_000,
|
||||
))
|
||||
96
backend/agent/tools/memory.py
Normal file
96
backend/agent/tools/memory.py
Normal file
@@ -0,0 +1,96 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from ...chat_memory import build_chat_memory_context, ensure_chat_memory_schema
|
||||
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
|
||||
def _int_argument(arguments: Dict[str, Any], key: str, default: int, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
value = int(arguments.get(key) or default)
|
||||
except Exception:
|
||||
value = default
|
||||
return max(minimum, min(value, maximum))
|
||||
|
||||
|
||||
def _memory_hit(item: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"session_id": item.get("session_id"),
|
||||
"session_name": item.get("session_name"),
|
||||
"user_message_id": item.get("user_message_id"),
|
||||
"assistant_message_id": item.get("assistant_message_id"),
|
||||
"created_at": item.get("created_at"),
|
||||
"score": round(float(item.get("_score") or item.get("score") or 0), 4),
|
||||
"user_excerpt": item.get("user_content"),
|
||||
"assistant_excerpt": item.get("assistant_content"),
|
||||
}
|
||||
|
||||
|
||||
async def chat_memory_search_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
top_k = _int_argument(arguments, "top_k", 6, 1, 20)
|
||||
context_character_budget = _int_argument(arguments, "context_character_budget", 10_000, 500, 60_000)
|
||||
mode = str(arguments.get("mode") or "search").strip().lower()
|
||||
if mode not in {"search", "recent"}:
|
||||
mode = "search"
|
||||
exclude_current_session = bool(arguments.get("exclude_current_session", True))
|
||||
exclude_session_id = context.session_id if exclude_current_session else None
|
||||
|
||||
db = context.db_factory()
|
||||
try:
|
||||
ensure_chat_memory_schema(db.get_bind())
|
||||
payload = build_chat_memory_context(
|
||||
db,
|
||||
str(arguments.get("prompt") or ""),
|
||||
exclude_session_id=exclude_session_id,
|
||||
top_k=top_k,
|
||||
context_character_budget=context_character_budget,
|
||||
mode=mode,
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
sources = payload.get("sources") or []
|
||||
return {
|
||||
"hits": [_memory_hit(item) for item in (payload.get("hits") or [])],
|
||||
"context_block": str(payload.get("context_block") or ""),
|
||||
"sources": sources,
|
||||
"scores": [source.get("score") for source in sources if isinstance(source, dict)],
|
||||
}
|
||||
|
||||
|
||||
def register_memory_tools(registry: NativeToolProvider) -> None:
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.chat_memory_search",
|
||||
description=(
|
||||
"Retrieve relevant completed turns from past Heimgeist chats. Use only when a workflow or agent "
|
||||
"decides previous chats are needed, such as questions about earlier conversations, prior decisions, "
|
||||
"or remembered discussion context; it does not run automatically."
|
||||
),
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "minLength": 1},
|
||||
"top_k": {"type": "integer", "minimum": 1, "maximum": 20},
|
||||
"context_character_budget": {"type": "integer", "minimum": 500, "maximum": 60000},
|
||||
"mode": {"type": "string", "enum": ["search", "recent"]},
|
||||
"exclude_current_session": {"type": "boolean"},
|
||||
},
|
||||
"required": ["prompt"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"hits": {"type": "array"},
|
||||
"context_block": {"type": "string"},
|
||||
"sources": {"type": "array"},
|
||||
"scores": {"type": "array"},
|
||||
},
|
||||
"required": ["hits", "context_block", "sources", "scores"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=chat_memory_search_handler,
|
||||
timeout_seconds=20,
|
||||
result_size_limit=100_000,
|
||||
))
|
||||
86
backend/agent/tools/saving.py
Normal file
86
backend/agent/tools/saving.py
Normal file
@@ -0,0 +1,86 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from ...local_rag import CreateWebsiteRequest, create_library_website
|
||||
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
|
||||
async def save_message_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
from ... import main as main_module
|
||||
|
||||
db = context.db_factory()
|
||||
try:
|
||||
result = await main_module._save_message_to_knowledge_impl(
|
||||
arguments["library_slug"],
|
||||
arguments["message_id"],
|
||||
db,
|
||||
title=arguments.get("title"),
|
||||
content=arguments.get("edited_content"),
|
||||
saved_by="agent" if context.selection_mode == "automatic" else "user",
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
return {"status": "saved", "confirmed": True, "result": result}
|
||||
|
||||
|
||||
async def save_website_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
result = await create_library_website(
|
||||
arguments["library_slug"],
|
||||
CreateWebsiteRequest(url=arguments["url"], title=arguments.get("title")),
|
||||
)
|
||||
return {"status": "saved", "confirmed": True, "result": result}
|
||||
|
||||
|
||||
SAVE_OUTPUT = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {"type": "string"},
|
||||
"confirmed": {"type": "boolean"},
|
||||
"result": {"type": "object"},
|
||||
},
|
||||
"required": ["status", "confirmed", "result"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
def register_saving_tools(registry: NativeToolProvider) -> None:
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.save_message_to_knowledge",
|
||||
description="Save a stable chat message snapshot to Heimgeist's local Knowledge store.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"message_id": {"type": "string", "minLength": 1},
|
||||
"library_slug": {"type": "string", "minLength": 1},
|
||||
"title": {"type": ["string", "null"]},
|
||||
"edited_content": {"type": ["string", "null"]},
|
||||
},
|
||||
"required": ["message_id", "library_slug"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema=SAVE_OUTPUT,
|
||||
handler=save_message_handler,
|
||||
risk_level="write",
|
||||
requires_confirmation=True,
|
||||
timeout_seconds=180,
|
||||
))
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.save_website_to_knowledge",
|
||||
description="Fetch and save a durable website snapshot to Heimgeist's local Knowledge store.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {"type": "string", "minLength": 1},
|
||||
"library_slug": {"type": "string", "minLength": 1},
|
||||
"title": {"type": ["string", "null"]},
|
||||
},
|
||||
"required": ["url", "library_slug"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema=SAVE_OUTPUT,
|
||||
handler=save_website_handler,
|
||||
risk_level="write",
|
||||
requires_confirmation=True,
|
||||
timeout_seconds=180,
|
||||
))
|
||||
49
backend/agent/tools/vision.py
Normal file
49
backend/agent/tools/vision.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
|
||||
async def vision_analyze_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
from ... import main as main_module
|
||||
|
||||
prepared, _images, context_block = await main_module._prepare_chat_message_attachments(
|
||||
arguments.get("attachments") or [],
|
||||
request_model_supports_vision=False,
|
||||
vision_model=arguments.get("vision_model"),
|
||||
transcription_model=arguments.get("transcription_model"),
|
||||
persist_file_text=False,
|
||||
)
|
||||
return {
|
||||
"context_block": context_block,
|
||||
"attachments": [main_module._attachment_history_payload(item) for item in prepared],
|
||||
"sources": [],
|
||||
}
|
||||
|
||||
|
||||
def register_vision_tools(registry: NativeToolProvider) -> None:
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.vision_analyze",
|
||||
description="Analyze chat attachments through Heimgeist's existing vision and extraction path.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"attachments": {"type": "array"},
|
||||
"vision_model": {"type": "string", "minLength": 1},
|
||||
"transcription_model": {"type": ["string", "null"]},
|
||||
},
|
||||
"required": ["attachments", "vision_model"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {"context_block": {"type": "string"}, "attachments": {"type": "array"}, "sources": {"type": "array"}},
|
||||
"required": ["context_block", "attachments", "sources"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=vision_analyze_handler,
|
||||
timeout_seconds=600,
|
||||
result_size_limit=140_000,
|
||||
llm_call=True,
|
||||
))
|
||||
378
backend/agent/tools/web.py
Normal file
378
backend/agent/tools/web.py
Normal file
@@ -0,0 +1,378 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Dict, List
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
from ...ollama_client import chat_typed
|
||||
from ...websearch import (
|
||||
DEFAULT_HEADERS,
|
||||
HTTP_LIMITS,
|
||||
HTTP_TIMEOUT,
|
||||
fallback_rerank,
|
||||
fetch_website_snapshot,
|
||||
render_recent_context,
|
||||
rerank,
|
||||
searx_search,
|
||||
)
|
||||
from ..registry import NativeToolProvider, ToolDefinition, ToolExecutionContext
|
||||
|
||||
|
||||
QUERY_FORMAT = {
|
||||
"type": "object",
|
||||
"properties": {"queries": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 5}},
|
||||
"required": ["queries"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
FETCH_TEXT_LIMIT = 12_000
|
||||
|
||||
NOISE_HOSTS = (
|
||||
"accounts.google.",
|
||||
"collinsdictionary.com",
|
||||
"consent.google.",
|
||||
"de.langenscheidt.com",
|
||||
"dict.cc",
|
||||
"dict.leo.org",
|
||||
"dictionary.cambridge.org",
|
||||
"duden.de",
|
||||
"dwds.de",
|
||||
"langenscheidt.com",
|
||||
"leo.org",
|
||||
"linguee.",
|
||||
"news.google.",
|
||||
)
|
||||
|
||||
NOISE_TITLE_MARKERS = (
|
||||
"before you continue",
|
||||
"deutsch-ubersetzung",
|
||||
"deutsch ubersetzung",
|
||||
"deutsch-uebersetzung",
|
||||
"deutsch uebersetzung",
|
||||
"englisch-deutsch",
|
||||
"english-german",
|
||||
"google consent",
|
||||
"worterbuch",
|
||||
)
|
||||
|
||||
|
||||
def _host_for(url: str) -> str:
|
||||
try:
|
||||
return str(urlparse(url).netloc or "").lower()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _is_noise_result(url: str, title: str = "") -> bool:
|
||||
host = _host_for(url)
|
||||
title_norm = str(title or "").lower()
|
||||
url_norm = str(url or "").lower()
|
||||
if any(marker in host for marker in NOISE_HOSTS):
|
||||
return True
|
||||
if any(marker in title_norm for marker in NOISE_TITLE_MARKERS):
|
||||
return True
|
||||
if "nah-meaning" in url_norm or "what-does-nah-mean" in url_norm:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _clean_queries(generated: List[Any], fallback: str) -> List[str]:
|
||||
cleaned: List[str] = []
|
||||
seen = set()
|
||||
for query in generated:
|
||||
text = " ".join(str(query or "").split()).strip()
|
||||
if not text:
|
||||
continue
|
||||
key = text.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
cleaned.append(text[:300])
|
||||
if len(cleaned) >= 5:
|
||||
break
|
||||
if cleaned:
|
||||
return cleaned
|
||||
fallback_text = " ".join(str(fallback or "").split()).strip()
|
||||
return [fallback_text[:300]] if fallback_text else []
|
||||
|
||||
|
||||
async def generate_queries_handler(arguments: Dict[str, Any], context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
recent = render_recent_context(arguments.get("messages") or [], char_limit=1600)
|
||||
prompt = (
|
||||
"Generate 3 concise, diverse web-search queries for the current request. "
|
||||
"Resolve references using recent conversation. Every query must include the concrete topic, "
|
||||
"entity, or location from the request. Never output standalone generic terms such as latest, "
|
||||
"current, top, today, news, or weather. Return only valid JSON matching the schema.\n\n"
|
||||
f"Current request:\n{arguments['prompt']}\n\nRecent conversation:\n{recent}"
|
||||
)
|
||||
result = await chat_typed(
|
||||
arguments["model"],
|
||||
[{"role": "user", "content": prompt}],
|
||||
format=QUERY_FORMAT,
|
||||
options={"temperature": 0.1},
|
||||
cancellation_event=context.cancellation_event,
|
||||
)
|
||||
try:
|
||||
parsed = json.loads(result.content)
|
||||
queries = parsed.get("queries") if isinstance(parsed, dict) else None
|
||||
except Exception:
|
||||
queries = None
|
||||
return {"queries": _clean_queries(queries or [], arguments["prompt"])}
|
||||
|
||||
|
||||
async def web_search_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
queries = arguments.get("queries") or []
|
||||
if arguments.get("query"):
|
||||
queries = [arguments["query"], *queries]
|
||||
unique_queries = []
|
||||
for query in queries:
|
||||
text = str(query or "").strip()
|
||||
if text and text not in unique_queries:
|
||||
unique_queries.append(text)
|
||||
maximum = max(1, min(int(arguments.get("maximum_results") or 12), 32))
|
||||
async with httpx.AsyncClient(
|
||||
headers=DEFAULT_HEADERS,
|
||||
follow_redirects=True,
|
||||
http2=True,
|
||||
limits=HTTP_LIMITS,
|
||||
timeout=HTTP_TIMEOUT,
|
||||
) as client:
|
||||
responses = await asyncio.gather(*[
|
||||
searx_search(
|
||||
client,
|
||||
query,
|
||||
max_results=min(8, maximum),
|
||||
searx_url=arguments.get("searx_url"),
|
||||
engines=arguments.get("engines") or None,
|
||||
)
|
||||
for query in unique_queries[:5]
|
||||
])
|
||||
results: List[Dict[str, Any]] = []
|
||||
seen = set()
|
||||
for query, items in zip(unique_queries, responses):
|
||||
for item in items:
|
||||
url = str(item.get("url") or "")
|
||||
title = str(item.get("title") or "")
|
||||
if not url or url in seen:
|
||||
continue
|
||||
if _is_noise_result(url, title):
|
||||
continue
|
||||
seen.add(url)
|
||||
results.append({"query": query, "url": url, "title": title, "engine": item.get("engine")})
|
||||
if len(results) >= maximum:
|
||||
break
|
||||
return {"queries": unique_queries, "results": results, "unavailable": not results}
|
||||
|
||||
|
||||
async def web_fetch_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
urls = arguments.get("urls") or []
|
||||
if arguments.get("url"):
|
||||
urls = [arguments["url"], *urls]
|
||||
maximum = max(1, min(int(arguments.get("maximum_pages") or 6), 12))
|
||||
unique = []
|
||||
for item in urls:
|
||||
url = item.get("url") if isinstance(item, dict) else item
|
||||
url = str(url or "").strip()
|
||||
title = str(item.get("title") or "") if isinstance(item, dict) else ""
|
||||
query = str(item.get("query") or "") if isinstance(item, dict) else ""
|
||||
if url and url not in unique and not _is_noise_result(url, title):
|
||||
unique.append(url)
|
||||
semaphore = asyncio.Semaphore(4)
|
||||
|
||||
async def fetch_one(url: str) -> Dict[str, Any]:
|
||||
try:
|
||||
async with semaphore:
|
||||
snapshot = await fetch_website_snapshot(url)
|
||||
full_text = str(snapshot.get("text") or "")
|
||||
text = full_text[:FETCH_TEXT_LIMIT]
|
||||
canonical_url = snapshot.get("url") or snapshot.get("final_url") or url
|
||||
title = snapshot.get("title") or ""
|
||||
if _is_noise_result(str(canonical_url), str(title)):
|
||||
return {
|
||||
"requested_url": snapshot.get("requested_url") or url,
|
||||
"canonical_url": canonical_url,
|
||||
"title": title,
|
||||
"cleaned_text": "",
|
||||
"fetch_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"content_hash": hashlib.sha256(full_text.encode("utf-8", errors="ignore")).hexdigest(),
|
||||
"error": "filtered_noise_page",
|
||||
}
|
||||
return {
|
||||
"requested_url": snapshot.get("requested_url") or url,
|
||||
"canonical_url": canonical_url,
|
||||
"title": title,
|
||||
"cleaned_text": text,
|
||||
"fetch_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"content_hash": hashlib.sha256(full_text.encode("utf-8", errors="ignore")).hexdigest(),
|
||||
"error": None,
|
||||
}
|
||||
except Exception as exc:
|
||||
return {
|
||||
"requested_url": url,
|
||||
"canonical_url": url,
|
||||
"title": "",
|
||||
"cleaned_text": "",
|
||||
"fetch_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"content_hash": "",
|
||||
"error": f"{type(exc).__name__}: {exc}",
|
||||
}
|
||||
|
||||
pages = await asyncio.gather(*(fetch_one(url) for url in unique[:maximum]))
|
||||
return {"pages": pages}
|
||||
|
||||
|
||||
async def web_rerank_handler(arguments: Dict[str, Any], _context: ToolExecutionContext) -> Dict[str, Any]:
|
||||
docs = []
|
||||
for page in arguments.get("pages") or []:
|
||||
if page.get("error") or not str(page.get("cleaned_text") or "").strip():
|
||||
continue
|
||||
url = str(page.get("canonical_url") or page.get("requested_url") or "")
|
||||
title = str(page.get("title") or "")
|
||||
text = str(page.get("cleaned_text") or "")
|
||||
if _is_noise_result(url, title):
|
||||
continue
|
||||
docs.append((url, text))
|
||||
context_excerpt = arguments.get("context_excerpt") or ""
|
||||
try:
|
||||
ranked = await rerank(
|
||||
arguments["prompt"],
|
||||
docs,
|
||||
model=arguments.get("model") or "",
|
||||
context_excerpt=context_excerpt,
|
||||
embed_model=arguments.get("rerank_model"),
|
||||
)
|
||||
except Exception as exc:
|
||||
ranked = fallback_rerank(
|
||||
arguments["prompt"],
|
||||
docs,
|
||||
context_excerpt,
|
||||
reason=f"rerank_exception:{type(exc).__name__}",
|
||||
)
|
||||
maximum = max(1, min(int(arguments.get("maximum_results") or 6), 12))
|
||||
minimum_score = float(arguments.get("minimum_score") or 0)
|
||||
selected = []
|
||||
page_by_url = {
|
||||
str(page.get("canonical_url") or page.get("requested_url") or ""): page
|
||||
for page in arguments.get("pages") or []
|
||||
}
|
||||
for url, text, score in ranked:
|
||||
if score < minimum_score:
|
||||
continue
|
||||
page = page_by_url.get(url) or {}
|
||||
title = str(page.get("title") or "")
|
||||
if _is_noise_result(url, title):
|
||||
continue
|
||||
selected.append({
|
||||
"type": "web",
|
||||
"url": url,
|
||||
"title": page.get("title") or url,
|
||||
"snippet": text[:1600],
|
||||
"score": score,
|
||||
})
|
||||
if len(selected) >= maximum:
|
||||
break
|
||||
context_lines = ["<websearch_context>"]
|
||||
if not selected:
|
||||
context_lines.append("Web search completed but no suitable readable pages were available.")
|
||||
for index, item in enumerate(selected, 1):
|
||||
context_lines.append(f"[W{index}] {item['title']}\n{item['snippet']}\nSource: {item['url']}")
|
||||
context_lines.append("</websearch_context>")
|
||||
return {"results": selected, "context_block": "\n".join(context_lines), "sources": selected}
|
||||
|
||||
|
||||
def register_web_tools(registry: NativeToolProvider) -> None:
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.web_generate_queries",
|
||||
description="Generate validated web-search queries from a request and recent conversation.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "minLength": 1},
|
||||
"model": {"type": "string", "minLength": 1},
|
||||
"messages": {"type": "array"},
|
||||
},
|
||||
"required": ["prompt", "model"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema=QUERY_FORMAT,
|
||||
handler=generate_queries_handler,
|
||||
timeout_seconds=120,
|
||||
llm_call=True,
|
||||
))
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.web_search",
|
||||
description="Search the configured SearXNG service and return structured results without answering.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": ["string", "null"]},
|
||||
"queries": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
|
||||
"engines": {"type": "array", "items": {"type": "string"}},
|
||||
"maximum_results": {"type": "integer", "minimum": 1, "maximum": 32},
|
||||
"searx_url": {"type": ["string", "null"]},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {"queries": {"type": "array"}, "results": {"type": "array"}, "unavailable": {"type": "boolean"}},
|
||||
"required": ["queries", "results", "unavailable"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=web_search_handler,
|
||||
timeout_seconds=45,
|
||||
))
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.web_fetch",
|
||||
description="Fetch and extract selected web pages using Heimgeist's bounded website policy.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {"type": ["string", "null"]},
|
||||
"urls": {"type": "array", "maxItems": 32},
|
||||
"maximum_pages": {"type": "integer", "minimum": 1, "maximum": 12},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {"pages": {"type": "array"}},
|
||||
"required": ["pages"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=web_fetch_handler,
|
||||
timeout_seconds=90,
|
||||
result_size_limit=180_000,
|
||||
))
|
||||
registry.register(ToolDefinition(
|
||||
name="heimgeist.web_rerank",
|
||||
description="Rank extracted web pages using Heimgeist's embedding-based reranker with lexical fallback.",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "minLength": 1},
|
||||
"pages": {"type": "array"},
|
||||
"model": {"type": ["string", "null"]},
|
||||
"rerank_model": {"type": ["string", "null"]},
|
||||
"context_excerpt": {"type": "string"},
|
||||
"maximum_results": {"type": "integer", "minimum": 1, "maximum": 12},
|
||||
"minimum_score": {"type": "number", "minimum": 0, "maximum": 100},
|
||||
},
|
||||
"required": ["prompt", "pages"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {"results": {"type": "array"}, "context_block": {"type": "string"}, "sources": {"type": "array"}},
|
||||
"required": ["results", "context_block", "sources"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=web_rerank_handler,
|
||||
timeout_seconds=180,
|
||||
result_size_limit=120_000,
|
||||
))
|
||||
157
backend/agent/validation.py
Normal file
157
backend/agent/validation.py
Normal file
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict, deque
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from .bindings import iter_references
|
||||
from .registry import NativeToolProvider, SchemaValidationError, validate_json_schema, validate_schema_definition
|
||||
from .schemas import ValidationIssue, WorkflowGraph, WorkflowValidationResult
|
||||
|
||||
|
||||
HOST_LIMITS = {
|
||||
"maximum_nodes": 80,
|
||||
"maximum_tool_calls": 40,
|
||||
"maximum_llm_calls": 16,
|
||||
"maximum_runtime_seconds": 600,
|
||||
"maximum_result_chars": 240_000,
|
||||
"maximum_concurrency": 8,
|
||||
}
|
||||
RUN_REFERENCE_FIELDS = {
|
||||
"session_id", "chat_model", "router_model", "vision_model", "transcription_model",
|
||||
"library_slug", "searx_url", "searx_engines", "messages", "attachments",
|
||||
"generation_options", "context_blocks", "target_message_id", "target_message_content", "target_url",
|
||||
"web_search_query", "web_search_queries",
|
||||
}
|
||||
|
||||
|
||||
def _issue(code: str, message: str, node_id: Optional[str] = None, field_path: Optional[str] = None) -> ValidationIssue:
|
||||
return ValidationIssue(code=code, message=message, node_id=node_id, field_path=field_path)
|
||||
|
||||
|
||||
def validate_workflow_graph(raw_graph: Dict[str, Any], registry: NativeToolProvider) -> WorkflowValidationResult:
|
||||
errors: List[ValidationIssue] = []
|
||||
warnings: List[ValidationIssue] = []
|
||||
try:
|
||||
graph = WorkflowGraph.model_validate(raw_graph)
|
||||
except ValidationError as exc:
|
||||
for item in exc.errors():
|
||||
errors.append(_issue("malformed_graph", item["msg"], field_path=".".join(str(p) for p in item["loc"])))
|
||||
return WorkflowValidationResult(valid=False, errors=errors)
|
||||
|
||||
if graph.schema_version != 1:
|
||||
errors.append(_issue("unsupported_schema_version", "Only workflow schema_version 1 is supported.", field_path="schema_version"))
|
||||
|
||||
for name, schema in {**graph.inputs, **graph.outputs}.items():
|
||||
try:
|
||||
validate_schema_definition(schema, f"schema.{name}")
|
||||
except SchemaValidationError as exc:
|
||||
errors.append(_issue("malformed_schema", str(exc), field_path=f"inputs.{name}"))
|
||||
|
||||
node_ids = [node.id for node in graph.nodes]
|
||||
edge_ids = [edge.id for edge in graph.edges]
|
||||
for identifier, values, path in (("node", node_ids, "nodes"), ("edge", edge_ids, "edges")):
|
||||
seen = set()
|
||||
for value in values:
|
||||
if not value:
|
||||
errors.append(_issue(f"empty_{identifier}_id", f"{identifier.title()} IDs cannot be empty.", field_path=path))
|
||||
elif value in seen:
|
||||
errors.append(_issue(f"duplicate_{identifier}_id", f"Duplicate {identifier} ID: {value}", field_path=path))
|
||||
seen.add(value)
|
||||
|
||||
nodes = {node.id: node for node in graph.nodes}
|
||||
input_nodes = [node for node in graph.nodes if node.type == "input"]
|
||||
output_nodes = [node for node in graph.nodes if node.type == "output"]
|
||||
if not input_nodes:
|
||||
errors.append(_issue("missing_input_node", "A workflow must contain an input node."))
|
||||
if not output_nodes:
|
||||
errors.append(_issue("missing_output_node", "A workflow must contain an output node."))
|
||||
|
||||
outgoing: Dict[str, List[Any]] = defaultdict(list)
|
||||
incoming: Dict[str, List[Any]] = defaultdict(list)
|
||||
for edge in graph.edges:
|
||||
if edge.source not in nodes:
|
||||
errors.append(_issue("missing_edge_source", f"Edge source does not exist: {edge.source}", field_path=f"edges.{edge.id}.source"))
|
||||
if edge.target not in nodes:
|
||||
errors.append(_issue("missing_edge_target", f"Edge target does not exist: {edge.target}", field_path=f"edges.{edge.id}.target"))
|
||||
if edge.source in nodes and edge.target in nodes:
|
||||
outgoing[edge.source].append(edge)
|
||||
incoming[edge.target].append(edge)
|
||||
|
||||
indegree = {node_id: len(incoming[node_id]) for node_id in nodes}
|
||||
queue = deque(node_id for node_id, degree in indegree.items() if degree == 0)
|
||||
visited: List[str] = []
|
||||
while queue:
|
||||
node_id = queue.popleft()
|
||||
visited.append(node_id)
|
||||
for edge in outgoing[node_id]:
|
||||
indegree[edge.target] -= 1
|
||||
if indegree[edge.target] == 0:
|
||||
queue.append(edge.target)
|
||||
if len(visited) != len(nodes):
|
||||
errors.append(_issue("cycle", "Workflow schema version 1 must be a DAG; cycles are not allowed."))
|
||||
|
||||
reachable = set()
|
||||
frontier = [node.id for node in input_nodes]
|
||||
while frontier:
|
||||
node_id = frontier.pop()
|
||||
if node_id in reachable:
|
||||
continue
|
||||
reachable.add(node_id)
|
||||
frontier.extend(edge.target for edge in outgoing[node_id])
|
||||
for node in graph.nodes:
|
||||
if node.type not in {"input"} and node.id not in reachable:
|
||||
errors.append(_issue("unreachable_node", f"Node {node.id} is not reachable from an input node.", node.id))
|
||||
|
||||
for node in graph.nodes:
|
||||
if node.type == "tool":
|
||||
tool_name = str(node.config.get("tool") or "")
|
||||
try:
|
||||
tool = registry.get_tool(tool_name)
|
||||
except KeyError:
|
||||
errors.append(_issue("unknown_tool", f"Unknown tool: {tool_name or '(missing)'}", node.id, "config.tool"))
|
||||
else:
|
||||
arguments = node.config.get("arguments", {})
|
||||
if not isinstance(arguments, dict):
|
||||
errors.append(_issue("invalid_tool_arguments", "Tool arguments must be an object.", node.id, "config.arguments"))
|
||||
else:
|
||||
literal_arguments = {
|
||||
key: value for key, value in arguments.items()
|
||||
if not (isinstance(value, dict) and set(value) == {"$ref"})
|
||||
}
|
||||
try:
|
||||
validate_json_schema(literal_arguments, tool.input_schema, partial=True)
|
||||
except SchemaValidationError as exc:
|
||||
errors.append(_issue("invalid_tool_arguments", str(exc), node.id, "config.arguments"))
|
||||
if node.type == "condition":
|
||||
operation = node.config.get("operation")
|
||||
allowed = {"equals", "not_equals", "exists", "greater_than", "less_than", "contains", "array_not_empty", "score_at_least"}
|
||||
if operation not in allowed:
|
||||
errors.append(_issue("invalid_condition", f"Unsupported condition operation: {operation}", node.id, "config.operation"))
|
||||
handles = {edge.source_handle for edge in outgoing[node.id]}
|
||||
if not {"true", "false"}.issubset(handles):
|
||||
errors.append(_issue("invalid_branch", "Condition nodes require both true and false outgoing branches.", node.id))
|
||||
if node.type == "prompt" and not node.config.get("model_source"):
|
||||
errors.append(_issue("missing_model_source", "Prompt nodes require model_source.", node.id, "config.model_source"))
|
||||
|
||||
for field_path, reference in iter_references(node.config, f"nodes.{node.id}.config"):
|
||||
parts = reference.split(".")
|
||||
if parts[0] == "input" and (len(parts) < 2 or parts[1] not in graph.inputs):
|
||||
errors.append(_issue("missing_reference", f"Unknown workflow input reference: {reference}", node.id, field_path))
|
||||
elif parts[0] == "run" and (len(parts) < 2 or parts[1] not in RUN_REFERENCE_FIELDS):
|
||||
errors.append(_issue("missing_reference", f"Unknown run reference: {reference}", node.id, field_path))
|
||||
elif parts[0] == "nodes" and (len(parts) < 3 or parts[1] not in nodes):
|
||||
errors.append(_issue("missing_reference", f"Unknown node reference: {reference}", node.id, field_path))
|
||||
elif parts[0] not in {"input", "run", "nodes"}:
|
||||
errors.append(_issue("missing_reference", f"Invalid reference: {reference}", node.id, field_path))
|
||||
|
||||
limits = graph.limits.model_dump()
|
||||
for key, maximum in HOST_LIMITS.items():
|
||||
value = limits[key]
|
||||
if value < 1 or value > maximum:
|
||||
errors.append(_issue("excessive_limit", f"{key} must be between 1 and {maximum}.", field_path=f"limits.{key}"))
|
||||
if len(graph.nodes) > graph.limits.maximum_nodes:
|
||||
errors.append(_issue("excessive_nodes", "The graph contains more nodes than its maximum_nodes limit.", field_path="nodes"))
|
||||
|
||||
return WorkflowValidationResult(valid=not errors, errors=errors, warnings=warnings)
|
||||
3
backend/agent/workflows/__init__.py
Normal file
3
backend/agent/workflows/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .builtins import BUILTIN_WORKFLOWS, seed_builtin_workflows
|
||||
|
||||
__all__ = ["BUILTIN_WORKFLOWS", "seed_builtin_workflows"]
|
||||
333
backend/agent/workflows/builtins.py
Normal file
333
backend/agent/workflows/builtins.py
Normal file
@@ -0,0 +1,333 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import WorkflowDefinition, WorkflowRevision
|
||||
|
||||
|
||||
LIMITS = {
|
||||
"maximum_nodes": 40,
|
||||
"maximum_tool_calls": 20,
|
||||
"maximum_llm_calls": 8,
|
||||
"maximum_runtime_seconds": 300,
|
||||
"maximum_result_chars": 120000,
|
||||
"maximum_concurrency": 4,
|
||||
}
|
||||
INPUTS = {"prompt": {"type": "string"}, "session_id": {"type": ["string", "null"]}}
|
||||
|
||||
|
||||
def node(node_id: str, node_type: str, x: float, y: float, config: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
||||
return {"id": node_id, "type": node_type, "position": {"x": x, "y": y}, "config": config or {}}
|
||||
|
||||
|
||||
def edge(source: str, target: str, source_handle: str = "output", suffix: str = "") -> Dict[str, Any]:
|
||||
return {
|
||||
"id": f"{source}-{target}{suffix}",
|
||||
"source": source,
|
||||
"source_handle": source_handle,
|
||||
"target": target,
|
||||
"target_handle": "input",
|
||||
}
|
||||
|
||||
|
||||
EVIDENCE_FIRST_SYSTEM_PROMPT = (
|
||||
"Answer the current user request using the supplied retrieved context as the primary evidence. "
|
||||
"If retrieved context conflicts with older chat history, prefer the retrieved context and explain the correction briefly. "
|
||||
"Do not recommend that the user consult external sources when relevant retrieved sources are already present."
|
||||
)
|
||||
CHAT_MEMORY_SYSTEM_PROMPT = (
|
||||
"Answer using the supplied previous-chat context as the primary evidence. "
|
||||
"Treat it as memory of earlier Heimgeist chats, not as fresh external evidence. "
|
||||
"If the retrieved chat context is empty or does not answer the request, say that no matching previous chat was found."
|
||||
)
|
||||
|
||||
|
||||
def chat_arguments(context_blocks: List[Dict[str, str]] | None = None, system_prompt: str = "") -> Dict[str, Any]:
|
||||
return {
|
||||
"model": {"$ref": "run.chat_model"},
|
||||
"messages": {"$ref": "run.messages"},
|
||||
"system_prompt": system_prompt,
|
||||
"context_blocks": context_blocks or [],
|
||||
"attachments": {"$ref": "run.attachments"},
|
||||
"vision_model": {"$ref": "run.vision_model"},
|
||||
"transcription_model": {"$ref": "run.transcription_model"},
|
||||
"generation_options": {"$ref": "run.generation_options"},
|
||||
"stream": True,
|
||||
"reasoning": False,
|
||||
}
|
||||
|
||||
|
||||
def graph(nodes: List[Dict[str, Any]], edges: List[Dict[str, Any]], *, limits: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"inputs": INPUTS,
|
||||
"outputs": {"content": {"type": "string"}},
|
||||
"nodes": nodes,
|
||||
"edges": edges,
|
||||
"limits": {**LIMITS, **(limits or {})},
|
||||
}
|
||||
|
||||
|
||||
DIRECT = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("chat", "tool", 320, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments()}),
|
||||
node("output", "output", 680, 80, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[edge("input", "chat"), edge("chat", "output")],
|
||||
)
|
||||
|
||||
KNOWLEDGE = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("search", "tool", 280, 20, {"tool": "heimgeist.knowledge_search", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "library_slug": {"$ref": "run.library_slug"},
|
||||
"top_k": 6, "context_character_budget": 14000, "embedding_model": None,
|
||||
}}),
|
||||
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.search.output"}])}),
|
||||
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[edge("input", "search"), edge("search", "chat"), edge("chat", "output")],
|
||||
)
|
||||
|
||||
CHAT_MEMORY = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("memory", "tool", 280, 20, {"tool": "heimgeist.chat_memory_search", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "top_k": 6, "context_character_budget": 10000,
|
||||
"mode": "search", "exclude_current_session": True,
|
||||
}}),
|
||||
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.memory.output"}], CHAT_MEMORY_SYSTEM_PROMPT)}),
|
||||
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[edge("input", "memory"), edge("memory", "chat"), edge("chat", "output")],
|
||||
)
|
||||
|
||||
RECENT_CHAT_MEMORY = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("memory", "tool", 280, 20, {"tool": "heimgeist.chat_memory_search", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "top_k": 6, "context_character_budget": 10000,
|
||||
"mode": "recent", "exclude_current_session": True,
|
||||
}}),
|
||||
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.memory.output"}], CHAT_MEMORY_SYSTEM_PROMPT)}),
|
||||
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[edge("input", "memory"), edge("memory", "chat"), edge("chat", "output")],
|
||||
)
|
||||
|
||||
|
||||
def web_graph() -> Dict[str, Any]:
|
||||
return graph(
|
||||
[
|
||||
node("input", "input", 0, 100),
|
||||
node("search", "tool", 300, 20, {"tool": "heimgeist.web_search", "arguments": {
|
||||
"query": {"$ref": "run.web_search_query"}, "queries": {"$ref": "run.web_search_queries"}, "engines": {"$ref": "run.searx_engines"},
|
||||
"maximum_results": 16, "searx_url": {"$ref": "run.searx_url"},
|
||||
}}),
|
||||
node("fetch", "tool", 760, 20, {"tool": "heimgeist.web_fetch", "arguments": {
|
||||
"url": None, "urls": {"$ref": "nodes.search.output.results"}, "maximum_pages": 6,
|
||||
}}),
|
||||
node("rerank", "tool", 1010, 20, {"tool": "heimgeist.web_rerank", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch.output.pages"}, "model": {"$ref": "run.chat_model"},
|
||||
"rerank_model": None, "context_excerpt": "", "maximum_results": 6, "minimum_score": 55,
|
||||
}}),
|
||||
node("chat", "tool", 1260, 100, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.rerank.output"}], EVIDENCE_FIRST_SYSTEM_PROMPT)}),
|
||||
node("output", "output", 1540, 100, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[edge("input", "search"), edge("search", "fetch"), edge("fetch", "rerank"), edge("rerank", "chat"), edge("chat", "output")],
|
||||
)
|
||||
|
||||
|
||||
VISION = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("vision", "tool", 280, 20, {"tool": "heimgeist.vision_analyze", "arguments": {
|
||||
"attachments": {"$ref": "run.attachments"}, "vision_model": {"$ref": "run.vision_model"},
|
||||
"transcription_model": {"$ref": "run.transcription_model"},
|
||||
}}),
|
||||
node("chat", "tool", 620, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.vision.output"}])}),
|
||||
node("output", "output", 960, 80, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[edge("input", "vision"), edge("vision", "chat"), edge("chat", "output")],
|
||||
limits={"maximum_runtime_seconds": 600},
|
||||
)
|
||||
|
||||
KNOWLEDGE_WEB = graph(
|
||||
[
|
||||
node("input", "input", 0, 150),
|
||||
node("knowledge", "tool", 260, 20, {"tool": "heimgeist.knowledge_search", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "library_slug": {"$ref": "run.library_slug"}, "top_k": 5,
|
||||
"context_character_budget": 10000, "embedding_model": None,
|
||||
}}),
|
||||
node("search", "tool", 520, 240, {"tool": "heimgeist.web_search", "arguments": {
|
||||
"query": {"$ref": "run.web_search_query"}, "queries": {"$ref": "run.web_search_queries"}, "engines": {"$ref": "run.searx_engines"},
|
||||
"maximum_results": 12, "searx_url": {"$ref": "run.searx_url"},
|
||||
}}),
|
||||
node("fetch", "tool", 780, 240, {"tool": "heimgeist.web_fetch", "arguments": {"url": None, "urls": {"$ref": "nodes.search.output.results"}, "maximum_pages": 5}}),
|
||||
node("rerank", "tool", 1040, 240, {"tool": "heimgeist.web_rerank", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch.output.pages"}, "model": {"$ref": "run.chat_model"},
|
||||
"rerank_model": None, "context_excerpt": "", "maximum_results": 5, "minimum_score": 50,
|
||||
}}),
|
||||
node("merge", "merge", 1300, 130, {"values": [{"$ref": "nodes.knowledge.output"}, {"$ref": "nodes.rerank.output"}], "deduplicate_by": "url"}),
|
||||
node("limit", "limit", 1520, 130, {"value": {"$ref": "nodes.merge.output"}, "maximum_chars": 22000}),
|
||||
node("chat", "tool", 1760, 130, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.limit.output"}], EVIDENCE_FIRST_SYSTEM_PROMPT)}),
|
||||
node("output", "output", 2040, 130, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[
|
||||
edge("input", "knowledge"), edge("input", "search"), edge("search", "fetch"), edge("fetch", "rerank"),
|
||||
edge("knowledge", "merge"), edge("rerank", "merge"), edge("merge", "limit"), edge("limit", "chat"), edge("chat", "output"),
|
||||
],
|
||||
)
|
||||
|
||||
REMEMBER = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("save", "tool", 300, 80, {"tool": "heimgeist.save_message_to_knowledge", "arguments": {
|
||||
"message_id": {"$ref": "run.target_message_id"}, "library_slug": {"$ref": "run.library_slug"}, "title": None, "edited_content": {"$ref": "run.target_message_content"},
|
||||
}}),
|
||||
node("confirmed", "condition", 570, 80, {"value": {"$ref": "nodes.save.output.confirmed"}, "operation": "equals", "compare_to": True}),
|
||||
node("saved", "template", 830, 20, {"template": "Saved the selected message to knowledge."}),
|
||||
node("rejected", "template", 830, 150, {"template": "The knowledge save was cancelled."}),
|
||||
node("response", "merge", 1080, 80, {"values": [{"$ref": "nodes.saved.output"}, {"$ref": "nodes.rejected.output"}], "allow_missing": True}),
|
||||
node("output", "output", 1320, 80, {"value": {"content": {"$ref": "nodes.response.output.context_block"}, "sources": [], "usage": {}}}),
|
||||
],
|
||||
[
|
||||
edge("input", "save"), edge("save", "confirmed"),
|
||||
edge("confirmed", "saved", "true"), edge("confirmed", "rejected", "false"),
|
||||
edge("saved", "response"), edge("rejected", "response"), edge("response", "output"),
|
||||
],
|
||||
)
|
||||
|
||||
SAVE_SOURCE = graph(
|
||||
[
|
||||
node("input", "input", 0, 80),
|
||||
node("save", "tool", 300, 80, {"tool": "heimgeist.save_website_to_knowledge", "arguments": {
|
||||
"url": {"$ref": "run.target_url"}, "library_slug": {"$ref": "run.library_slug"}, "title": None,
|
||||
}}),
|
||||
node("confirmed", "condition", 570, 80, {"value": {"$ref": "nodes.save.output.confirmed"}, "operation": "equals", "compare_to": True}),
|
||||
node("saved", "template", 830, 20, {"template": "Saved the website snapshot to knowledge."}),
|
||||
node("rejected", "template", 830, 150, {"template": "The website save was cancelled."}),
|
||||
node("response", "merge", 1080, 80, {"values": [{"$ref": "nodes.saved.output"}, {"$ref": "nodes.rejected.output"}], "allow_missing": True}),
|
||||
node("output", "output", 1320, 80, {"value": {"content": {"$ref": "nodes.response.output.context_block"}, "sources": [], "usage": {}}}),
|
||||
],
|
||||
[
|
||||
edge("input", "save"), edge("save", "confirmed"),
|
||||
edge("confirmed", "saved", "true"), edge("confirmed", "rejected", "false"),
|
||||
edge("saved", "response"), edge("rejected", "response"), edge("response", "output"),
|
||||
],
|
||||
)
|
||||
|
||||
RESEARCH = graph(
|
||||
[
|
||||
node("input", "input", 0, 180),
|
||||
node("search1", "tool", 710, 80, {"tool": "heimgeist.web_search", "arguments": {
|
||||
"query": {"$ref": "run.web_search_query"}, "queries": {"$ref": "run.web_search_queries"}, "engines": {"$ref": "run.searx_engines"},
|
||||
"maximum_results": 18, "searx_url": {"$ref": "run.searx_url"},
|
||||
}}),
|
||||
node("fetch1", "tool", 950, 80, {"tool": "heimgeist.web_fetch", "arguments": {"url": None, "urls": {"$ref": "nodes.search1.output.results"}, "maximum_pages": 7}}),
|
||||
node("rank1", "tool", 1190, 80, {"tool": "heimgeist.web_rerank", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch1.output.pages"}, "model": {"$ref": "run.chat_model"},
|
||||
"rerank_model": None, "context_excerpt": "", "maximum_results": 6, "minimum_score": 50,
|
||||
}}),
|
||||
node("evaluate", "prompt", 1430, 80, {
|
||||
"model_source": "chat_model",
|
||||
"system_template": (
|
||||
"Judge whether the retrieved evidence directly answers the standalone request. "
|
||||
"Return JSON only. Set sufficient=true only when the evidence contains relevant sourced facts for the main answer. "
|
||||
"If sufficient=true, follow_up_query must be an empty string. "
|
||||
"If sufficient=false, follow_up_query must be one concise web search query for the missing information, not an explanation."
|
||||
),
|
||||
"user_template": "Original user message: {{input.prompt}}\nResolved request and router inputs: {{nodes.input.output}}\nEvidence: {{nodes.rank1.output.context_block}}",
|
||||
"output_mode": "json", "json_schema": {"type": "object", "properties": {"sufficient": {"type": "boolean"}, "follow_up_query": {"type": "string"}}, "required": ["sufficient", "follow_up_query"], "additionalProperties": False},
|
||||
"temperature": 0.1, "json_repair": True,
|
||||
}),
|
||||
node("sufficient", "condition", 1690, 80, {"value": {"$ref": "nodes.evaluate.output.sufficient"}, "operation": "equals", "compare_to": True}),
|
||||
node("queries2", "select", 1910, 220, {"value": {"$ref": "nodes.evaluate.output.follow_up_query"}}),
|
||||
node("search2", "tool", 2130, 220, {"tool": "heimgeist.web_search", "arguments": {
|
||||
"query": {"$ref": "nodes.queries2.output"}, "queries": [], "engines": {"$ref": "run.searx_engines"},
|
||||
"maximum_results": 10, "searx_url": {"$ref": "run.searx_url"},
|
||||
}}),
|
||||
node("fetch2", "tool", 2350, 220, {"tool": "heimgeist.web_fetch", "arguments": {"url": None, "urls": {"$ref": "nodes.search2.output.results"}, "maximum_pages": 4}}),
|
||||
node("rank2", "tool", 2570, 220, {"tool": "heimgeist.web_rerank", "arguments": {
|
||||
"prompt": {"$ref": "input.prompt"}, "pages": {"$ref": "nodes.fetch2.output.pages"}, "model": {"$ref": "run.chat_model"},
|
||||
"rerank_model": None, "context_excerpt": "", "maximum_results": 4, "minimum_score": 45,
|
||||
}}),
|
||||
node("empty2", "template", 1910, -80, {"template": "", "values": {}}),
|
||||
node("merge", "merge", 2820, 80, {"values": [{"$ref": "nodes.rank1.output"}, {"$ref": "nodes.rank2.output"}], "deduplicate_by": "url", "allow_missing": True}),
|
||||
node("limit", "limit", 3050, 80, {"value": {"$ref": "nodes.merge.output"}, "maximum_chars": 28000}),
|
||||
node("chat", "tool", 3280, 80, {"tool": "heimgeist.chat", "arguments": chat_arguments([{"$ref": "nodes.limit.output"}], EVIDENCE_FIRST_SYSTEM_PROMPT)}),
|
||||
node("output", "output", 3520, 80, {"value": {"$ref": "nodes.chat.output"}}),
|
||||
],
|
||||
[
|
||||
edge("input", "search1"), edge("search1", "fetch1"), edge("fetch1", "rank1"),
|
||||
edge("rank1", "evaluate"), edge("evaluate", "sufficient"), edge("sufficient", "empty2", "true", "-true"), edge("sufficient", "queries2", "false", "-false"),
|
||||
edge("queries2", "search2"), edge("search2", "fetch2"), edge("fetch2", "rank2"), edge("rank1", "merge"), edge("rank2", "merge"), edge("empty2", "merge"),
|
||||
edge("merge", "limit"), edge("limit", "chat"), edge("chat", "output"),
|
||||
],
|
||||
limits={"maximum_tool_calls": 24, "maximum_llm_calls": 10, "maximum_runtime_seconds": 420},
|
||||
)
|
||||
|
||||
BUILTIN_WORKFLOWS = [
|
||||
{"slug": "input-output", "name": "Input -> Output", "description": "Normal Heimgeist chat with optional compatibility context.", "routing_description": "Choose only when no external tool is needed: conversational replies, writing, editing, reasoning, brainstorming, explanation, or stable knowledge the model can answer without retrieval. Do not choose when the standalone request needs facts outside the conversation/model context, source grounding, live local knowledge retrieval, attachment analysis, or knowledge-saving actions.", "routing_examples": ["Explain this concept", "Draft a reply", "Rewrite this paragraph", "What do you mean by that?"], "estimated_cost_class": "low", "required_capabilities": ["chat"], "graph": DIRECT},
|
||||
{"slug": "chat-memory-answer", "name": "Chat Memory Answer", "description": "Search previous Heimgeist chats and answer from matching turns.", "routing_description": "Choose when the standalone request asks Heimgeist to use past chats, earlier conversations, remembered discussion context, previous decisions, or topics discussed before. This workflow searches previous chat turns before answering. Do not choose for general factual questions that merely resemble something discussed before; choose Web Answer, Knowledge Answer, or direct chat based on the requested evidence.", "routing_examples": ["What music did we talk about before?", "What did we decide earlier about packaging?", "Use our previous chat about Ollama settings"], "estimated_cost_class": "medium", "required_capabilities": ["chat_memory", "chat"], "graph": CHAT_MEMORY},
|
||||
{"slug": "recent-chat-memory-answer", "name": "Recent Chat Memory Answer", "description": "Answer from the most recent previous Heimgeist chat.", "routing_description": "Choose when the standalone request specifically asks about the last, previous, latest, or most recent earlier Heimgeist chat or conversation. This workflow retrieves the most recent previous chat turn instead of doing a relevance search.", "routing_examples": ["What was the last conversation about?", "Worum ging es im letzten Gespräch?", "Continue from the previous chat"], "estimated_cost_class": "medium", "required_capabilities": ["chat_memory", "chat"], "graph": RECENT_CHAT_MEMORY},
|
||||
{"slug": "knowledge-answer", "name": "Knowledge Answer", "description": "Answer from local knowledge.", "routing_description": "Choose when the standalone request asks about or should be grounded in Heimgeist's local Knowledge store, and current web evidence is not required. This workflow retrieves local knowledge before answering.", "routing_examples": ["What do my notes say about this?", "Summarize the saved knowledge entry"], "estimated_cost_class": "medium", "required_capabilities": ["rag"], "graph": KNOWLEDGE},
|
||||
{"slug": "web-answer", "name": "Web Answer", "description": "Search, fetch, rank, and answer from current web sources.", "routing_description": "Choose when the standalone request needs web evidence and can likely be answered by one bounded search/fetch/rank pass: facts outside the conversation/model context, source-grounded lookup, public information that may have changed, or a follow-up that inherits such a web-grounded topic. This is the default web workflow for direct answer requests. Prefer it over Research unless the request itself requires investigation, comparison, validation, or broad synthesis.", "routing_examples": ["Look this up online", "What is the current status?", "Find the latest information about this topic", "What happened with that since then?"], "estimated_cost_class": "medium", "required_capabilities": ["web"], "graph": web_graph()},
|
||||
{"slug": "vision-answer", "name": "Vision Answer", "description": "Analyze attachments and answer with a vision model.", "routing_description": "Use when image or document attachments must be analyzed.", "routing_examples": ["What is shown in this image?"], "estimated_cost_class": "medium", "required_capabilities": ["vision"], "graph": VISION},
|
||||
{"slug": "knowledge-web-answer", "name": "Knowledge + Web Answer", "description": "Combine local knowledge and current web evidence.", "routing_description": "Choose when both capabilities are needed: Heimgeist's local Knowledge store is relevant, and the standalone request also requires web evidence or updated external facts.", "routing_examples": ["Compare my notes with the latest information", "Check my saved source against current web evidence"], "estimated_cost_class": "high", "required_capabilities": ["rag", "web"], "graph": KNOWLEDGE_WEB},
|
||||
{"slug": "remember-this", "name": "Remember This", "description": "Save a selected chat message to knowledge.", "routing_description": "Use only when the user explicitly asks to remember or save a chat message.", "routing_examples": ["Remember this answer"], "estimated_cost_class": "low", "required_capabilities": ["knowledge_write"], "graph": REMEMBER},
|
||||
{"slug": "save-source", "name": "Save Source", "description": "Save a website snapshot to knowledge.", "routing_description": "Use when the user explicitly asks to save a URL as a knowledge source.", "routing_examples": ["Save this website to Knowledge"], "estimated_cost_class": "low", "required_capabilities": ["web", "knowledge_write"], "graph": SAVE_SOURCE},
|
||||
{"slug": "research", "name": "Research", "description": "Bounded two-round evidence research with source validation.", "routing_description": "Choose only when the standalone request needs an investigation rather than a direct lookup: compare sources, resolve uncertainty, validate claims, synthesize several angles, or perform a second search if first-pass evidence is insufficient. Do not choose this solely because web evidence is needed, because the topic is important, or because information is current. Choose Web Answer for direct web-grounded questions.", "routing_examples": ["Research the competing explanations and cite sources", "Compare the strongest evidence for both claims", "Investigate this topic in depth"], "estimated_cost_class": "high", "required_capabilities": ["web", "chat"], "graph": RESEARCH},
|
||||
]
|
||||
|
||||
|
||||
def _checksum(graph_value: Dict[str, Any]) -> str:
|
||||
canonical = json.dumps(graph_value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def seed_builtin_workflows(session: Session) -> None:
|
||||
for item in BUILTIN_WORKFLOWS:
|
||||
workflow = session.query(WorkflowDefinition).filter(WorkflowDefinition.slug == item["slug"]).first()
|
||||
if workflow is None:
|
||||
workflow = WorkflowDefinition(
|
||||
slug=item["slug"], name=item["name"], description=item["description"], built_in=True, enabled=True,
|
||||
routing_description=item["routing_description"], routing_examples_json=json.dumps(item["routing_examples"]),
|
||||
estimated_cost_class=item["estimated_cost_class"], required_capabilities_json=json.dumps(item["required_capabilities"]),
|
||||
)
|
||||
session.add(workflow)
|
||||
session.flush()
|
||||
else:
|
||||
workflow.name = item["name"]
|
||||
workflow.description = item["description"]
|
||||
workflow.built_in = True
|
||||
workflow.routing_description = item["routing_description"]
|
||||
workflow.routing_examples_json = json.dumps(item["routing_examples"])
|
||||
workflow.estimated_cost_class = item["estimated_cost_class"]
|
||||
workflow.required_capabilities_json = json.dumps(item["required_capabilities"])
|
||||
workflow.updated_at = datetime.utcnow()
|
||||
checksum = _checksum(item["graph"])
|
||||
revision = session.query(WorkflowRevision).filter(
|
||||
WorkflowRevision.workflow_id == workflow.id,
|
||||
WorkflowRevision.checksum == checksum,
|
||||
).first()
|
||||
if revision is None:
|
||||
latest = session.query(WorkflowRevision).filter(WorkflowRevision.workflow_id == workflow.id).order_by(WorkflowRevision.version.desc()).first()
|
||||
revision = WorkflowRevision(
|
||||
workflow_id=workflow.id,
|
||||
version=(latest.version + 1) if latest else 1,
|
||||
graph_json=json.dumps(item["graph"], ensure_ascii=False),
|
||||
created_by="system",
|
||||
trusted=True,
|
||||
checksum=checksum,
|
||||
)
|
||||
session.add(revision)
|
||||
session.flush()
|
||||
workflow.current_revision_id = revision.id
|
||||
session.commit()
|
||||
1
backend/agent/workflows/research.py
Normal file
1
backend/agent/workflows/research.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Research workflow constants live in builtins.py to keep seeded graphs versioned together."""
|
||||
206
backend/app_settings.py
Normal file
206
backend/app_settings.py
Normal file
@@ -0,0 +1,206 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
APP_NAME = "Heimgeist"
|
||||
DEFAULT_BACKEND_API_URL = "http://127.0.0.1:8000"
|
||||
DEFAULT_OLLAMA_API_URL = "http://127.0.0.1:11434"
|
||||
DEFAULT_EMBED_MODEL = "nomic-embed-text:latest"
|
||||
DEFAULT_RERANK_MODEL = DEFAULT_EMBED_MODEL
|
||||
DEFAULT_ENRICHMENT_MODEL = "qwen3:4b"
|
||||
DEFAULT_TRANSCRIPTION_MODEL = "base"
|
||||
DEFAULT_WORKFLOW_ROUTER_MODEL = ""
|
||||
DEFAULT_WORKFLOW_SELECTION_MODE = "auto"
|
||||
DEFAULT_AUTO_DEEP_ENRICHMENT = True
|
||||
BGE_EMBED_MODEL = "bge-m3:latest"
|
||||
DEFAULT_SETTINGS: Dict[str, Any] = {
|
||||
"backendApiUrl": DEFAULT_BACKEND_API_URL,
|
||||
"ollamaApiUrl": DEFAULT_OLLAMA_API_URL,
|
||||
"chatModel": "llama3",
|
||||
"visionModel": "",
|
||||
"embedModel": DEFAULT_EMBED_MODEL,
|
||||
"rerankModel": DEFAULT_RERANK_MODEL,
|
||||
"enrichmentModel": DEFAULT_ENRICHMENT_MODEL,
|
||||
"transcriptionModel": DEFAULT_TRANSCRIPTION_MODEL,
|
||||
"workflowRouterModel": DEFAULT_WORKFLOW_ROUTER_MODEL,
|
||||
"workflowSelectionMode": DEFAULT_WORKFLOW_SELECTION_MODE,
|
||||
"autoDeepEnrichment": DEFAULT_AUTO_DEEP_ENRICHMENT,
|
||||
}
|
||||
|
||||
|
||||
def _default_settings_dir() -> Path:
|
||||
if sys.platform == "darwin":
|
||||
return Path.home() / "Library" / "Application Support" / APP_NAME
|
||||
if os.name == "nt":
|
||||
appdata = os.getenv("APPDATA")
|
||||
if appdata:
|
||||
return Path(appdata) / APP_NAME
|
||||
return Path.home() / "AppData" / "Roaming" / APP_NAME
|
||||
return Path(os.getenv("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / APP_NAME
|
||||
|
||||
|
||||
def settings_path() -> Path:
|
||||
custom_path = os.getenv("HEIMGEIST_SETTINGS_FILE")
|
||||
if custom_path:
|
||||
return Path(custom_path).expanduser()
|
||||
return _default_settings_dir() / "settings.json"
|
||||
|
||||
|
||||
def _looks_like_ollama_url(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
|
||||
trimmed = value.strip()
|
||||
if not trimmed:
|
||||
return False
|
||||
|
||||
if ":11434" in trimmed:
|
||||
return True
|
||||
|
||||
return trimmed.rstrip("/").endswith("/api")
|
||||
|
||||
|
||||
def _normalize_url(value: Any, fallback: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
return fallback
|
||||
|
||||
trimmed = value.strip().rstrip("/")
|
||||
return trimmed or fallback
|
||||
|
||||
|
||||
def normalize_embed_model(value: Any) -> str:
|
||||
if not isinstance(value, str):
|
||||
return DEFAULT_EMBED_MODEL
|
||||
|
||||
trimmed = value.strip()
|
||||
if not trimmed:
|
||||
return DEFAULT_EMBED_MODEL
|
||||
|
||||
lowered = trimmed.lower()
|
||||
if lowered in {"bge", "bge-m3", BGE_EMBED_MODEL}:
|
||||
return BGE_EMBED_MODEL
|
||||
if lowered in {"nomic", "nomic-embed-text", DEFAULT_EMBED_MODEL}:
|
||||
return DEFAULT_EMBED_MODEL
|
||||
return trimmed
|
||||
|
||||
|
||||
def normalize_rerank_model(value: Any) -> str:
|
||||
return normalize_embed_model(value)
|
||||
|
||||
|
||||
def normalize_model_name(value: Any, fallback: str = "") -> str:
|
||||
if not isinstance(value, str):
|
||||
return fallback
|
||||
trimmed = value.strip()
|
||||
return trimmed or fallback
|
||||
|
||||
|
||||
def normalize_workflow_selection_mode(value: Any) -> str:
|
||||
if isinstance(value, str) and value.strip().lower() == "manual":
|
||||
return "manual"
|
||||
return DEFAULT_WORKFLOW_SELECTION_MODE
|
||||
|
||||
|
||||
def normalize_transcription_model(value: Any) -> str:
|
||||
return normalize_model_name(value, DEFAULT_TRANSCRIPTION_MODEL)
|
||||
|
||||
|
||||
def normalize_boolean(value: Any, default: bool = False) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {"true", "1", "yes", "on"}:
|
||||
return True
|
||||
if normalized in {"false", "0", "no", "off", ""}:
|
||||
return False
|
||||
return default
|
||||
|
||||
|
||||
def load_app_settings() -> Dict[str, Any]:
|
||||
path = settings_path()
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
raw = {}
|
||||
except Exception:
|
||||
raw = {}
|
||||
|
||||
if not isinstance(raw, dict):
|
||||
raw = {}
|
||||
|
||||
settings = {**DEFAULT_SETTINGS, **raw}
|
||||
if "backendApiUrl" not in raw and isinstance(raw.get("ollamaApiUrl"), str):
|
||||
if _looks_like_ollama_url(raw["ollamaApiUrl"]):
|
||||
settings["backendApiUrl"] = DEFAULT_BACKEND_API_URL
|
||||
settings["ollamaApiUrl"] = _normalize_url(raw["ollamaApiUrl"], DEFAULT_OLLAMA_API_URL)
|
||||
else:
|
||||
settings["backendApiUrl"] = _normalize_url(raw["ollamaApiUrl"], DEFAULT_BACKEND_API_URL)
|
||||
settings["ollamaApiUrl"] = DEFAULT_OLLAMA_API_URL
|
||||
else:
|
||||
settings["backendApiUrl"] = _normalize_url(settings.get("backendApiUrl"), DEFAULT_BACKEND_API_URL)
|
||||
settings["ollamaApiUrl"] = _normalize_url(settings.get("ollamaApiUrl"), DEFAULT_OLLAMA_API_URL)
|
||||
if "rerankModel" not in raw:
|
||||
settings["rerankModel"] = settings.get("embedModel")
|
||||
if "visionModel" not in raw:
|
||||
settings["visionModel"] = settings.get("chatModel", "")
|
||||
settings["embedModel"] = normalize_embed_model(settings.get("embedModel"))
|
||||
settings["rerankModel"] = normalize_rerank_model(settings.get("rerankModel"))
|
||||
settings["enrichmentModel"] = normalize_model_name(
|
||||
settings.get("enrichmentModel"),
|
||||
DEFAULT_ENRICHMENT_MODEL,
|
||||
)
|
||||
settings["chatModel"] = normalize_model_name(settings.get("chatModel"))
|
||||
settings["visionModel"] = normalize_model_name(settings.get("visionModel"))
|
||||
settings["transcriptionModel"] = normalize_transcription_model(settings.get("transcriptionModel"))
|
||||
settings["workflowRouterModel"] = normalize_model_name(settings.get("workflowRouterModel"))
|
||||
settings["workflowSelectionMode"] = normalize_workflow_selection_mode(settings.get("workflowSelectionMode"))
|
||||
settings["autoDeepEnrichment"] = normalize_boolean(
|
||||
settings.get("autoDeepEnrichment"),
|
||||
DEFAULT_AUTO_DEEP_ENRICHMENT,
|
||||
)
|
||||
|
||||
return settings
|
||||
|
||||
|
||||
def get_ollama_api_url() -> str:
|
||||
settings = load_app_settings()
|
||||
return _normalize_url(settings.get("ollamaApiUrl"), DEFAULT_OLLAMA_API_URL)
|
||||
|
||||
|
||||
def get_embed_model_preference() -> str:
|
||||
settings = load_app_settings()
|
||||
return normalize_embed_model(settings.get("embedModel"))
|
||||
|
||||
|
||||
def get_rerank_model_preference() -> str:
|
||||
settings = load_app_settings()
|
||||
return normalize_rerank_model(settings.get("rerankModel"))
|
||||
|
||||
|
||||
def get_enrichment_model_preference() -> str:
|
||||
settings = load_app_settings()
|
||||
return normalize_model_name(settings.get("enrichmentModel"), DEFAULT_ENRICHMENT_MODEL)
|
||||
|
||||
|
||||
def get_transcription_model_preference() -> str:
|
||||
settings = load_app_settings()
|
||||
return normalize_transcription_model(settings.get("transcriptionModel"))
|
||||
|
||||
|
||||
def get_workflow_router_model_preference() -> str:
|
||||
settings = load_app_settings()
|
||||
return normalize_model_name(settings.get("workflowRouterModel"))
|
||||
|
||||
|
||||
def get_auto_deep_enrichment_preference() -> bool:
|
||||
settings = load_app_settings()
|
||||
return normalize_boolean(
|
||||
settings.get("autoDeepEnrichment"),
|
||||
DEFAULT_AUTO_DEEP_ENRICHMENT,
|
||||
)
|
||||
665
backend/chat_memory.py
Normal file
665
backend/chat_memory.py
Normal file
@@ -0,0 +1,665 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import models
|
||||
|
||||
|
||||
DEFAULT_MEMORY_TOP_K = 4
|
||||
DEFAULT_MEMORY_CONTEXT_CHARS = 3600
|
||||
_TOKEN_RE = re.compile(r"[\w][\w'_-]*", re.UNICODE)
|
||||
_THINK_RE = re.compile(r"<think(?:ing)?>.*?</think(?:ing)?>", re.IGNORECASE | re.DOTALL)
|
||||
|
||||
|
||||
def ensure_chat_memory_schema(engine) -> None:
|
||||
"""Create the lightweight chat memory tables used for past-chat retrieval."""
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chat_memory_turns (
|
||||
turn_key TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
session_name TEXT NOT NULL DEFAULT '',
|
||||
user_message_id TEXT NOT NULL,
|
||||
assistant_message_id TEXT NOT NULL,
|
||||
user_message_row_id INTEGER NOT NULL,
|
||||
assistant_message_row_id INTEGER NOT NULL,
|
||||
user_content TEXT NOT NULL,
|
||||
assistant_content TEXT NOT NULL,
|
||||
attachment_summary TEXT NOT NULL DEFAULT '',
|
||||
search_text TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
))
|
||||
conn.execute(text(
|
||||
"CREATE INDEX IF NOT EXISTS ix_chat_memory_turns_session_id "
|
||||
"ON chat_memory_turns (session_id)"
|
||||
))
|
||||
conn.execute(text(
|
||||
"CREATE INDEX IF NOT EXISTS ix_chat_memory_turns_assistant_row "
|
||||
"ON chat_memory_turns (assistant_message_row_id)"
|
||||
))
|
||||
try:
|
||||
conn.execute(text(
|
||||
"""
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS chat_memory_turns_fts USING fts5(
|
||||
turn_key UNINDEXED,
|
||||
session_id UNINDEXED,
|
||||
session_name,
|
||||
user_content,
|
||||
assistant_content,
|
||||
attachment_summary,
|
||||
search_text,
|
||||
tokenize = 'unicode61'
|
||||
)
|
||||
"""
|
||||
))
|
||||
except Exception as exc:
|
||||
print("[chat-memory] FTS index unavailable:", exc)
|
||||
|
||||
|
||||
def _ensure_schema_for_session(db: Session) -> None:
|
||||
try:
|
||||
ensure_chat_memory_schema(db.get_bind())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _clean_content(value: Any, limit: int = 12_000) -> str:
|
||||
text_value = _THINK_RE.sub("", str(value or ""))
|
||||
text_value = re.sub(r"\s+", " ", text_value).strip()
|
||||
if len(text_value) > limit:
|
||||
return text_value[:limit].rstrip() + "..."
|
||||
return text_value
|
||||
|
||||
|
||||
def _attachment_summary(raw_value: Any) -> str:
|
||||
try:
|
||||
items = json.loads(raw_value or "[]") if isinstance(raw_value, str) else (raw_value or [])
|
||||
except Exception:
|
||||
return ""
|
||||
labels: List[str] = []
|
||||
iterable = items if isinstance(items, list) else []
|
||||
for item in iterable:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
name = str(item.get("name") or item.get("source_path") or "").strip()
|
||||
if name:
|
||||
labels.append(name[:160])
|
||||
return ", ".join(labels[:8])
|
||||
|
||||
|
||||
def _is_memory_only_source_value(raw_value: Any) -> bool:
|
||||
try:
|
||||
sources = json.loads(raw_value or "[]")
|
||||
except Exception:
|
||||
return False
|
||||
if not isinstance(sources, list) or not sources:
|
||||
return False
|
||||
for source in sources:
|
||||
if not isinstance(source, dict) or source.get("type") != "chat_memory":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_memory_only_response(row: models.ChatMessage) -> bool:
|
||||
return _is_memory_only_source_value(getattr(row, "sources_json", None))
|
||||
|
||||
|
||||
def _completed_turns(
|
||||
session: models.ChatSession,
|
||||
rows: Sequence[models.ChatMessage],
|
||||
*,
|
||||
skip_memory_only: bool = True,
|
||||
) -> List[Dict[str, Any]]:
|
||||
turns: List[Dict[str, Any]] = []
|
||||
pending_user: Optional[models.ChatMessage] = None
|
||||
session_title = _clean_content(session.name, limit=200) or "New Chat"
|
||||
for row in rows:
|
||||
if row.role == "user":
|
||||
pending_user = row
|
||||
continue
|
||||
if row.role != "assistant" or pending_user is None:
|
||||
continue
|
||||
if skip_memory_only and _is_memory_only_response(row):
|
||||
pending_user = None
|
||||
continue
|
||||
|
||||
user_content = _clean_content(pending_user.content)
|
||||
assistant_content = _clean_content(row.content)
|
||||
if not user_content or not assistant_content:
|
||||
pending_user = None
|
||||
continue
|
||||
|
||||
attachments = _attachment_summary(getattr(pending_user, "attachments_json", None))
|
||||
created_at = row.created_at.isoformat() if row.created_at else datetime.utcnow().isoformat()
|
||||
turn_key = f"{pending_user.message_id}:{row.message_id}"
|
||||
search_text = "\n".join(part for part in (
|
||||
session_title,
|
||||
attachments,
|
||||
f"User: {user_content}",
|
||||
f"Assistant: {assistant_content}",
|
||||
) if part.strip())
|
||||
turns.append({
|
||||
"turn_key": turn_key,
|
||||
"session_id": session.session_id,
|
||||
"session_name": session_title,
|
||||
"user_message_id": pending_user.message_id,
|
||||
"assistant_message_id": row.message_id,
|
||||
"user_message_row_id": pending_user.id,
|
||||
"assistant_message_row_id": row.id,
|
||||
"user_content": user_content,
|
||||
"assistant_content": assistant_content,
|
||||
"attachment_summary": attachments,
|
||||
"search_text": search_text,
|
||||
"created_at": created_at,
|
||||
"updated_at": datetime.utcnow().isoformat(),
|
||||
})
|
||||
pending_user = None
|
||||
return turns
|
||||
|
||||
|
||||
def _delete_fts_rows(db: Session, keys: Sequence[str]) -> None:
|
||||
if not keys:
|
||||
return
|
||||
try:
|
||||
for turn_key in keys:
|
||||
db.execute(text("DELETE FROM chat_memory_turns_fts WHERE turn_key = :turn_key"), {"turn_key": turn_key})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _insert_turn(db: Session, turn: Dict[str, Any]) -> None:
|
||||
db.execute(text(
|
||||
"""
|
||||
INSERT OR REPLACE INTO chat_memory_turns (
|
||||
turn_key, session_id, session_name, user_message_id, assistant_message_id,
|
||||
user_message_row_id, assistant_message_row_id, user_content, assistant_content,
|
||||
attachment_summary, search_text, created_at, updated_at
|
||||
) VALUES (
|
||||
:turn_key, :session_id, :session_name, :user_message_id, :assistant_message_id,
|
||||
:user_message_row_id, :assistant_message_row_id, :user_content, :assistant_content,
|
||||
:attachment_summary, :search_text, :created_at, :updated_at
|
||||
)
|
||||
"""
|
||||
), turn)
|
||||
_delete_fts_rows(db, [turn["turn_key"]])
|
||||
try:
|
||||
db.execute(text(
|
||||
"""
|
||||
INSERT INTO chat_memory_turns_fts (
|
||||
turn_key, session_id, session_name, user_content, assistant_content,
|
||||
attachment_summary, search_text
|
||||
) VALUES (
|
||||
:turn_key, :session_id, :session_name, :user_content, :assistant_content,
|
||||
:attachment_summary, :search_text
|
||||
)
|
||||
"""
|
||||
), turn)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def delete_chat_memory_for_session(db: Session, session_id: str, *, commit: bool = True) -> None:
|
||||
_ensure_schema_for_session(db)
|
||||
keys = [
|
||||
row[0]
|
||||
for row in db.execute(
|
||||
text("SELECT turn_key FROM chat_memory_turns WHERE session_id = :session_id"),
|
||||
{"session_id": session_id},
|
||||
).fetchall()
|
||||
]
|
||||
_delete_fts_rows(db, keys)
|
||||
db.execute(text("DELETE FROM chat_memory_turns WHERE session_id = :session_id"), {"session_id": session_id})
|
||||
if commit:
|
||||
db.commit()
|
||||
|
||||
|
||||
def sync_chat_memory_for_session(db: Session, session_id: str, *, commit: bool = True) -> int:
|
||||
_ensure_schema_for_session(db)
|
||||
session = db.query(models.ChatSession).filter(models.ChatSession.session_id == session_id).first()
|
||||
if session is None:
|
||||
delete_chat_memory_for_session(db, session_id, commit=commit)
|
||||
return 0
|
||||
|
||||
rows = (
|
||||
db.query(models.ChatMessage)
|
||||
.filter(models.ChatMessage.session_pk == session.id)
|
||||
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
|
||||
.all()
|
||||
)
|
||||
turns = _completed_turns(session, rows)
|
||||
delete_chat_memory_for_session(db, session_id, commit=False)
|
||||
for turn in turns:
|
||||
_insert_turn(db, turn)
|
||||
if commit:
|
||||
db.commit()
|
||||
return len(turns)
|
||||
|
||||
|
||||
def sync_all_chat_memory(db: Session, *, commit: bool = True) -> int:
|
||||
_ensure_schema_for_session(db)
|
||||
try:
|
||||
db.execute(text("DELETE FROM chat_memory_turns_fts"))
|
||||
except Exception:
|
||||
pass
|
||||
db.execute(text("DELETE FROM chat_memory_turns"))
|
||||
count = 0
|
||||
sessions = db.query(models.ChatSession).order_by(models.ChatSession.id.asc()).all()
|
||||
for session in sessions:
|
||||
rows = (
|
||||
db.query(models.ChatMessage)
|
||||
.filter(models.ChatMessage.session_pk == session.id)
|
||||
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
|
||||
.all()
|
||||
)
|
||||
for turn in _completed_turns(session, rows):
|
||||
_insert_turn(db, turn)
|
||||
count += 1
|
||||
if commit:
|
||||
db.commit()
|
||||
return count
|
||||
|
||||
|
||||
def safe_backfill_chat_memory(db_factory) -> None:
|
||||
db = db_factory()
|
||||
try:
|
||||
count = sync_all_chat_memory(db)
|
||||
print(f"[chat-memory] indexed {count} completed chat turns")
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
print("[chat-memory] backfill failed:", exc)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def safe_sync_chat_memory_for_session(db: Session, session_id: Optional[str]) -> None:
|
||||
if not session_id:
|
||||
return
|
||||
try:
|
||||
sync_chat_memory_for_session(db, str(session_id))
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
print("[chat-memory] session sync failed:", exc)
|
||||
|
||||
|
||||
def safe_delete_chat_memory_for_session(db: Session, session_id: Optional[str]) -> None:
|
||||
if not session_id:
|
||||
return
|
||||
try:
|
||||
delete_chat_memory_for_session(db, str(session_id), commit=False)
|
||||
except Exception as exc:
|
||||
print("[chat-memory] session delete failed:", exc)
|
||||
|
||||
|
||||
def _query_tokens(prompt: str, limit: int = 24) -> List[str]:
|
||||
tokens: List[str] = []
|
||||
seen = set()
|
||||
for raw in _TOKEN_RE.findall(str(prompt or "").casefold()):
|
||||
token = raw.strip("'_-")
|
||||
if len(token) < 2 or token in seen:
|
||||
continue
|
||||
seen.add(token)
|
||||
tokens.append(token)
|
||||
if len(tokens) >= limit:
|
||||
break
|
||||
return tokens
|
||||
|
||||
|
||||
def _fts_match_query(tokens: Sequence[str]) -> str:
|
||||
safe_terms = []
|
||||
for token in tokens:
|
||||
cleaned = re.sub(r"[^0-9A-Za-z_\u0080-\uffff]", "", token)
|
||||
if cleaned:
|
||||
safe_terms.append(f'"{cleaned}"')
|
||||
return " OR ".join(safe_terms)
|
||||
|
||||
|
||||
def _row_mapping(row: Any) -> Dict[str, Any]:
|
||||
if isinstance(row, dict):
|
||||
return row
|
||||
try:
|
||||
return dict(row._mapping)
|
||||
except Exception:
|
||||
return dict(row)
|
||||
|
||||
|
||||
def _score_hit(
|
||||
row: Dict[str, Any],
|
||||
tokens: Sequence[str],
|
||||
fts_rank: Optional[float] = None,
|
||||
) -> float:
|
||||
title = str(row.get("session_name") or "").casefold()
|
||||
user_text = str(row.get("user_content") or "").casefold()
|
||||
assistant_text = str(row.get("assistant_content") or "").casefold()
|
||||
attachment_text = str(row.get("attachment_summary") or "").casefold()
|
||||
combined = f"{title} {attachment_text} {user_text} {assistant_text}"
|
||||
hits = [token for token in tokens if token in combined]
|
||||
if not hits:
|
||||
return 0.0
|
||||
score = len(hits) / max(1, min(len(tokens), 8))
|
||||
score += 0.18 * sum(1 for token in hits if token in title)
|
||||
score += 0.10 * sum(1 for token in hits if token in user_text)
|
||||
if fts_rank is not None:
|
||||
try:
|
||||
score += min(0.08, 1.0 / (1.0 + abs(float(fts_rank))))
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
assistant_row = int(row.get("assistant_message_row_id") or 0)
|
||||
score += min(0.04, assistant_row / 2_000_000)
|
||||
except Exception:
|
||||
pass
|
||||
return score
|
||||
|
||||
|
||||
def _load_fts_candidates(
|
||||
db: Session,
|
||||
tokens: Sequence[str],
|
||||
*,
|
||||
exclude_session_id: Optional[str],
|
||||
limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
match = _fts_match_query(tokens)
|
||||
if not match:
|
||||
return []
|
||||
try:
|
||||
rows = db.execute(text(
|
||||
"""
|
||||
SELECT
|
||||
t.turn_key, t.session_id, t.session_name, t.user_message_id,
|
||||
t.assistant_message_id, t.user_message_row_id, t.assistant_message_row_id,
|
||||
t.user_content, t.assistant_content, t.attachment_summary, t.search_text,
|
||||
t.created_at, bm25(chat_memory_turns_fts) AS fts_rank
|
||||
FROM chat_memory_turns_fts
|
||||
JOIN chat_memory_turns t ON t.turn_key = chat_memory_turns_fts.turn_key
|
||||
WHERE chat_memory_turns_fts MATCH :match
|
||||
AND (:exclude_session_id IS NULL OR t.session_id != :exclude_session_id)
|
||||
ORDER BY fts_rank ASC, t.assistant_message_row_id DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
), {
|
||||
"match": match,
|
||||
"exclude_session_id": exclude_session_id,
|
||||
"limit": max(limit, 1),
|
||||
}).mappings().all()
|
||||
except Exception:
|
||||
return []
|
||||
candidates: List[Dict[str, Any]] = []
|
||||
for row in rows:
|
||||
item = _row_mapping(row)
|
||||
item["_score"] = _score_hit(item, tokens, item.get("fts_rank"))
|
||||
if item["_score"] > 0:
|
||||
candidates.append(item)
|
||||
return candidates
|
||||
|
||||
|
||||
def _load_table_candidates(
|
||||
db: Session,
|
||||
tokens: Sequence[str],
|
||||
*,
|
||||
exclude_session_id: Optional[str],
|
||||
limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
try:
|
||||
rows = db.execute(text(
|
||||
"""
|
||||
SELECT
|
||||
turn_key, session_id, session_name, user_message_id, assistant_message_id,
|
||||
user_message_row_id, assistant_message_row_id, user_content, assistant_content,
|
||||
attachment_summary, search_text, created_at
|
||||
FROM chat_memory_turns
|
||||
WHERE (:exclude_session_id IS NULL OR session_id != :exclude_session_id)
|
||||
ORDER BY assistant_message_row_id DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
), {
|
||||
"exclude_session_id": exclude_session_id,
|
||||
"limit": max(limit, 1),
|
||||
}).mappings().all()
|
||||
except Exception:
|
||||
return []
|
||||
candidates: List[Dict[str, Any]] = []
|
||||
for row in rows:
|
||||
item = _row_mapping(row)
|
||||
item["_score"] = _score_hit(item, tokens)
|
||||
if item["_score"] > 0:
|
||||
candidates.append(item)
|
||||
return candidates
|
||||
|
||||
|
||||
def _load_live_candidates(
|
||||
db: Session,
|
||||
tokens: Sequence[str],
|
||||
*,
|
||||
exclude_session_id: Optional[str],
|
||||
limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
try:
|
||||
rows = db.execute(text(
|
||||
"""
|
||||
SELECT
|
||||
s.session_id, s.name AS session_name,
|
||||
m.id AS message_row_id, m.message_id, m.role, m.content,
|
||||
m.sources_json, m.attachments_json, m.created_at
|
||||
FROM chat_messages m
|
||||
JOIN chat_sessions s ON s.id = m.session_pk
|
||||
WHERE (:exclude_session_id IS NULL OR s.session_id != :exclude_session_id)
|
||||
ORDER BY s.id ASC, m.created_at ASC, m.id ASC
|
||||
LIMIT :limit
|
||||
"""
|
||||
), {
|
||||
"exclude_session_id": exclude_session_id,
|
||||
"limit": max(limit, 1),
|
||||
}).mappings().all()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
turns: List[Dict[str, Any]] = []
|
||||
pending_by_session: Dict[str, Dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
item = _row_mapping(row)
|
||||
session_id = str(item.get("session_id") or "")
|
||||
if item.get("role") == "user":
|
||||
pending_by_session[session_id] = item
|
||||
continue
|
||||
if item.get("role") != "assistant" or session_id not in pending_by_session:
|
||||
continue
|
||||
if _is_memory_only_source_value(item.get("sources_json")):
|
||||
pending_by_session.pop(session_id, None)
|
||||
continue
|
||||
user = pending_by_session.pop(session_id)
|
||||
user_content = _clean_content(user.get("content"))
|
||||
assistant_content = _clean_content(item.get("content"))
|
||||
if not user_content or not assistant_content:
|
||||
continue
|
||||
attachments = _attachment_summary(user.get("attachments_json"))
|
||||
turn = {
|
||||
"turn_key": f"{user.get('message_id')}:{item.get('message_id')}",
|
||||
"session_id": session_id,
|
||||
"session_name": _clean_content(item.get("session_name"), limit=200) or "New Chat",
|
||||
"user_message_id": user.get("message_id"),
|
||||
"assistant_message_id": item.get("message_id"),
|
||||
"user_message_row_id": user.get("message_row_id"),
|
||||
"assistant_message_row_id": item.get("message_row_id"),
|
||||
"user_content": user_content,
|
||||
"assistant_content": assistant_content,
|
||||
"attachment_summary": attachments,
|
||||
"created_at": str(item.get("created_at") or ""),
|
||||
}
|
||||
turn["_score"] = _score_hit(turn, tokens)
|
||||
if turn["_score"] > 0:
|
||||
turns.append(turn)
|
||||
return turns
|
||||
|
||||
|
||||
def _trim(value: Any, limit: int) -> str:
|
||||
text_value = _clean_content(value, limit=max(limit * 2, limit))
|
||||
if len(text_value) <= limit:
|
||||
return text_value
|
||||
return text_value[:limit].rstrip() + "..."
|
||||
|
||||
|
||||
def _dedupe_hits(candidates: Sequence[Dict[str, Any]], top_k: int) -> List[Dict[str, Any]]:
|
||||
seen = set()
|
||||
ordered = sorted(candidates, key=lambda item: (float(item.get("_score") or 0), int(item.get("assistant_message_row_id") or 0)), reverse=True)
|
||||
hits: List[Dict[str, Any]] = []
|
||||
for item in ordered:
|
||||
key = item.get("turn_key") or (item.get("session_id"), item.get("assistant_message_id"))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
hits.append(item)
|
||||
if len(hits) >= top_k:
|
||||
break
|
||||
return hits
|
||||
|
||||
|
||||
def _context_payload_from_hits(
|
||||
hits: Sequence[Dict[str, Any]],
|
||||
*,
|
||||
context_character_budget: int,
|
||||
intro: str,
|
||||
) -> Dict[str, Any]:
|
||||
if not hits:
|
||||
return {"context_block": "", "sources": [], "hits": []}
|
||||
|
||||
header = f"<chat_memory_context>\n{intro}"
|
||||
blocks = [header]
|
||||
sources: List[Dict[str, Any]] = []
|
||||
remaining = max(600, int(context_character_budget)) - len(header) - len("</chat_memory_context>")
|
||||
for idx, hit in enumerate(hits, start=1):
|
||||
title = _trim(hit.get("session_name") or "Previous chat", 120)
|
||||
date = str(hit.get("created_at") or "")[:10]
|
||||
user = _trim(hit.get("user_content"), 520)
|
||||
assistant = _trim(hit.get("assistant_content"), 900)
|
||||
attachments = _trim(hit.get("attachment_summary"), 180)
|
||||
attachment_line = f"\nAttachments: {attachments}" if attachments else ""
|
||||
chunk = (
|
||||
f"[M{idx}] {title}{f' ({date})' if date else ''}{attachment_line}\n"
|
||||
f"User: {user}\n"
|
||||
f"Assistant: {assistant}"
|
||||
)
|
||||
if len(chunk) > remaining:
|
||||
if remaining < 500:
|
||||
break
|
||||
chunk = chunk[:remaining].rstrip() + "..."
|
||||
blocks.append(chunk)
|
||||
remaining -= len(chunk) + 2
|
||||
sources.append({
|
||||
"type": "chat_memory",
|
||||
"title": f"Chat memory: {title}",
|
||||
"source_session_id": hit.get("session_id"),
|
||||
"source_message_id": hit.get("assistant_message_id"),
|
||||
"snippet": assistant[:500],
|
||||
"score": round(float(hit.get("_score") or 0), 4),
|
||||
"created_at": hit.get("created_at"),
|
||||
})
|
||||
if remaining <= 0:
|
||||
break
|
||||
blocks.append("</chat_memory_context>")
|
||||
return {"context_block": "\n\n".join(blocks), "sources": sources, "hits": list(hits[:len(sources)])}
|
||||
|
||||
|
||||
def _load_previous_session_hits(
|
||||
db: Session,
|
||||
*,
|
||||
exclude_session_id: Optional[str],
|
||||
limit: int,
|
||||
) -> List[Dict[str, Any]]:
|
||||
current_created_at = None
|
||||
if exclude_session_id:
|
||||
try:
|
||||
current_session = db.query(models.ChatSession).filter(models.ChatSession.session_id == exclude_session_id).first()
|
||||
current_created_at = current_session.created_at if current_session else None
|
||||
except Exception:
|
||||
current_created_at = None
|
||||
|
||||
try:
|
||||
query = db.query(models.ChatSession)
|
||||
if exclude_session_id:
|
||||
query = query.filter(models.ChatSession.session_id != exclude_session_id)
|
||||
if current_created_at:
|
||||
query = query.filter(models.ChatSession.created_at < current_created_at)
|
||||
sessions = query.order_by(models.ChatSession.created_at.desc(), models.ChatSession.id.desc()).limit(20).all()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
for session in sessions:
|
||||
rows = (
|
||||
db.query(models.ChatMessage)
|
||||
.filter(models.ChatMessage.session_pk == session.id)
|
||||
.order_by(models.ChatMessage.created_at.asc(), models.ChatMessage.id.asc())
|
||||
.all()
|
||||
)
|
||||
hits = _completed_turns(session, rows, skip_memory_only=False)[:max(1, limit)]
|
||||
if hits:
|
||||
for hit in hits:
|
||||
hit["_score"] = 1.0
|
||||
return hits
|
||||
return []
|
||||
|
||||
|
||||
def build_chat_memory_context(
|
||||
db: Session,
|
||||
prompt: str,
|
||||
*,
|
||||
exclude_session_id: Optional[str] = None,
|
||||
top_k: int = DEFAULT_MEMORY_TOP_K,
|
||||
context_character_budget: int = DEFAULT_MEMORY_CONTEXT_CHARS,
|
||||
mode: str = "search",
|
||||
) -> Dict[str, Any]:
|
||||
if mode == "recent":
|
||||
hits = _load_previous_session_hits(db, exclude_session_id=exclude_session_id, limit=max(1, top_k))
|
||||
return _context_payload_from_hits(
|
||||
hits,
|
||||
context_character_budget=context_character_budget,
|
||||
intro=(
|
||||
"Most recent previous chat. Use this to answer questions about the last or previous conversation; "
|
||||
"do not treat it as fresh external evidence."
|
||||
),
|
||||
)
|
||||
|
||||
tokens = _query_tokens(prompt)
|
||||
if not tokens:
|
||||
return {"context_block": "", "sources": [], "hits": []}
|
||||
|
||||
candidate_limit = max(80, top_k * 24)
|
||||
candidates = _load_fts_candidates(
|
||||
db,
|
||||
tokens,
|
||||
exclude_session_id=exclude_session_id,
|
||||
limit=candidate_limit,
|
||||
)
|
||||
if len(candidates) < top_k:
|
||||
candidates.extend(_load_table_candidates(
|
||||
db,
|
||||
tokens,
|
||||
exclude_session_id=exclude_session_id,
|
||||
limit=max(300, candidate_limit),
|
||||
))
|
||||
if len(candidates) < top_k:
|
||||
candidates.extend(_load_live_candidates(
|
||||
db,
|
||||
tokens,
|
||||
exclude_session_id=exclude_session_id,
|
||||
limit=1500,
|
||||
))
|
||||
|
||||
hits = _dedupe_hits(candidates, max(1, top_k))
|
||||
return _context_payload_from_hits(
|
||||
hits,
|
||||
context_character_budget=context_character_budget,
|
||||
intro=(
|
||||
"Relevant excerpts from previous chats. Use these only when they help answer the current request; "
|
||||
"they may be outdated and should not override explicit current context or fresh retrieved evidence."
|
||||
),
|
||||
)
|
||||
@@ -1,8 +1,25 @@
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, DeclarativeBase
|
||||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||||
import uuid
|
||||
|
||||
DATABASE_URL = "sqlite:///./backend/app.db"
|
||||
from .paths import database_path, sqlite_database_url
|
||||
|
||||
"""
|
||||
Database utilities and configuration. This module defines the SQLAlchemy
|
||||
engine, session factory and base class for models. It also contains a
|
||||
lightweight migration helper used to evolve the schema over time. The
|
||||
`ensure_sources_column` helper adds the JSON-backed columns used by chat
|
||||
messages when they do not already exist.
|
||||
|
||||
The migration uses SQLite's `ALTER TABLE` syntax and therefore should
|
||||
only run once on startup. It is safe to call repeatedly: when a column
|
||||
already exists, the function will simply no-op.
|
||||
"""
|
||||
|
||||
DATABASE_PATH = database_path()
|
||||
DATABASE_URL = sqlite_database_url(DATABASE_PATH)
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
@@ -12,3 +29,42 @@ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def ensure_sources_column(engine):
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
cols = [row[1] for row in conn.execute(text("PRAGMA table_info(chat_messages)"))]
|
||||
if "message_id" not in cols:
|
||||
conn.execute(text("ALTER TABLE chat_messages ADD COLUMN message_id TEXT"))
|
||||
if "sources_json" not in cols:
|
||||
conn.execute(text("ALTER TABLE chat_messages ADD COLUMN sources_json TEXT DEFAULT '[]'"))
|
||||
if "attachments_json" not in cols:
|
||||
conn.execute(text("ALTER TABLE chat_messages ADD COLUMN attachments_json TEXT DEFAULT '[]'"))
|
||||
for column_name, definition in (
|
||||
("workflow_id", "TEXT"),
|
||||
("workflow_revision_id", "TEXT"),
|
||||
("workflow_run_id", "TEXT"),
|
||||
("agent_summary_json", "TEXT DEFAULT '{}'"),
|
||||
("usage_json", "TEXT DEFAULT '{}'"),
|
||||
):
|
||||
if column_name not in cols:
|
||||
conn.execute(text(f"ALTER TABLE chat_messages ADD COLUMN {column_name} {definition}"))
|
||||
missing_ids = conn.execute(
|
||||
text("SELECT id FROM chat_messages WHERE message_id IS NULL OR message_id = ''")
|
||||
).fetchall()
|
||||
for row in missing_ids:
|
||||
conn.execute(
|
||||
text("UPDATE chat_messages SET message_id = :message_id WHERE id = :id"),
|
||||
{"message_id": str(uuid.uuid4()), "id": row[0]},
|
||||
)
|
||||
conn.execute(text(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS ix_chat_messages_message_id "
|
||||
"ON chat_messages (message_id)"
|
||||
))
|
||||
conn.execute(text(
|
||||
"CREATE INDEX IF NOT EXISTS ix_chat_messages_workflow_run_id "
|
||||
"ON chat_messages (workflow_run_id)"
|
||||
))
|
||||
except Exception as e:
|
||||
print("[db] ensure_sources_column error:", e)
|
||||
|
||||
2365
backend/local_rag.py
Normal file
2365
backend/local_rag.py
Normal file
File diff suppressed because it is too large
Load Diff
997
backend/main.py
997
backend/main.py
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
from .database import Base
|
||||
|
||||
class ChatSession(Base):
|
||||
@@ -17,9 +18,19 @@ class ChatMessage(Base):
|
||||
__tablename__ = 'chat_messages'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
message_id = Column(String(36), unique=True, index=True, nullable=False, default=lambda: str(uuid.uuid4()))
|
||||
session_pk = Column(Integer, ForeignKey('chat_sessions.id'), nullable=False)
|
||||
role = Column(String(16), nullable=False) # 'user' | 'assistant'
|
||||
content = Column(Text, nullable=False)
|
||||
# JSON-encoded list of citation URLs; null/empty => no chips
|
||||
sources_json = Column(Text, nullable=True, default='[]')
|
||||
# JSON-encoded list of inline image attachments for user messages.
|
||||
attachments_json = Column(Text, nullable=True, default='[]')
|
||||
workflow_id = Column(String(36), nullable=True)
|
||||
workflow_revision_id = Column(String(36), nullable=True)
|
||||
workflow_run_id = Column(String(36), nullable=True, index=True)
|
||||
agent_summary_json = Column(Text, nullable=True, default='{}')
|
||||
usage_json = Column(Text, nullable=True, default='{}')
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
session = relationship("ChatSession", back_populates="messages")
|
||||
|
||||
232
backend/ollama_admin.py
Normal file
232
backend/ollama_admin.py
Normal file
@@ -0,0 +1,232 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import Any, Dict, List, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
from .app_settings import (
|
||||
get_embed_model_preference,
|
||||
get_ollama_api_url,
|
||||
get_rerank_model_preference,
|
||||
get_transcription_model_preference,
|
||||
normalize_embed_model,
|
||||
normalize_rerank_model,
|
||||
)
|
||||
from .whisper_admin import ensure_whisper_model_downloaded, inspect_whisper_model
|
||||
|
||||
|
||||
LOCAL_OLLAMA_HOSTS = {"127.0.0.1", "localhost", "::1"}
|
||||
_OLLAMA_PULL_LOCK = asyncio.Lock()
|
||||
|
||||
|
||||
def _ollama_binary() -> Optional[str]:
|
||||
return shutil.which("ollama")
|
||||
|
||||
|
||||
def _is_local_ollama_url(url: str) -> bool:
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
except Exception:
|
||||
return False
|
||||
return (parsed.hostname or "").strip().lower() in LOCAL_OLLAMA_HOSTS
|
||||
|
||||
|
||||
def _model_aliases(model: str) -> set[str]:
|
||||
normalized = normalize_embed_model(model)
|
||||
aliases = {normalized}
|
||||
if normalized.endswith(":latest"):
|
||||
aliases.add(normalized[:-7])
|
||||
else:
|
||||
aliases.add(f"{normalized}:latest")
|
||||
return aliases
|
||||
|
||||
|
||||
async def _list_model_names(ollama_url: str, *, timeout: float = 5.0) -> List[str]:
|
||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||
response = await client.get(f"{ollama_url.rstrip('/')}/api/tags")
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
|
||||
out: List[str] = []
|
||||
for item in payload.get("models", []) or []:
|
||||
name = str((item or {}).get("name") or "").strip()
|
||||
if name:
|
||||
out.append(name)
|
||||
return out
|
||||
|
||||
|
||||
async def inspect_ollama_startup() -> Dict[str, Any]:
|
||||
ollama_url = get_ollama_api_url()
|
||||
embed_model = get_embed_model_preference()
|
||||
rerank_model = get_rerank_model_preference()
|
||||
transcription_model = get_transcription_model_preference()
|
||||
ollama_bin = _ollama_binary()
|
||||
is_local = _is_local_ollama_url(ollama_url)
|
||||
whisper_status = inspect_whisper_model(transcription_model)
|
||||
available_models: List[str] = []
|
||||
error = ""
|
||||
running = False
|
||||
|
||||
try:
|
||||
available_models = await _list_model_names(ollama_url)
|
||||
running = True
|
||||
except Exception as exc:
|
||||
error = str(exc)
|
||||
|
||||
available = bool(set(available_models) & _model_aliases(embed_model))
|
||||
rerank_available = bool(set(available_models) & _model_aliases(rerank_model))
|
||||
return {
|
||||
"ollama_url": ollama_url,
|
||||
"ollama_running": running,
|
||||
"ollama_binary_found": bool(ollama_bin),
|
||||
"can_manage_locally": bool(ollama_bin) and is_local,
|
||||
"selected_embed_model": embed_model,
|
||||
"selected_rerank_model": rerank_model,
|
||||
"selected_transcription_model": transcription_model,
|
||||
"embedding_model_available": available,
|
||||
"reranking_model_available": rerank_available,
|
||||
"available_models": available_models,
|
||||
"whisper_model": whisper_status["model"],
|
||||
"whisper_model_available": bool(whisper_status["available"]),
|
||||
"whisper_error": whisper_status["error"],
|
||||
"error": error,
|
||||
}
|
||||
|
||||
|
||||
async def start_local_ollama() -> Dict[str, Any]:
|
||||
status = await inspect_ollama_startup()
|
||||
if status["ollama_running"]:
|
||||
return status
|
||||
if not status["can_manage_locally"]:
|
||||
raise RuntimeError("Ollama can only be started automatically when the configured Ollama URL points to this machine.")
|
||||
|
||||
ollama_bin = _ollama_binary()
|
||||
if not ollama_bin:
|
||||
raise FileNotFoundError("Could not find the 'ollama' executable in PATH.")
|
||||
|
||||
subprocess.Popen(
|
||||
[ollama_bin, "serve"],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
env=os.environ.copy(),
|
||||
)
|
||||
|
||||
for _ in range(20):
|
||||
await asyncio.sleep(0.5)
|
||||
status = await inspect_ollama_startup()
|
||||
if status["ollama_running"]:
|
||||
return status
|
||||
|
||||
raise RuntimeError("Started 'ollama serve', but Ollama did not become reachable in time.")
|
||||
|
||||
|
||||
async def pull_local_model(model: Optional[str] = None) -> Dict[str, Any]:
|
||||
async with _OLLAMA_PULL_LOCK:
|
||||
status = await inspect_ollama_startup()
|
||||
if not status["can_manage_locally"]:
|
||||
raise RuntimeError("Heimgeist can only pull models automatically when the configured Ollama URL points to this machine.")
|
||||
if not status["ollama_running"]:
|
||||
raise RuntimeError("Ollama must be running before Heimgeist can pull a model.")
|
||||
|
||||
ollama_bin = _ollama_binary()
|
||||
if not ollama_bin:
|
||||
raise FileNotFoundError("Could not find the 'ollama' executable in PATH.")
|
||||
|
||||
model_name = normalize_embed_model(model or status["selected_embed_model"])
|
||||
if bool(set(status["available_models"]) & _model_aliases(model_name)):
|
||||
return {
|
||||
"model": model_name,
|
||||
"downloaded": False,
|
||||
"status": status,
|
||||
}
|
||||
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
ollama_bin,
|
||||
"pull",
|
||||
model_name,
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
_stdout, stderr = await process.communicate()
|
||||
if process.returncode != 0:
|
||||
detail = (stderr or b"").decode("utf-8", errors="ignore").strip()
|
||||
raise RuntimeError(detail or f"'ollama pull {model_name}' failed with exit code {process.returncode}.")
|
||||
|
||||
status = await inspect_ollama_startup()
|
||||
return {
|
||||
"model": model_name,
|
||||
"downloaded": True,
|
||||
"status": status,
|
||||
}
|
||||
|
||||
|
||||
async def prepare_startup_models() -> Dict[str, Any]:
|
||||
status = await inspect_ollama_startup()
|
||||
whisper_result = await asyncio.to_thread(ensure_whisper_model_downloaded, status["whisper_model"])
|
||||
status = await inspect_ollama_startup()
|
||||
|
||||
embedding_result: Dict[str, Any] = {
|
||||
"model": status["selected_embed_model"],
|
||||
"available": bool(status["embedding_model_available"]),
|
||||
"downloaded": False,
|
||||
"skipped": False,
|
||||
"reason": "",
|
||||
}
|
||||
rerank_result: Dict[str, Any] = {
|
||||
"model": status["selected_rerank_model"],
|
||||
"available": bool(status["reranking_model_available"]),
|
||||
"downloaded": False,
|
||||
"skipped": False,
|
||||
"reason": "",
|
||||
}
|
||||
|
||||
if not status["ollama_running"]:
|
||||
embedding_result["skipped"] = True
|
||||
embedding_result["reason"] = "Ollama is not running."
|
||||
rerank_result["skipped"] = True
|
||||
rerank_result["reason"] = "Ollama is not running."
|
||||
elif not status["can_manage_locally"]:
|
||||
embedding_result["skipped"] = True
|
||||
embedding_result["reason"] = "Automatic model pulls are only available for local Ollama."
|
||||
rerank_result["skipped"] = True
|
||||
rerank_result["reason"] = "Automatic model pulls are only available for local Ollama."
|
||||
elif not status["embedding_model_available"]:
|
||||
pulled = await pull_local_model(status["selected_embed_model"])
|
||||
status = pulled["status"]
|
||||
embedding_result = {
|
||||
"model": pulled["model"],
|
||||
"available": bool(status["embedding_model_available"]),
|
||||
"downloaded": bool(pulled.get("downloaded")),
|
||||
"skipped": False,
|
||||
"reason": "",
|
||||
}
|
||||
|
||||
rerank_model = normalize_rerank_model(status["selected_rerank_model"])
|
||||
if rerank_model == normalize_embed_model(status["selected_embed_model"]):
|
||||
rerank_result["available"] = bool(status["embedding_model_available"])
|
||||
rerank_result["downloaded"] = bool(embedding_result.get("downloaded"))
|
||||
elif not rerank_result["skipped"] and not status["reranking_model_available"]:
|
||||
pulled = await pull_local_model(rerank_model)
|
||||
status = pulled["status"]
|
||||
rerank_result = {
|
||||
"model": pulled["model"],
|
||||
"available": bool(status["reranking_model_available"]),
|
||||
"downloaded": bool(pulled.get("downloaded")),
|
||||
"skipped": False,
|
||||
"reason": "",
|
||||
}
|
||||
|
||||
return {
|
||||
"ollama": status,
|
||||
"whisper": whisper_result,
|
||||
"embedding_model": embedding_result,
|
||||
"reranking_model": rerank_result,
|
||||
}
|
||||
@@ -1,55 +1,372 @@
|
||||
|
||||
import asyncio
|
||||
import httpx
|
||||
import json
|
||||
from typing import Dict, Any, List, AsyncGenerator
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Any, List, AsyncGenerator, Optional, Tuple
|
||||
|
||||
from .app_settings import get_ollama_api_url
|
||||
|
||||
_MODEL_DETAILS_CACHE: Dict[Tuple[str, str], Tuple[float, Dict[str, Any]]] = {}
|
||||
_MODEL_DETAILS_TTL_S = 15.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class OllamaToolCall:
|
||||
name: str
|
||||
arguments: Dict[str, Any]
|
||||
raw: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OllamaUsage:
|
||||
prompt_eval_count: int = 0
|
||||
eval_count: int = 0
|
||||
total_duration: int = 0
|
||||
load_duration: int = 0
|
||||
prompt_eval_duration: int = 0
|
||||
eval_duration: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class OllamaChatResult:
|
||||
content: str = ""
|
||||
thinking: str = ""
|
||||
tool_calls: List[OllamaToolCall] = field(default_factory=list)
|
||||
usage: OllamaUsage = field(default_factory=OllamaUsage)
|
||||
done_reason: Optional[str] = None
|
||||
raw: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OllamaStreamChunk:
|
||||
content: str = ""
|
||||
thinking: str = ""
|
||||
tool_calls: List[OllamaToolCall] = field(default_factory=list)
|
||||
done: bool = False
|
||||
usage: OllamaUsage = field(default_factory=OllamaUsage)
|
||||
raw: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _cache_key(model: str) -> Tuple[str, str]:
|
||||
ollama_url = get_ollama_api_url()
|
||||
return (ollama_url.rstrip('/'), str(model or '').strip())
|
||||
|
||||
|
||||
def _get_cached_model_details(model: str) -> Dict[str, Any]:
|
||||
cached = _MODEL_DETAILS_CACHE.get(_cache_key(model))
|
||||
return cached[1] if cached else {}
|
||||
|
||||
|
||||
def _string_tokens(value: Any) -> List[str]:
|
||||
if isinstance(value, str):
|
||||
trimmed = value.strip()
|
||||
return [trimmed] if trimmed else []
|
||||
if isinstance(value, dict):
|
||||
out: List[str] = []
|
||||
for key, item in value.items():
|
||||
out.extend(_string_tokens(key))
|
||||
out.extend(_string_tokens(item))
|
||||
return out
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
out: List[str] = []
|
||||
for item in value:
|
||||
out.extend(_string_tokens(item))
|
||||
return out
|
||||
return []
|
||||
|
||||
|
||||
def _normalize_capabilities(model_data: Dict[str, Any]) -> List[str]:
|
||||
out = []
|
||||
for item in model_data.get("capabilities") or []:
|
||||
text = str(item).strip().lower()
|
||||
if text and text not in out:
|
||||
out.append(text)
|
||||
return out
|
||||
|
||||
|
||||
def _combined_model_tokens(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> str:
|
||||
return " ".join(
|
||||
token.lower()
|
||||
for token in _string_tokens(name) + _string_tokens(tag_item.get("details")) + _string_tokens(model_data)
|
||||
)
|
||||
|
||||
|
||||
def _is_embedding_model(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> bool:
|
||||
capabilities = set(_normalize_capabilities(model_data))
|
||||
if "embedding" in capabilities or "embeddings" in capabilities:
|
||||
return True
|
||||
|
||||
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
|
||||
return any(
|
||||
marker in lowered_tokens
|
||||
for marker in (
|
||||
" embed ",
|
||||
" embedding ",
|
||||
"embed-",
|
||||
"-embed",
|
||||
"nomic-embed",
|
||||
"mxbai-embed",
|
||||
"snowflake-arctic-embed",
|
||||
"bge-m3",
|
||||
"bge ",
|
||||
)
|
||||
) or lowered_tokens.startswith("bge")
|
||||
|
||||
|
||||
def _is_rerank_model(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> bool:
|
||||
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
|
||||
return (
|
||||
_is_embedding_model(name, model_data, tag_item)
|
||||
or "rerank" in lowered_tokens
|
||||
or "cross-encoder" in lowered_tokens
|
||||
)
|
||||
|
||||
|
||||
def _supports_vision_fast(name: str, model_data: Dict[str, Any], tag_item: Dict[str, Any]) -> bool:
|
||||
if supports_vision(model_data):
|
||||
return True
|
||||
|
||||
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
|
||||
return any(
|
||||
marker in lowered_tokens
|
||||
for marker in (
|
||||
" vision ",
|
||||
"-vision",
|
||||
" vision-",
|
||||
"vision:",
|
||||
"llava",
|
||||
"bakllava",
|
||||
"moondream",
|
||||
"minicpm-v",
|
||||
"minicpmv",
|
||||
"pixtral",
|
||||
"qwen-vl",
|
||||
"qwen2vl",
|
||||
"qwen2.5vl",
|
||||
"qwen2.5-omni",
|
||||
"granite3.2-vision",
|
||||
"llama3.2-vision",
|
||||
"gemma3",
|
||||
"gemma4",
|
||||
"-vl",
|
||||
" vl ",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _build_model_catalog_entry(tag_item: Dict[str, Any], model_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
name = str((tag_item or {}).get("name") or "").strip()
|
||||
capabilities = _normalize_capabilities(model_data)
|
||||
is_embedding = _is_embedding_model(name, model_data, tag_item)
|
||||
is_rerank = _is_rerank_model(name, model_data, tag_item)
|
||||
has_vision = _supports_vision_fast(name, model_data, tag_item)
|
||||
lowered_tokens = _combined_model_tokens(name, model_data, tag_item)
|
||||
is_non_chat = is_embedding or "rerank" in lowered_tokens or "cross-encoder" in lowered_tokens
|
||||
return {
|
||||
"name": name,
|
||||
"capabilities": capabilities,
|
||||
"supports_vision": has_vision,
|
||||
"is_embedding": is_embedding,
|
||||
"can_chat": not is_non_chat,
|
||||
"can_rerank": is_rerank,
|
||||
}
|
||||
|
||||
OLLAMA_URL = "http://127.0.0.1:11434"
|
||||
|
||||
async def list_models() -> Dict[str, Any]:
|
||||
ollama_url = get_ollama_api_url()
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
r = await client.get(f"{OLLAMA_URL}/api/tags")
|
||||
r = await client.get(f"{ollama_url}/api/tags")
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
# Normalize to a simple list of names
|
||||
models = [m.get('name') for m in data.get('models', [])]
|
||||
return {"models": models}
|
||||
|
||||
async def chat(model: str, messages: List[Dict[str, str]]) -> str:
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"stream": False
|
||||
|
||||
async def list_model_catalog() -> Dict[str, Any]:
|
||||
ollama_url = get_ollama_api_url()
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
r = await client.get(f"{ollama_url}/api/tags")
|
||||
r.raise_for_status()
|
||||
payload = r.json()
|
||||
|
||||
raw_models = payload.get("models", []) or []
|
||||
models = [
|
||||
_build_model_catalog_entry(
|
||||
item or {},
|
||||
_get_cached_model_details(str((item or {}).get("name") or "").strip()),
|
||||
)
|
||||
for item in raw_models
|
||||
if str((item or {}).get("name") or "").strip()
|
||||
]
|
||||
|
||||
return {
|
||||
"models": models,
|
||||
"chat_models": [model["name"] for model in models if model["can_chat"]],
|
||||
"embedding_models": [model["name"] for model in models if model["is_embedding"]],
|
||||
"vision_models": [model["name"] for model in models if model["supports_vision"]],
|
||||
"reranking_models": [model["name"] for model in models if model["can_rerank"]],
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=600.0) as client:
|
||||
r = await client.post(f"{OLLAMA_URL}/api/chat", json=payload)
|
||||
|
||||
async def show_model(model: str, *, refresh: bool = False) -> Dict[str, Any]:
|
||||
ollama_url = get_ollama_api_url()
|
||||
cache_key = (ollama_url.rstrip('/'), str(model or '').strip())
|
||||
cached = _MODEL_DETAILS_CACHE.get(cache_key)
|
||||
now = time.monotonic()
|
||||
if not refresh and cached and (now - cached[0]) < _MODEL_DETAILS_TTL_S:
|
||||
return cached[1]
|
||||
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
r = await client.post(f"{ollama_url}/api/show", json={"model": model})
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
# Ollama returns full conversation; pick last message content
|
||||
try:
|
||||
return data["message"]["content"]
|
||||
except Exception:
|
||||
# Newer Ollama formats may return messages list
|
||||
msgs = data.get("messages") or []
|
||||
if msgs:
|
||||
return msgs[-1].get("content", "")
|
||||
return data.get("content", "")
|
||||
_MODEL_DETAILS_CACHE[cache_key] = (now, data)
|
||||
return data
|
||||
|
||||
async def chat_stream(model: str, messages: List[Dict[str, str]]) -> AsyncGenerator[str, None]:
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"stream": True
|
||||
}
|
||||
def supports_vision(model_data: Dict[str, Any]) -> bool:
|
||||
capabilities = model_data.get("capabilities") or []
|
||||
if any(str(item).strip().lower() == "vision" for item in capabilities):
|
||||
return True
|
||||
|
||||
model_info = model_data.get("model_info") or {}
|
||||
if isinstance(model_info, dict):
|
||||
for key in model_info.keys():
|
||||
lowered = str(key).strip().lower()
|
||||
if ".vision." in lowered or lowered.endswith(".vision"):
|
||||
return True
|
||||
if lowered.endswith("tokens_per_image") or re.search(r"\bmm\b", lowered):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _parse_tool_calls(value: Any) -> List[OllamaToolCall]:
|
||||
calls: List[OllamaToolCall] = []
|
||||
for item in value or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
function = item.get("function") if isinstance(item.get("function"), dict) else item
|
||||
name = str(function.get("name") or "").strip()
|
||||
arguments = function.get("arguments") or {}
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except Exception:
|
||||
arguments = {}
|
||||
if name and isinstance(arguments, dict):
|
||||
calls.append(OllamaToolCall(name=name, arguments=arguments, raw=item))
|
||||
return calls
|
||||
|
||||
|
||||
def _usage_from_payload(data: Dict[str, Any]) -> OllamaUsage:
|
||||
return OllamaUsage(
|
||||
prompt_eval_count=int(data.get("prompt_eval_count") or 0),
|
||||
eval_count=int(data.get("eval_count") or 0),
|
||||
total_duration=int(data.get("total_duration") or 0),
|
||||
load_duration=int(data.get("load_duration") or 0),
|
||||
prompt_eval_duration=int(data.get("prompt_eval_duration") or 0),
|
||||
eval_duration=int(data.get("eval_duration") or 0),
|
||||
)
|
||||
|
||||
|
||||
def _chat_payload(
|
||||
model: str,
|
||||
messages: List[Dict[str, Any]],
|
||||
*,
|
||||
stream: bool,
|
||||
options: Optional[Dict[str, Any]] = None,
|
||||
tools: Optional[List[Dict[str, Any]]] = None,
|
||||
format: Optional[Any] = None,
|
||||
think: Optional[bool] = None,
|
||||
) -> Dict[str, Any]:
|
||||
payload: Dict[str, Any] = {"model": model, "messages": messages, "stream": stream}
|
||||
if options:
|
||||
payload["options"] = options
|
||||
if tools:
|
||||
payload["tools"] = tools
|
||||
if format is not None:
|
||||
payload["format"] = format
|
||||
if think is not None:
|
||||
payload["think"] = bool(think)
|
||||
return payload
|
||||
|
||||
|
||||
async def chat_typed(
|
||||
model: str,
|
||||
messages: List[Dict[str, Any]],
|
||||
*,
|
||||
options: Dict[str, Any] | None = None,
|
||||
tools: Optional[List[Dict[str, Any]]] = None,
|
||||
format: Optional[Any] = None,
|
||||
think: Optional[bool] = None,
|
||||
cancellation_event: Optional[Any] = None,
|
||||
) -> OllamaChatResult:
|
||||
ollama_url = get_ollama_api_url()
|
||||
if cancellation_event is not None and cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
payload = _chat_payload(model, messages, stream=False, options=options, tools=tools, format=format, think=think)
|
||||
async with httpx.AsyncClient(timeout=600.0) as client:
|
||||
async with client.stream("POST", f"{OLLAMA_URL}/api/chat", json=payload) as r:
|
||||
r.raise_for_status()
|
||||
async for line in r.aiter_lines():
|
||||
if line:
|
||||
try:
|
||||
chunk = json.loads(line)
|
||||
if "content" in chunk: # Newer Ollama format
|
||||
yield chunk["content"]
|
||||
elif "message" in chunk and "content" in chunk["message"]: # Older format
|
||||
yield chunk["message"]["content"]
|
||||
except json.JSONDecodeError:
|
||||
pass # Ignore invalid JSON lines
|
||||
r = await client.post(f"{ollama_url}/api/chat", json=payload)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
message = data.get("message") if isinstance(data.get("message"), dict) else {}
|
||||
if not message and data.get("messages"):
|
||||
message = data["messages"][-1] or {}
|
||||
return OllamaChatResult(
|
||||
content=str(message.get("content") or data.get("content") or ""),
|
||||
thinking=str(message.get("thinking") or data.get("thinking") or ""),
|
||||
tool_calls=_parse_tool_calls(message.get("tool_calls") or data.get("tool_calls")),
|
||||
usage=_usage_from_payload(data),
|
||||
done_reason=data.get("done_reason"),
|
||||
raw=data,
|
||||
)
|
||||
|
||||
|
||||
async def chat_stream_typed(
|
||||
model: str,
|
||||
messages: List[Dict[str, Any]],
|
||||
*,
|
||||
options: Optional[Dict[str, Any]] = None,
|
||||
tools: Optional[List[Dict[str, Any]]] = None,
|
||||
format: Optional[Any] = None,
|
||||
think: Optional[bool] = None,
|
||||
cancellation_event: Optional[Any] = None,
|
||||
) -> AsyncGenerator[OllamaStreamChunk, None]:
|
||||
ollama_url = get_ollama_api_url()
|
||||
payload = _chat_payload(model, messages, stream=True, options=options, tools=tools, format=format, think=think)
|
||||
async with httpx.AsyncClient(timeout=600.0) as client:
|
||||
async with client.stream("POST", f"{ollama_url}/api/chat", json=payload) as response:
|
||||
response.raise_for_status()
|
||||
async for line in response.aiter_lines():
|
||||
if cancellation_event is not None and cancellation_event.is_set():
|
||||
raise asyncio.CancelledError()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
message = data.get("message") if isinstance(data.get("message"), dict) else {}
|
||||
yield OllamaStreamChunk(
|
||||
content=str(message.get("content") or data.get("content") or ""),
|
||||
thinking=str(message.get("thinking") or data.get("thinking") or ""),
|
||||
tool_calls=_parse_tool_calls(message.get("tool_calls") or data.get("tool_calls")),
|
||||
done=bool(data.get("done")),
|
||||
usage=_usage_from_payload(data),
|
||||
raw=data,
|
||||
)
|
||||
|
||||
|
||||
async def chat(
|
||||
model: str,
|
||||
messages: List[Dict[str, Any]],
|
||||
*,
|
||||
options: Dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
return (await chat_typed(model, messages, options=options)).content
|
||||
|
||||
async def chat_stream(model: str, messages: List[Dict[str, Any]]) -> AsyncGenerator[str, None]:
|
||||
async for chunk in chat_stream_typed(model, messages):
|
||||
if chunk.content:
|
||||
yield chunk.content
|
||||
|
||||
112
backend/paths.py
Normal file
112
backend/paths.py
Normal file
@@ -0,0 +1,112 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parent
|
||||
DEFAULT_DB_PATH = BACKEND_DIR / "app.db"
|
||||
DEFAULT_LIB_ROOT = BACKEND_DIR / "libraries"
|
||||
|
||||
|
||||
def _clean_env(name: str) -> str:
|
||||
return os.getenv(name, "").strip()
|
||||
|
||||
|
||||
def _path_from_env(name: str) -> Path | None:
|
||||
value = _clean_env(name)
|
||||
if not value:
|
||||
return None
|
||||
return Path(value).expanduser()
|
||||
|
||||
|
||||
def _ensure_parent(path: Path) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _ensure_dir(path: Path) -> Path:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def data_dir() -> Path | None:
|
||||
"""
|
||||
Optional app-managed data root for packaged deployments.
|
||||
|
||||
HEIMGEIST_DATA_DIR is internal sidecar plumbing. Normal users should not
|
||||
need to configure it manually, and development intentionally leaves it
|
||||
unset so data stays in backend/app.db and backend/libraries.
|
||||
"""
|
||||
|
||||
path = _path_from_env("HEIMGEIST_DATA_DIR")
|
||||
if path is None:
|
||||
return None
|
||||
return _ensure_dir(path)
|
||||
|
||||
|
||||
def database_path() -> Path:
|
||||
"""
|
||||
Resolve the SQLite database path.
|
||||
|
||||
Precedence:
|
||||
1. HEIMGEIST_DB_PATH, for explicit packaged sidecar plumbing.
|
||||
2. HEIMGEIST_DATA_DIR/app.db, for packaged app-managed data.
|
||||
3. backend/app.db, for unchanged local development behavior.
|
||||
"""
|
||||
|
||||
explicit_path = _path_from_env("HEIMGEIST_DB_PATH")
|
||||
if explicit_path is not None:
|
||||
return _ensure_parent(explicit_path)
|
||||
|
||||
base_dir = data_dir()
|
||||
if base_dir is not None:
|
||||
return _ensure_parent(base_dir / "app.db")
|
||||
|
||||
return _ensure_parent(DEFAULT_DB_PATH)
|
||||
|
||||
|
||||
def library_root() -> Path:
|
||||
"""
|
||||
Resolve the local RAG library root.
|
||||
|
||||
Precedence:
|
||||
1. HEIMGEIST_LIB_ROOT, for explicit packaged sidecar plumbing.
|
||||
2. HEIMGEIST_DATA_DIR/libraries, for packaged app-managed data.
|
||||
3. backend/libraries, for unchanged local development behavior.
|
||||
"""
|
||||
|
||||
explicit_path = _path_from_env("HEIMGEIST_LIB_ROOT")
|
||||
if explicit_path is not None:
|
||||
return _ensure_dir(explicit_path)
|
||||
|
||||
base_dir = data_dir()
|
||||
if base_dir is not None:
|
||||
return _ensure_dir(base_dir / "libraries")
|
||||
|
||||
return _ensure_dir(DEFAULT_LIB_ROOT)
|
||||
|
||||
|
||||
def tool_root() -> Path:
|
||||
explicit_path = _path_from_env("HEIMGEIST_TOOL_DIR")
|
||||
if explicit_path is not None:
|
||||
return _ensure_dir(explicit_path)
|
||||
|
||||
base_dir = data_dir()
|
||||
if base_dir is not None:
|
||||
return _ensure_dir(base_dir / "tools")
|
||||
|
||||
if sys.platform == "darwin":
|
||||
return _ensure_dir(Path.home() / "Library" / "Application Support" / "Heimgeist" / "tools")
|
||||
if os.name == "nt":
|
||||
appdata = os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
root = Path(appdata) if appdata else Path.home() / "AppData" / "Local"
|
||||
return _ensure_dir(root / "Heimgeist" / "tools")
|
||||
xdg_data = Path(os.getenv("XDG_DATA_HOME", str(Path.home() / ".local" / "share")))
|
||||
return _ensure_dir(xdg_data / "Heimgeist" / "tools")
|
||||
|
||||
|
||||
def sqlite_database_url(path: Path | None = None) -> str:
|
||||
target = path or database_path()
|
||||
return f"sqlite:///{target.as_posix()}"
|
||||
0
backend/rag/__init__.py
Normal file
0
backend/rag/__init__.py
Normal file
1788
backend/rag/corpus_builder.py
Normal file
1788
backend/rag/corpus_builder.py
Normal file
File diff suppressed because it is too large
Load Diff
1101
backend/rag/corpus_enricher.py
Normal file
1101
backend/rag/corpus_enricher.py
Normal file
File diff suppressed because it is too large
Load Diff
707
backend/rag/index_builder.py
Normal file
707
backend/rag/index_builder.py
Normal file
@@ -0,0 +1,707 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
03_index_builder.py
|
||||
|
||||
Flexible FAISS index builder for hybrid RAG.
|
||||
|
||||
Supports these inputs (any subset):
|
||||
- --raw : corpus.jsonl from 01_corpus_builder.py (no enrichment)
|
||||
- --enhanced : corpus.enhanced.jsonl from 02_corpus_enricher.py
|
||||
- --shadow : corpus.shadow.jsonl from 02_corpus_enricher.py
|
||||
|
||||
Outputs (by default into ./indexes):
|
||||
- shadow.index.faiss : FAISS IP index over vectors of "shadow_text"
|
||||
- shadow.meta.jsonl : metadata for each FAISS id (id, doc_id, record_id, title, url, record_type, mime, lang, kind, shadow_text)
|
||||
- content.index.faiss : FAISS IP index over vectors of chunked "text"
|
||||
- content.meta.jsonl : metadata for each FAISS id (id, doc_id, record_id, chunk_no, title, url, text, record_type, mime, lang)
|
||||
|
||||
Behavior
|
||||
- If you provide --shadow → build shadow from it.
|
||||
- Else if you provide --enhanced → synthesize shadow from enriched fields (headline+summary+keywords+entities+qa).
|
||||
- Else if you provide --raw → synthesize shadow from raw (title + first sentences + hints).
|
||||
- If you provide --enhanced → build content from it.
|
||||
- Else if you provide --raw → build content from raw text (chunking).
|
||||
- You can disable either side with --no-shadow or --no-content.
|
||||
|
||||
Embedding
|
||||
- Uses Ollama /api/embeddings with cosine similarity (L2-normalize then IP).
|
||||
|
||||
Examples:
|
||||
|
||||
# Full hybrid from enriched+shadow
|
||||
python 03_index_builder.py \
|
||||
--enhanced corpus.enhanced.jsonl \
|
||||
--shadow corpus.shadow.jsonl \
|
||||
--out-dir indexes \
|
||||
--embed-model "dengcao/Qwen3-Embedding-0.6B:F16" \
|
||||
--target-chars 2500 --overlap-chars 200 \
|
||||
--concurrency 6
|
||||
|
||||
# Raw-only (no enricher) → builds content from raw text and a proxy shadow
|
||||
python 03_index_builder.py \
|
||||
--raw corpus.jsonl \
|
||||
--out-dir indexes \
|
||||
--embed-model "dengcao/Qwen3-Embedding-0.6B:F16"
|
||||
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse, json, sys, uuid, os, re, math
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Iterable, List, Tuple, Optional, Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import threading
|
||||
import numpy as np
|
||||
import requests
|
||||
import faiss
|
||||
|
||||
try:
|
||||
from backend.rag.ollama_embeddings import resolve_embed_model, request_embedding
|
||||
except ModuleNotFoundError:
|
||||
from .ollama_embeddings import resolve_embed_model, request_embedding
|
||||
|
||||
try:
|
||||
from tqdm import tqdm
|
||||
except ImportError:
|
||||
tqdm = None
|
||||
|
||||
# -----------------------------
|
||||
# IO
|
||||
# -----------------------------
|
||||
def read_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if line.strip():
|
||||
try:
|
||||
yield json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
def ensure_dir(p: Path):
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# -----------------------------
|
||||
# Text helpers
|
||||
# -----------------------------
|
||||
def pick_text(rec: Dict[str, Any]) -> str:
|
||||
return rec.get("text") or rec.get("content") or rec.get("body") or ""
|
||||
|
||||
def first_sentences(s: str, max_chars: int = 500) -> str:
|
||||
s = (s or "").strip()
|
||||
if not s:
|
||||
return ""
|
||||
# cheap sentence-ish split
|
||||
parts = re.split(r"(?<=[\.\!\?])\s+", s)
|
||||
out = []
|
||||
total = 0
|
||||
for p in parts:
|
||||
if not p:
|
||||
continue
|
||||
out.append(p)
|
||||
total += len(p) + 1
|
||||
if total >= max_chars:
|
||||
break
|
||||
joined = " ".join(out).strip()
|
||||
return joined[:max_chars].rstrip()
|
||||
|
||||
def chunk_text(txt: str, target_chars: int = 2500, overlap_chars: int = 200) -> Iterable[str]:
|
||||
# paragraph-first greedy pack
|
||||
paras = [p.strip() for p in (txt or "").split("\n\n") if p.strip()]
|
||||
if not paras:
|
||||
if txt.strip():
|
||||
yield from _split_oversized_text(txt.strip(), target_chars, overlap_chars)
|
||||
return
|
||||
buf, size = [], 0
|
||||
for p in paras:
|
||||
if len(p) > target_chars:
|
||||
if buf:
|
||||
yield "\n\n".join(buf)
|
||||
buf, size = [], 0
|
||||
yield from _split_oversized_text(p, target_chars, overlap_chars)
|
||||
continue
|
||||
if size + len(p) + 2 > target_chars and buf:
|
||||
chunk = "\n\n".join(buf)
|
||||
yield chunk
|
||||
if overlap_chars > 0 and len(chunk) > overlap_chars:
|
||||
tail = chunk[-overlap_chars:]
|
||||
buf, size = [tail], len(tail)
|
||||
else:
|
||||
buf, size = [], 0
|
||||
buf.append(p)
|
||||
size += len(p) + 2
|
||||
if buf:
|
||||
yield "\n\n".join(buf)
|
||||
|
||||
def _split_oversized_text(txt: str, target_chars: int, overlap_chars: int) -> Iterable[str]:
|
||||
clean = (txt or "").strip()
|
||||
target = max(400, int(target_chars))
|
||||
overlap = min(max(0, int(overlap_chars)), target // 3)
|
||||
start = 0
|
||||
while start < len(clean):
|
||||
limit = min(len(clean), start + target)
|
||||
end = limit
|
||||
if limit < len(clean):
|
||||
search_from = start + max(1, target // 2)
|
||||
whitespace = max(clean.rfind(" ", search_from, limit), clean.rfind("\n", search_from, limit))
|
||||
if whitespace > start:
|
||||
end = whitespace
|
||||
chunk = clean[start:end].strip()
|
||||
if chunk:
|
||||
yield chunk
|
||||
if end >= len(clean):
|
||||
break
|
||||
start = max(start + 1, end - overlap)
|
||||
|
||||
def clamp_int(value: int, low: int, high: int) -> int:
|
||||
return max(low, min(high, value))
|
||||
|
||||
def sample_evenly_spaced_chunks(chunks: List[str], target_count: int) -> List[str]:
|
||||
if target_count <= 0 or len(chunks) <= target_count:
|
||||
return chunks
|
||||
if target_count == 1:
|
||||
return [chunks[len(chunks) // 2]]
|
||||
|
||||
last = len(chunks) - 1
|
||||
step = last / float(target_count - 1)
|
||||
picked: List[str] = []
|
||||
seen = set()
|
||||
for idx in range(target_count):
|
||||
source_idx = int(round(idx * step))
|
||||
source_idx = clamp_int(source_idx, 0, last)
|
||||
while source_idx in seen and source_idx < last:
|
||||
source_idx += 1
|
||||
if source_idx in seen:
|
||||
source_idx = max(i for i in range(last + 1) if i not in seen)
|
||||
seen.add(source_idx)
|
||||
picked.append(chunks[source_idx])
|
||||
return picked
|
||||
|
||||
def plan_content_chunking(
|
||||
txt: str,
|
||||
target_chars: int,
|
||||
overlap_chars: int,
|
||||
*,
|
||||
baseline_chunks: Optional[int] = None,
|
||||
) -> Dict[str, int | bool | str]:
|
||||
clean = (txt or "").strip()
|
||||
text_len = len(clean)
|
||||
base_target = max(400, int(target_chars))
|
||||
base_overlap = max(0, int(overlap_chars))
|
||||
baseline_chunk_count = baseline_chunks
|
||||
if baseline_chunk_count is None:
|
||||
baseline_chunk_count = max(1, math.ceil(text_len / max(1, base_target))) if text_len else 1
|
||||
|
||||
adaptive = baseline_chunk_count > 24
|
||||
chunk_budget = baseline_chunk_count
|
||||
planned_target = base_target
|
||||
sampling_fallback = False
|
||||
|
||||
if adaptive:
|
||||
chunk_budget = min(
|
||||
baseline_chunk_count,
|
||||
max(24, math.ceil(3.5 * math.sqrt(baseline_chunk_count))),
|
||||
)
|
||||
planned_target = math.ceil(text_len / max(1, chunk_budget)) if text_len else base_target
|
||||
|
||||
max_target = max(base_target, base_target * 8)
|
||||
if planned_target > max_target:
|
||||
planned_target = max_target
|
||||
sampling_fallback = adaptive
|
||||
|
||||
planned_target = clamp_int(planned_target, base_target, max_target)
|
||||
planned_overlap = min(base_overlap, max(0, planned_target // 12))
|
||||
|
||||
return {
|
||||
"doc_chars": text_len,
|
||||
"baseline_chunks": baseline_chunk_count,
|
||||
"chunk_budget": chunk_budget,
|
||||
"target_chars": planned_target,
|
||||
"overlap_chars": planned_overlap,
|
||||
"adaptive": adaptive,
|
||||
"sampling_fallback": sampling_fallback,
|
||||
"mode": "adaptive" if adaptive else "fixed",
|
||||
}
|
||||
|
||||
def chunk_text_for_index(txt: str, target_chars: int, overlap_chars: int) -> Tuple[List[str], Dict[str, int | bool | str]]:
|
||||
clean = (txt or "").strip()
|
||||
if not clean:
|
||||
return [], {
|
||||
"doc_chars": 0,
|
||||
"baseline_chunks": 0,
|
||||
"chunk_budget": 0,
|
||||
"target_chars": max(400, int(target_chars)),
|
||||
"overlap_chars": max(0, int(overlap_chars)),
|
||||
"adaptive": False,
|
||||
"sampling_fallback": False,
|
||||
"mode": "fixed",
|
||||
"chunks_indexed": 0,
|
||||
"chunks_saved": 0,
|
||||
}
|
||||
|
||||
base_target = max(400, int(target_chars))
|
||||
base_overlap = max(0, int(overlap_chars))
|
||||
baseline_chunks = list(chunk_text(clean, base_target, base_overlap))
|
||||
plan = plan_content_chunking(
|
||||
clean,
|
||||
target_chars,
|
||||
overlap_chars,
|
||||
baseline_chunks=len(baseline_chunks),
|
||||
)
|
||||
|
||||
if not plan["adaptive"]:
|
||||
chunks = baseline_chunks
|
||||
else:
|
||||
chunks = list(
|
||||
chunk_text(
|
||||
clean,
|
||||
int(plan["target_chars"]),
|
||||
int(plan["overlap_chars"]),
|
||||
)
|
||||
)
|
||||
|
||||
if plan["adaptive"] and len(chunks) > int(plan["chunk_budget"]):
|
||||
chunks = sample_evenly_spaced_chunks(chunks, int(plan["chunk_budget"]))
|
||||
plan["mode"] = "adaptive-sampled"
|
||||
|
||||
plan["chunks_indexed"] = len(chunks)
|
||||
plan["chunks_saved"] = max(0, int(plan["baseline_chunks"]) - len(chunks))
|
||||
return chunks, plan
|
||||
|
||||
def norm_f32(mat: np.ndarray) -> np.ndarray:
|
||||
mat = np.asarray(mat, dtype="float32")
|
||||
norms = np.linalg.norm(mat, axis=1, keepdims=True)
|
||||
norms[norms == 0] = 1.0
|
||||
return mat / norms
|
||||
|
||||
# -----------------------------
|
||||
# Embedding
|
||||
# -----------------------------
|
||||
def embed_many(ollama_url: str, model: str, texts: List[str], *, concurrency: int = 4, timeout: int = 120, on_progress=None) -> List[np.ndarray]:
|
||||
if not texts:
|
||||
return []
|
||||
|
||||
resolved_model, first_vec = resolve_embed_model(
|
||||
ollama_url,
|
||||
model,
|
||||
probe_text=texts[0],
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def _embed_one(t: str) -> np.ndarray:
|
||||
vec = request_embedding(ollama_url, resolved_model, t, timeout=timeout)
|
||||
return np.array(vec, dtype="float32")
|
||||
|
||||
out: List[Optional[np.ndarray]] = [None] * len(texts)
|
||||
out[0] = np.array(first_vec, dtype="float32")
|
||||
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:
|
||||
futures = {ex.submit(_embed_one, t): i for i, t in enumerate(texts[1:], start=1)}
|
||||
|
||||
progress_bar = None
|
||||
if on_progress is None and 'tqdm' in globals() and tqdm is not None:
|
||||
progress_bar = tqdm(as_completed(futures), total=len(futures), desc=f"embed:{resolved_model}")
|
||||
|
||||
iterator = progress_bar if progress_bar else as_completed(futures)
|
||||
|
||||
count = 1
|
||||
for fut in iterator:
|
||||
i = futures[fut]
|
||||
out[i] = fut.result()
|
||||
count += 1
|
||||
if on_progress:
|
||||
on_progress("embed", count / len(texts), f"Embedding {count}/{len(texts)}")
|
||||
|
||||
# type: ignore
|
||||
return out # List[np.ndarray]
|
||||
|
||||
# -----------------------------
|
||||
# Meta helpers
|
||||
# -----------------------------
|
||||
def derive_doc_id_from_any(any_id: Optional[str], parent_id: Optional[str]) -> str:
|
||||
"""Prefer parent_id if present (file-level), else base of 'id' before '#...'."""
|
||||
if parent_id:
|
||||
return str(parent_id)
|
||||
if not any_id:
|
||||
return ""
|
||||
return any_id.split("#", 1)[0]
|
||||
|
||||
def kind_from_rec(rec: Dict[str, Any]) -> str:
|
||||
rt = (rec.get("record_type") or "").lower()
|
||||
mime = (rec.get("mime") or "").lower()
|
||||
if rt == "image" or (mime.startswith("image/")):
|
||||
return "image"
|
||||
if rt == "av" or mime.startswith(("audio/", "video/")):
|
||||
return "av"
|
||||
if "html" in mime or rt in {"html-section"}:
|
||||
return "html"
|
||||
if "pdf" in mime or rt == "page":
|
||||
return "pdf"
|
||||
if rt == "code-summary" or mime.startswith("text/x-code"):
|
||||
return "code"
|
||||
return rt or "file"
|
||||
|
||||
# -----------------------------
|
||||
# Shadow text synthesis (fallbacks)
|
||||
# -----------------------------
|
||||
def synth_shadow_from_enhanced(rec: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Build a compact shadow_text from enriched fields if present.
|
||||
"""
|
||||
parts: List[str] = []
|
||||
h = (rec.get("headline") or rec.get("title") or "").strip()
|
||||
s = (rec.get("summary") or "").strip()
|
||||
kws = rec.get("keywords") or []
|
||||
ents = rec.get("entities") or []
|
||||
qas = rec.get("qa") or []
|
||||
|
||||
if h:
|
||||
parts.append(f"headline: {h}")
|
||||
if s:
|
||||
parts.append(f"summary: {s}")
|
||||
if kws:
|
||||
parts.append("keywords: " + ", ".join([str(k).strip() for k in kws if str(k).strip()]))
|
||||
if ents:
|
||||
uniq = {}
|
||||
for e in ents:
|
||||
if not isinstance(e, dict):
|
||||
continue
|
||||
name = (e.get("name") or "").strip()
|
||||
typ = (e.get("type") or "OTHER").strip().upper()
|
||||
if name and name.lower() not in uniq:
|
||||
uniq[name.lower()] = (name, typ)
|
||||
if uniq:
|
||||
parts.append("entities: " + "; ".join(f"{n} [{t}]" for n, t in uniq.values()))
|
||||
if qas:
|
||||
qa_lines = []
|
||||
for qa in qas[:4]:
|
||||
if not isinstance(qa, dict):
|
||||
continue
|
||||
q = (qa.get("q") or "").strip()
|
||||
a = (qa.get("a") or "").strip()
|
||||
if q and a:
|
||||
qa_lines.append(f"Q: {q}\nA: {a}")
|
||||
if qa_lines:
|
||||
parts.append("qa:\n" + "\n".join(qa_lines))
|
||||
return "\n".join(parts).strip()
|
||||
|
||||
def synth_shadow_from_raw(rec: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Build a proxy shadow_text without any LLM: title + first sentences + light hints.
|
||||
"""
|
||||
title = (rec.get("title") or "").strip()
|
||||
text = pick_text(rec)
|
||||
kind = kind_from_rec(rec)
|
||||
url = rec.get("url") or rec.get("source_path") or ""
|
||||
head = f"headline: {title}" if title else ""
|
||||
summary = first_sentences(text, 500)
|
||||
parts = []
|
||||
if head:
|
||||
parts.append(head)
|
||||
if summary:
|
||||
parts.append(f"summary: {summary}")
|
||||
hints = []
|
||||
if kind:
|
||||
hints.append(kind)
|
||||
if rec.get("mime"):
|
||||
hints.append(rec.get("mime").split(";")[0])
|
||||
if url:
|
||||
hints.append(Path(url).name)
|
||||
if hints:
|
||||
parts.append("keywords: " + ", ".join(hints))
|
||||
return "\n".join(parts).strip()
|
||||
|
||||
# -----------------------------
|
||||
# Builders
|
||||
# -----------------------------
|
||||
def build_shadow_any(
|
||||
shadow_jsonl: Optional[Path],
|
||||
enhanced_jsonl: Optional[Path],
|
||||
raw_jsonl: Optional[Path],
|
||||
out_index: Path,
|
||||
out_meta: Path,
|
||||
*,
|
||||
ollama: str,
|
||||
model: str,
|
||||
concurrency: int
|
||||
) -> Tuple[int, int, int]:
|
||||
"""
|
||||
Build FAISS over shadow_text from best available source.
|
||||
Priority: shadow_jsonl > enhanced_jsonl (synth) > raw_jsonl (synth).
|
||||
Returns (n_input_records, n_indexed, dim)
|
||||
"""
|
||||
src_records: List[Dict[str, Any]] = []
|
||||
mode = ""
|
||||
if shadow_jsonl and shadow_jsonl.exists():
|
||||
src_records = list(read_jsonl(shadow_jsonl))
|
||||
mode = "shadow"
|
||||
elif enhanced_jsonl and enhanced_jsonl.exists():
|
||||
src_records = list(read_jsonl(enhanced_jsonl))
|
||||
mode = "enhanced->shadow"
|
||||
elif raw_jsonl and raw_jsonl.exists():
|
||||
src_records = list(read_jsonl(raw_jsonl))
|
||||
mode = "raw->shadow"
|
||||
else:
|
||||
raise SystemExit("[ERR] No input for shadow index (need --shadow OR --enhanced OR --raw).")
|
||||
|
||||
if not src_records:
|
||||
raise SystemExit("[ERR] Empty input for shadow index.")
|
||||
|
||||
texts: List[str] = []
|
||||
metas: List[Dict[str, Any]] = []
|
||||
for rec in src_records:
|
||||
if mode == "shadow":
|
||||
st = rec.get("shadow_text") or ""
|
||||
elif mode == "enhanced->shadow":
|
||||
st = synth_shadow_from_enhanced(rec)
|
||||
else:
|
||||
st = synth_shadow_from_raw(rec)
|
||||
|
||||
if not st.strip():
|
||||
continue
|
||||
|
||||
record_id = rec.get("id") or rec.get("record_id") or str(uuid.uuid4())
|
||||
doc_id = derive_doc_id_from_any(record_id, rec.get("parent_id"))
|
||||
|
||||
meta = {
|
||||
"id": None, # numeric FAISS id later
|
||||
"record_id": record_id,
|
||||
"doc_id": doc_id,
|
||||
"title": rec.get("title"),
|
||||
"url": rec.get("url") or rec.get("source_path"),
|
||||
"record_type": rec.get("record_type"),
|
||||
"mime": rec.get("mime"),
|
||||
"lang": rec.get("lang"),
|
||||
"kind": kind_from_rec(rec),
|
||||
"shadow_text": st,
|
||||
}
|
||||
metas.append(meta)
|
||||
texts.append(st)
|
||||
|
||||
if not texts:
|
||||
raise SystemExit("[ERR] no shadow_text to embed")
|
||||
|
||||
vecs = embed_many(ollama, model, texts, concurrency=concurrency)
|
||||
d = len(vecs[0])
|
||||
mat = norm_f32(np.vstack(vecs))
|
||||
|
||||
base = faiss.IndexFlatIP(d)
|
||||
index = faiss.IndexIDMap2(base)
|
||||
|
||||
out_meta.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out_meta, "w", encoding="utf-8") as mf:
|
||||
buf_vecs, buf_ids = [], []
|
||||
next_id = 0
|
||||
for m, v in zip(metas, mat):
|
||||
m["id"] = next_id
|
||||
mf.write(json.dumps(m, ensure_ascii=False) + "\n")
|
||||
buf_vecs.append(v)
|
||||
buf_ids.append(next_id)
|
||||
next_id += 1
|
||||
if len(buf_vecs) >= 512:
|
||||
index.add_with_ids(np.vstack(buf_vecs), np.array(buf_ids, dtype="int64"))
|
||||
buf_vecs, buf_ids = [], []
|
||||
if buf_vecs:
|
||||
index.add_with_ids(np.vstack(buf_vecs), np.array(buf_ids, dtype="int64"))
|
||||
|
||||
faiss.write_index(index, str(out_index))
|
||||
return (len(src_records), index.ntotal, d)
|
||||
|
||||
def build_content_any(
|
||||
enhanced_jsonl: Optional[Path],
|
||||
raw_jsonl: Optional[Path],
|
||||
out_index: Path,
|
||||
out_meta: Path,
|
||||
*,
|
||||
ollama: str,
|
||||
model: str,
|
||||
target_chars: int,
|
||||
overlap_chars: int,
|
||||
concurrency: int
|
||||
) -> Tuple[int, int, int, Dict[str, Any]]:
|
||||
"""
|
||||
Build FAISS over chunked 'text' from best available source.
|
||||
Priority: enhanced_jsonl > raw_jsonl.
|
||||
Returns (n_input_records, n_chunks, dim)
|
||||
"""
|
||||
src_records: List[Dict[str, Any]] = []
|
||||
mode = ""
|
||||
if enhanced_jsonl and enhanced_jsonl.exists():
|
||||
src_records = list(read_jsonl(enhanced_jsonl))
|
||||
mode = "enhanced"
|
||||
elif raw_jsonl and raw_jsonl.exists():
|
||||
src_records = list(read_jsonl(raw_jsonl))
|
||||
mode = "raw"
|
||||
else:
|
||||
raise SystemExit("[ERR] No input for content index (need --enhanced OR --raw).")
|
||||
|
||||
metas: List[Dict[str, Any]] = []
|
||||
texts: List[str] = []
|
||||
stats: Dict[str, Any] = {
|
||||
"docs_with_text": 0,
|
||||
"adaptive_docs": 0,
|
||||
"sampled_docs": 0,
|
||||
"baseline_chunks": 0,
|
||||
"chunks_indexed": 0,
|
||||
"chunks_saved": 0,
|
||||
"max_doc_chunks": 0,
|
||||
"max_doc_chars": 0,
|
||||
}
|
||||
for rec in src_records:
|
||||
base_text = pick_text(rec)
|
||||
if not base_text.strip():
|
||||
continue
|
||||
record_id = rec.get("id") or rec.get("record_id") or str(uuid.uuid4())
|
||||
doc_id = derive_doc_id_from_any(record_id, rec.get("parent_id"))
|
||||
title = rec.get("title")
|
||||
url = rec.get("url") or rec.get("source_path")
|
||||
|
||||
chunks, chunk_plan = chunk_text_for_index(base_text, target_chars, overlap_chars)
|
||||
if not chunks:
|
||||
continue
|
||||
stats["docs_with_text"] += 1
|
||||
stats["baseline_chunks"] += int(chunk_plan["baseline_chunks"])
|
||||
stats["chunks_indexed"] += len(chunks)
|
||||
stats["chunks_saved"] += int(chunk_plan["chunks_saved"])
|
||||
stats["max_doc_chunks"] = max(stats["max_doc_chunks"], len(chunks))
|
||||
stats["max_doc_chars"] = max(stats["max_doc_chars"], int(chunk_plan["doc_chars"]))
|
||||
if chunk_plan["adaptive"]:
|
||||
stats["adaptive_docs"] += 1
|
||||
if chunk_plan["mode"] == "adaptive-sampled":
|
||||
stats["sampled_docs"] += 1
|
||||
for ci, chunk in enumerate(chunks):
|
||||
meta = {
|
||||
"id": None, # numeric FAISS id later
|
||||
"doc_id": doc_id,
|
||||
"record_id": record_id,
|
||||
"chunk_no": ci,
|
||||
"doc_chunk_count": len(chunks),
|
||||
"doc_chars": int(chunk_plan["doc_chars"]),
|
||||
"chunk_target_chars": int(chunk_plan["target_chars"]),
|
||||
"chunk_overlap_chars": int(chunk_plan["overlap_chars"]),
|
||||
"chunking_mode": chunk_plan["mode"],
|
||||
"title": title,
|
||||
"url": url,
|
||||
"text": chunk,
|
||||
"record_type": rec.get("record_type"),
|
||||
"mime": rec.get("mime"),
|
||||
"lang": rec.get("lang"),
|
||||
}
|
||||
metas.append(meta)
|
||||
texts.append(chunk)
|
||||
|
||||
if not texts:
|
||||
raise SystemExit("[ERR] no content chunks to embed")
|
||||
|
||||
vecs = embed_many(ollama, model, texts, concurrency=concurrency)
|
||||
d = len(vecs[0])
|
||||
mat = norm_f32(np.vstack(vecs))
|
||||
|
||||
base = faiss.IndexFlatIP(d)
|
||||
index = faiss.IndexIDMap2(base)
|
||||
|
||||
out_meta.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out_meta, "w", encoding="utf-8") as mf:
|
||||
buf_vecs, buf_ids = [], []
|
||||
next_id = 0
|
||||
for m, v in zip(metas, mat):
|
||||
m["id"] = next_id
|
||||
mf.write(json.dumps(m, ensure_ascii=False) + "\n")
|
||||
buf_vecs.append(v)
|
||||
buf_ids.append(next_id)
|
||||
next_id += 1
|
||||
if len(buf_vecs) >= 512:
|
||||
index.add_with_ids(np.vstack(buf_vecs), np.array(buf_ids, dtype="int64"))
|
||||
buf_vecs, buf_ids = [], []
|
||||
if buf_vecs:
|
||||
index.add_with_ids(np.vstack(buf_vecs), np.array(buf_ids, dtype="int64"))
|
||||
|
||||
faiss.write_index(index, str(out_index))
|
||||
return (len(src_records), index.ntotal, d, stats)
|
||||
|
||||
# -----------------------------
|
||||
# CLI
|
||||
# -----------------------------
|
||||
def run_index(raw: Path|None, enhanced: Path|None, shadow: Path|None, out_dir: Path, *,
|
||||
on_progress=None, **opts) -> dict:
|
||||
|
||||
args = argparse.Namespace(
|
||||
raw=raw,
|
||||
enhanced=enhanced,
|
||||
shadow=shadow,
|
||||
out_dir=out_dir,
|
||||
embed_model=opts.get("embed_model", "bge-m3:latest"),
|
||||
ollama=opts.get("ollama", "http://localhost:11434"),
|
||||
target_chars=opts.get("target_chars", 2500),
|
||||
overlap_chars=opts.get("overlap_chars", 200),
|
||||
concurrency=opts.get("concurrency", 6),
|
||||
no_shadow=opts.get("no_shadow", False),
|
||||
no_content=opts.get("no_content", False),
|
||||
)
|
||||
|
||||
ensure_dir(out_dir)
|
||||
resolved_model, _ = resolve_embed_model(args.ollama, args.embed_model)
|
||||
|
||||
shadow_index_path = out_dir / "shadow.index.faiss"
|
||||
shadow_meta_path = out_dir / "shadow.meta.jsonl"
|
||||
content_index_path = out_dir / "content.index.faiss"
|
||||
content_meta_path = out_dir / "content.meta.jsonl"
|
||||
|
||||
results = {}
|
||||
built_any = False
|
||||
|
||||
if not args.no_shadow:
|
||||
if on_progress: on_progress("shadow", 0.1, "Building shadow index...")
|
||||
s_tot, s_ix, s_dim = build_shadow_any(
|
||||
args.shadow, args.enhanced, args.raw,
|
||||
shadow_index_path, shadow_meta_path,
|
||||
ollama=args.ollama, model=resolved_model, concurrency=args.concurrency
|
||||
)
|
||||
results["shadow"] = {"records": s_tot, "indexed": s_ix, "dim": s_dim}
|
||||
if on_progress: on_progress("shadow", 0.5, "Shadow index complete.")
|
||||
built_any = True
|
||||
|
||||
if not args.no_content:
|
||||
if on_progress: on_progress("content", 0.6, "Building content index...")
|
||||
c_tot, c_ix, c_dim, c_stats = build_content_any(
|
||||
args.enhanced, args.raw,
|
||||
content_index_path, content_meta_path,
|
||||
ollama=args.ollama, model=resolved_model,
|
||||
target_chars=args.target_chars, overlap_chars=args.overlap_chars,
|
||||
concurrency=args.concurrency
|
||||
)
|
||||
results["content"] = {"records": c_tot, "chunks": c_ix, "dim": c_dim, **c_stats}
|
||||
if on_progress: on_progress("content", 0.9, "Content index complete.")
|
||||
built_any = True
|
||||
|
||||
if not built_any:
|
||||
return {"status": "warning", "message": "Nothing built."}
|
||||
|
||||
if on_progress: on_progress("done", 1.0, "Indexing complete.")
|
||||
return {"status": "ok", "results": results, "embed_model": resolved_model}
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Build FAISS indexes (shadow + content) for hybrid RAG with or without enrichment.")
|
||||
ap.add_argument("--raw", help="Raw corpus JSONL (from 01_corpus_builder.py)")
|
||||
ap.add_argument("--enhanced", help="Enhanced corpus JSONL (from 02_corpus_enricher.py)")
|
||||
ap.add_argument("--shadow", help="Shadow corpus JSONL (from 02_corpus_enricher.py)")
|
||||
ap.add_argument("--out-dir", default="indexes", help="Output directory for indexes + metadata")
|
||||
ap.add_argument("--embed-model", default="bge-m3:latest", help="Ollama embedding model")
|
||||
ap.add_argument("--ollama", default="http://localhost:11434", help="Ollama base URL")
|
||||
ap.add_argument("--target-chars", type=int, default=2500, help="Chunk size for content index")
|
||||
ap.add_argument("--overlap-chars", type=int, default=200, help="Overlap size for content index")
|
||||
ap.add_argument("--concurrency", type=int, default=6, help="Parallel HTTP workers for embeddings")
|
||||
ap.add_argument("--no-shadow", action="store_true", help="Do not build shadow index")
|
||||
ap.add_argument("--no-content", action="store_true", help="Do not build content index")
|
||||
args = ap.parse_args()
|
||||
|
||||
run_index(
|
||||
Path(args.raw) if args.raw else None,
|
||||
Path(args.enhanced) if args.enhanced else None,
|
||||
Path(args.shadow) if args.shadow else None,
|
||||
Path(args.out_dir),
|
||||
on_progress=lambda p, pct, d: print(f"[{p}] {pct*100:.1f}%: {d}"),
|
||||
**vars(args)
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
97
backend/rag/ollama_embeddings.py
Normal file
97
backend/rag/ollama_embeddings.py
Normal file
@@ -0,0 +1,97 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Iterable, List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
DEFAULT_EMBED_CANDIDATES = (
|
||||
"nomic-embed-text:latest",
|
||||
"bge-m3:latest",
|
||||
"dengcao/Qwen3-Embedding-0.6B:F16",
|
||||
)
|
||||
|
||||
_MODEL_CACHE: Dict[Tuple[str, str], str] = {}
|
||||
|
||||
|
||||
def _cache_key(ollama_url: str, preferred_model: Optional[str]) -> Tuple[str, str]:
|
||||
return (ollama_url.rstrip("/"), str(preferred_model or "").strip())
|
||||
|
||||
|
||||
def _candidate_models(preferred_model: Optional[str]) -> List[str]:
|
||||
out: List[str] = []
|
||||
seen = set()
|
||||
if preferred_model:
|
||||
primary = str(preferred_model).strip()
|
||||
candidates = [primary]
|
||||
if primary.endswith(":latest"):
|
||||
candidates.append(primary[:-7])
|
||||
else:
|
||||
candidates.append(f"{primary}:latest")
|
||||
else:
|
||||
candidates = list(DEFAULT_EMBED_CANDIDATES)
|
||||
|
||||
for model in candidates:
|
||||
name = str(model or "").strip()
|
||||
if not name or name in seen:
|
||||
continue
|
||||
out.append(name)
|
||||
seen.add(name)
|
||||
return out
|
||||
|
||||
|
||||
def _response_error_text(response: requests.Response) -> str:
|
||||
try:
|
||||
payload = response.json()
|
||||
except Exception:
|
||||
payload = None
|
||||
if isinstance(payload, dict):
|
||||
message = str(payload.get("error") or "").strip()
|
||||
if message:
|
||||
return message
|
||||
return (response.text or f"HTTP {response.status_code}").strip()
|
||||
|
||||
|
||||
def request_embedding(ollama_url: str, model: str, text: str, *, timeout: int = 120) -> List[float]:
|
||||
response = requests.post(
|
||||
f"{ollama_url.rstrip('/')}/api/embeddings",
|
||||
json={"model": model, "prompt": text},
|
||||
timeout=timeout,
|
||||
)
|
||||
if not response.ok:
|
||||
raise RuntimeError(f"{model}: {_response_error_text(response)}")
|
||||
|
||||
data = response.json()
|
||||
vec = data.get("embedding") or (data.get("embeddings") or [None])[0]
|
||||
if vec is None:
|
||||
raise RuntimeError(f"{model}: Ollama returned no embedding vector")
|
||||
return vec
|
||||
|
||||
|
||||
def resolve_embed_model(
|
||||
ollama_url: str,
|
||||
preferred_model: Optional[str],
|
||||
*,
|
||||
probe_text: str = "embedding probe",
|
||||
timeout: int = 120,
|
||||
) -> Tuple[str, List[float]]:
|
||||
key = _cache_key(ollama_url, preferred_model)
|
||||
cached = _MODEL_CACHE.get(key)
|
||||
if cached:
|
||||
try:
|
||||
return cached, request_embedding(ollama_url, cached, probe_text, timeout=timeout)
|
||||
except Exception:
|
||||
_MODEL_CACHE.pop(key, None)
|
||||
|
||||
errors: List[str] = []
|
||||
for model in _candidate_models(preferred_model):
|
||||
try:
|
||||
vector = request_embedding(ollama_url, model, probe_text, timeout=timeout)
|
||||
_MODEL_CACHE[key] = model
|
||||
return model, vector
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
|
||||
tried = ", ".join(_candidate_models(preferred_model)) or "(none)"
|
||||
detail = "; ".join(errors) if errors else "no candidate models were available"
|
||||
raise RuntimeError(f"No working Ollama embedding model found. Tried: {tried}. {detail}")
|
||||
688
backend/rag/unified_rag.py
Normal file
688
backend/rag/unified_rag.py
Normal file
@@ -0,0 +1,688 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
04_unified_rag.py
|
||||
|
||||
Hybrid retrieval + (optional) rerank + (optional) answer generation.
|
||||
|
||||
Now supports:
|
||||
- HYBRID: shadow+content indexes (best quality)
|
||||
- SINGLE-INDEX:
|
||||
* legacy pair (--index/--store) ← back-compat
|
||||
* content-only pair (--content-index/--content-store)
|
||||
* shadow-only pair (--shadow-index/--shadow-store)
|
||||
|
||||
If you skipped enrichment:
|
||||
- Build only content + proxy shadow with 03_index_builder.py (raw → content; raw/enhanced→proxy shadow)
|
||||
- Query with:
|
||||
* HYBRID: provide both pairs
|
||||
* SINGLE-INDEX: provide only one pair (content OR shadow)
|
||||
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse, json, os, sys, subprocess, math
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Tuple, Optional
|
||||
|
||||
import faiss
|
||||
import numpy as np
|
||||
import requests
|
||||
import threading
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from backend.rag.ollama_embeddings import resolve_embed_model
|
||||
except ModuleNotFoundError:
|
||||
from .ollama_embeddings import resolve_embed_model
|
||||
|
||||
# -----------------------------
|
||||
# Utilities
|
||||
# -----------------------------
|
||||
def norm_f32(mat: np.ndarray) -> np.ndarray:
|
||||
mat = np.asarray(mat, dtype="float32")
|
||||
norms = np.linalg.norm(mat, axis=1, keepdims=True)
|
||||
norms[norms == 0] = 1.0
|
||||
return mat / norms
|
||||
|
||||
def zscore(x: List[float]) -> List[float]:
|
||||
if not x:
|
||||
return []
|
||||
mu = float(np.mean(x))
|
||||
sd = float(np.std(x))
|
||||
if sd == 0.0:
|
||||
return [0.0 for _ in x]
|
||||
return [(v - mu) / sd for v in x]
|
||||
|
||||
def sanitize(s: Optional[str]) -> str:
|
||||
if not s:
|
||||
return ""
|
||||
import re
|
||||
s = re.sub(r"<\s*think\s*>.*?<\s*/\s*think\s*>", "", s, flags=re.S|re.I)
|
||||
s = re.sub(r"^\s*```(?:\w+)?\s*|\s*```\s*$", "", s, flags=re.M)
|
||||
s = re.sub(r"[ \t]+", " ", s)
|
||||
s = re.sub(r"\n{3,}", "\n\n", s)
|
||||
return s.strip()
|
||||
|
||||
def pick_any_text(rec: Dict) -> str:
|
||||
"""Use 'text' if present else 'shadow_text' for rerank/answer/pretty."""
|
||||
return rec.get("text") or rec.get("shadow_text") or rec.get("content") or rec.get("body") or ""
|
||||
|
||||
def embed_query(ollama_url: str, model: str, text: str, timeout_s: int = 60) -> np.ndarray:
|
||||
resolved_model, vec = resolve_embed_model(
|
||||
ollama_url,
|
||||
model,
|
||||
probe_text=text,
|
||||
timeout=timeout_s,
|
||||
)
|
||||
return np.array(vec, dtype="float32")
|
||||
|
||||
def load_meta(store_path: str) -> Dict[int, Dict]:
|
||||
id2meta: Dict[int, Dict] = {}
|
||||
with open(store_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
rec = json.loads(line)
|
||||
id2meta[int(rec["id"])] = rec
|
||||
return id2meta
|
||||
|
||||
def truncate_text(s: Optional[str], limit: int) -> str:
|
||||
if not s:
|
||||
return ""
|
||||
return s if len(s) <= limit else s[:limit]
|
||||
|
||||
def derive_doc_id(rec: Dict) -> str:
|
||||
# Prefer explicit doc_id if provided by meta builder
|
||||
did = rec.get("doc_id")
|
||||
if did:
|
||||
return did
|
||||
rid = rec.get("record_id") or rec.get("id") or ""
|
||||
return rid.split("#", 1)[0]
|
||||
|
||||
# -----------------------------
|
||||
# Rerank (subprocess worker)
|
||||
# -----------------------------
|
||||
def sentence_transformers_available() -> bool:
|
||||
try:
|
||||
import importlib.util as _ilu
|
||||
spec = _ilu.find_spec("sentence_transformers")
|
||||
return spec is not None
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def rerank_subprocess(
|
||||
query: str,
|
||||
docs: List[str],
|
||||
*,
|
||||
worker_path: Path,
|
||||
model: str,
|
||||
device: str,
|
||||
dtype: str,
|
||||
batch: int,
|
||||
maxlen: int,
|
||||
) -> Optional[List[Tuple[int, float]]]:
|
||||
"""
|
||||
Call this same script with --mode rerank-worker via a clean Python subprocess.
|
||||
Returns: list of (local_index, score) sorted desc, or None on failure.
|
||||
"""
|
||||
payload = {"query": query, "docs": docs}
|
||||
cmd = [
|
||||
sys.executable,
|
||||
str(worker_path),
|
||||
"--mode", "rerank-worker",
|
||||
"--rerank-model", model,
|
||||
"--rerank-device", device,
|
||||
"--rerank-dtype", dtype,
|
||||
"--rerank-batch", str(batch),
|
||||
"--rerank-maxlen", str(maxlen),
|
||||
"--stdio"
|
||||
]
|
||||
env = os.environ.copy()
|
||||
env.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")
|
||||
env.setdefault("TOKENIZERS_PARALLELISM", "false")
|
||||
env.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
||||
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
input=json.dumps(payload).encode("utf-8"),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"[rerank] failed to launch worker: {e}\n")
|
||||
return None
|
||||
|
||||
if proc.returncode != 0:
|
||||
sys.stderr.write(proc.stderr.decode("utf-8", errors="ignore") + "\n")
|
||||
return None
|
||||
|
||||
try:
|
||||
data = json.loads(proc.stdout.decode("utf-8"))
|
||||
results = data.get("results") or []
|
||||
pairs = [(int(r["index"]), float(r["score"])) for r in results]
|
||||
pairs.sort(key=lambda x: x[1], reverse=True)
|
||||
return pairs
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"[rerank] parse error: {e}\n")
|
||||
return None
|
||||
|
||||
# -----------------------------
|
||||
# Simple diversity (per-source cap)
|
||||
# -----------------------------
|
||||
def apply_per_source_cap(ordered: List[Dict], per_source_limit: int) -> List[Dict]:
|
||||
if per_source_limit <= 0:
|
||||
return ordered
|
||||
counts = {}
|
||||
out = []
|
||||
for rec in ordered:
|
||||
key = rec.get("url") or rec.get("doc_id") or rec.get("title") or str(rec.get("id"))
|
||||
c = counts.get(key, 0)
|
||||
if c < per_source_limit:
|
||||
out.append(rec)
|
||||
counts[key] = c + 1
|
||||
return out
|
||||
|
||||
# -----------------------------
|
||||
# Generation
|
||||
# -----------------------------
|
||||
def generate(
|
||||
ollama_url: str,
|
||||
model: str,
|
||||
prompt: str,
|
||||
system: Optional[str] = None,
|
||||
temperature: float = 0.2,
|
||||
timeout_s: int = 180,
|
||||
on_stream=None,
|
||||
) -> str:
|
||||
payload = {"model": model, "prompt": prompt, "options": {"temperature": temperature}}
|
||||
if system:
|
||||
payload["system"] = system
|
||||
r = requests.post(f"{ollama_url.rstrip('/')}/api/generate", json=payload, timeout=timeout_s, stream=True)
|
||||
r.raise_for_status()
|
||||
out = []
|
||||
for chunk in r.iter_lines(decode_unicode=True):
|
||||
if not chunk:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(chunk)
|
||||
delta = obj.get("response", "")
|
||||
out.append(delta)
|
||||
if on_stream:
|
||||
on_stream({"delta": delta})
|
||||
if obj.get("done"):
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return sanitize("".join(out))
|
||||
|
||||
# -----------------------------
|
||||
# Search helpers
|
||||
# -----------------------------
|
||||
def faiss_search(index: faiss.Index, qvec: np.ndarray, k: int) -> Tuple[List[int], List[float]]:
|
||||
sims, ids = index.search(qvec, k)
|
||||
ids = [int(i) for i in ids[0] if i != -1]
|
||||
sims = [float(s) for s in sims[0][: len(ids)]]
|
||||
return ids, sims
|
||||
|
||||
# -----------------------------
|
||||
# Output / answer
|
||||
# -----------------------------
|
||||
def output_or_answer(final: List[Dict], args, on_stream=None):
|
||||
if not args.answer:
|
||||
# Return top-k results without generating an answer
|
||||
return {
|
||||
"done": True,
|
||||
"sources": [
|
||||
{
|
||||
"doc_id": rec.get("doc_id"),
|
||||
"title": rec.get("title"),
|
||||
"url": rec.get("url"),
|
||||
"record_type": rec.get("record_type"),
|
||||
"mime": rec.get("mime"),
|
||||
"lang": rec.get("lang"),
|
||||
"snippet": pick_any_text(rec),
|
||||
"scores": {
|
||||
"final": float(rec.get("_score", 0.0)),
|
||||
"shadow": float(rec.get("_shadow")) if rec.get("_shadow") is not None else None,
|
||||
"content": float(rec.get("_ann", 0.0)),
|
||||
"rerank": float(rec.get("_rerank")) if rec.get("_rerank") is not None else None,
|
||||
},
|
||||
}
|
||||
for rec in final
|
||||
],
|
||||
}
|
||||
|
||||
# Build prompt for answering
|
||||
context_blocks, sources = [], []
|
||||
for i, rec in enumerate(final, start=1):
|
||||
text = pick_any_text(rec)
|
||||
title = rec.get("title") or "(untitled)"
|
||||
url = rec.get("url") or title
|
||||
sources.append(f"[{i}] {url}")
|
||||
context_blocks.append(f"[{i}] {title}\n{text}")
|
||||
|
||||
system = (
|
||||
"You are a careful researcher. Answer ONLY from the provided sources. "
|
||||
"Cite like [1], [2] in-line. If the answer is not in the sources, say you can't find it. "
|
||||
"Do not include private chain-of-thought or <think> tags."
|
||||
)
|
||||
prompt = (
|
||||
f"Question: {args.query}\n\n"
|
||||
"Use the sources below. If not answerable from them, say so clearly.\n\n"
|
||||
"Sources:\n" + "\n\n".join(context_blocks) + "\n\n----\n\n"
|
||||
"Remember: only use these sources. Provide a concise answer with citations.\n\n"
|
||||
f"And again. The question you need to answer is: {args.query}"
|
||||
)
|
||||
|
||||
full_answer = generate(args.ollama, args.gen_model, prompt, system=system, temperature=args.temperature, on_stream=on_stream)
|
||||
|
||||
final_result = {
|
||||
"done": True,
|
||||
"answer": full_answer,
|
||||
"sources": [
|
||||
{
|
||||
"doc_id": rec.get("doc_id"),
|
||||
"title": rec.get("title"),
|
||||
"url": rec.get("url"),
|
||||
}
|
||||
for rec in final
|
||||
],
|
||||
}
|
||||
if on_stream:
|
||||
on_stream(final_result)
|
||||
|
||||
return final_result
|
||||
|
||||
# -----------------------------
|
||||
# Main CLI (search / answer)
|
||||
# -----------------------------
|
||||
def run_cli(args, on_stream=None):
|
||||
# Determine mode
|
||||
hybrid_ok = all([args.shadow_index, args.shadow_store, args.content_index, args.content_store])
|
||||
|
||||
single_pair: Optional[Tuple[str, str]] = None
|
||||
single_kind = None
|
||||
if not hybrid_ok:
|
||||
# Prefer legacy if provided
|
||||
if args.index and args.store:
|
||||
single_pair = (args.index, args.store)
|
||||
single_kind = "legacy"
|
||||
elif args.content_index and args.content_store:
|
||||
single_pair = (args.content_index, args.content_store)
|
||||
single_kind = "content"
|
||||
elif args.shadow_index and args.shadow_store:
|
||||
single_pair = (args.shadow_index, args.shadow_store)
|
||||
single_kind = "shadow"
|
||||
|
||||
# Embed query
|
||||
q = norm_f32(embed_query(args.ollama, args.embed_model, args.query).reshape(1, -1))
|
||||
|
||||
if single_pair:
|
||||
# SINGLE-INDEX path (works for legacy/content-only/shadow-only)
|
||||
index = faiss.read_index(single_pair[0])
|
||||
id2meta = load_meta(single_pair[1])
|
||||
|
||||
ids, sims = faiss_search(index, q, min(args.candidates, index.ntotal))
|
||||
candidates = []
|
||||
for pos, _id in enumerate(ids):
|
||||
base = id2meta[_id]
|
||||
rec = dict(base)
|
||||
rec["_ann"] = sims[pos]
|
||||
candidates.append(rec)
|
||||
|
||||
# Optional rerank
|
||||
reranked_scores = None
|
||||
if not args.no_rerank and sentence_transformers_available():
|
||||
docs = [truncate_text(pick_any_text(c), args.max_doc_chars) for c in candidates]
|
||||
pairs = rerank_subprocess(
|
||||
args.query, docs,
|
||||
worker_path=Path(__file__),
|
||||
model=args.rerank_model,
|
||||
device=args.rerank_device,
|
||||
dtype=args.rerank_dtype,
|
||||
batch=args.rerank_batch,
|
||||
maxlen=args.rerank_maxlen,
|
||||
)
|
||||
if pairs is not None:
|
||||
reranked_scores = [None] * len(candidates)
|
||||
for local_idx, score in pairs:
|
||||
if 0 <= local_idx < len(reranked_scores):
|
||||
reranked_scores[local_idx] = float(score)
|
||||
min_score = min([s for s in reranked_scores if s is not None], default=0.0)
|
||||
reranked_scores = [s if s is not None else min_score for s in reranked_scores]
|
||||
else:
|
||||
print("[info] rerank disabled (worker failed).", file=sys.stderr)
|
||||
|
||||
# Blend
|
||||
if reranked_scores is not None:
|
||||
z_ann = zscore([c["_ann"] for c in candidates])
|
||||
z_rr = zscore(reranked_scores)
|
||||
alpha = float(args.blend)
|
||||
final_scores = [(1 - alpha) * a + alpha * r for a, r in zip(z_ann, z_rr)]
|
||||
for rec, fs, rr in zip(candidates, final_scores, reranked_scores):
|
||||
rec["_score"] = float(fs)
|
||||
rec["_rerank"] = float(rr)
|
||||
candidates.sort(key=lambda r: r["_score"], reverse=True)
|
||||
else:
|
||||
for rec in candidates:
|
||||
rec["_score"] = rec["_ann"]
|
||||
|
||||
final = candidates[: max(1, min(args.k, len(candidates)))]
|
||||
return output_or_answer(final, args, on_stream=on_stream)
|
||||
|
||||
# HYBRID path
|
||||
shadow_index = faiss.read_index(args.shadow_index)
|
||||
shadow_meta = load_meta(args.shadow_store)
|
||||
content_index = faiss.read_index(args.content_index)
|
||||
content_meta = load_meta(args.content_store)
|
||||
|
||||
# Stage A: Shadow search → doc shortlist
|
||||
sid_list, s_sim = faiss_search(shadow_index, q, min(args.shadow_candidates, shadow_index.ntotal))
|
||||
s_hits = [{"id": sid, "sim": sim, **shadow_meta[sid]} for sid, sim in zip(sid_list, s_sim)]
|
||||
|
||||
# optional shadow weighting by kind
|
||||
kw = {}
|
||||
for kv in args.shadow_kind_weights.split(","):
|
||||
kv = kv.strip()
|
||||
if not kv:
|
||||
continue
|
||||
if ":" in kv:
|
||||
k, v = kv.split(":", 1)
|
||||
try:
|
||||
kw[k.strip().lower()] = float(v)
|
||||
except Exception:
|
||||
pass
|
||||
if kw:
|
||||
for h in s_hits:
|
||||
w = kw.get((h.get("kind") or "").lower(), 1.0)
|
||||
h["sim"] *= float(w)
|
||||
|
||||
# group to doc_id
|
||||
doc_scores: Dict[str, float] = {}
|
||||
for h in s_hits:
|
||||
did = derive_doc_id(h)
|
||||
doc_scores[did] = max(doc_scores.get(did, 0.0), float(h["sim"])) # max over shadow signals
|
||||
|
||||
# Stage B: Content search (global)
|
||||
cid_list, c_sim = faiss_search(content_index, q, min(args.content_candidates, content_index.ntotal))
|
||||
c_hits = [{"id": cid, "sim": sim, **content_meta[cid]} for cid, sim in zip(cid_list, c_sim)]
|
||||
|
||||
# Stage C: filter to doc shortlist
|
||||
ordered_docs = sorted(doc_scores.items(), key=lambda kv: kv[1], reverse=True)[: args.doc_top]
|
||||
if not ordered_docs:
|
||||
# Fallback: derive docs from top content hits
|
||||
tmp_docs = []
|
||||
seen = set()
|
||||
for h in c_hits:
|
||||
did = derive_doc_id(h)
|
||||
if did not in seen:
|
||||
seen.add(did)
|
||||
tmp_docs.append((did, float(h['sim'])))
|
||||
if len(tmp_docs) >= args.doc_top:
|
||||
break
|
||||
ordered_docs = tmp_docs
|
||||
shortlist = set([d for d, _ in ordered_docs])
|
||||
|
||||
# keep content hits belonging to shortlist (fallback to global if empty)
|
||||
content_for_docs = [h for h in c_hits if derive_doc_id(h) in shortlist] or c_hits
|
||||
|
||||
# per-doc cap
|
||||
per_doc = max(1, args.per_doc_chunks)
|
||||
doc_buckets: Dict[str, List[Dict]] = {}
|
||||
for h in content_for_docs:
|
||||
did = derive_doc_id(h)
|
||||
doc_buckets.setdefault(did, []).append(h)
|
||||
for did, arr in doc_buckets.items():
|
||||
arr.sort(key=lambda r: r["sim"], reverse=True)
|
||||
doc_buckets[did] = arr[:per_doc]
|
||||
|
||||
# flatten, compute final score as blend of shadow(doc) + content(chunk)
|
||||
out_candidates: List[Dict] = []
|
||||
for did, doc_sim in ordered_docs:
|
||||
for ch in doc_buckets.get(did, []):
|
||||
final = dict(ch)
|
||||
final["_shadow"] = float(doc_sim)
|
||||
final["_ann"] = float(ch["sim"])
|
||||
alpha = float(args.doc_blend) # weight of shadow
|
||||
beta = float(args.chunk_blend) # weight of chunk ann
|
||||
final["_score"] = alpha * float(doc_sim) + beta * float(ch["sim"])
|
||||
out_candidates.append(final)
|
||||
|
||||
if not out_candidates:
|
||||
print("No retrieval results.", file=sys.stderr)
|
||||
if args.answer:
|
||||
print("No results from retrieval; cannot answer.")
|
||||
return
|
||||
|
||||
out_candidates.sort(key=lambda r: r["_score"], reverse=True)
|
||||
|
||||
# Optional rerank of the first pool
|
||||
reranked_scores = None
|
||||
if not args.no_rerank and sentence_transformers_available():
|
||||
pool = out_candidates[: args.candidates]
|
||||
docs = [truncate_text(pick_any_text(c), args.max_doc_chars) for c in pool]
|
||||
pairs = rerank_subprocess(
|
||||
args.query, docs,
|
||||
worker_path=Path(__file__),
|
||||
model=args.rerank_model,
|
||||
device=args.rerank_device,
|
||||
dtype=args.rerank_dtype,
|
||||
batch=args.rerank_batch,
|
||||
maxlen=args.rerank_maxlen,
|
||||
)
|
||||
if pairs is not None:
|
||||
reranked_scores = [None] * len(pool)
|
||||
for local_idx, score in pairs:
|
||||
if 0 <= local_idx < len(pool):
|
||||
reranked_scores[local_idx] = float(score)
|
||||
min_score = min([s for s in reranked_scores if s is not None], default=0.0)
|
||||
reranked_scores = [s if s is not None else min_score for s in reranked_scores]
|
||||
z_ann = zscore([c["_score"] for c in pool])
|
||||
z_rr = zscore(reranked_scores)
|
||||
alpha = float(args.blend)
|
||||
blended = [(1 - alpha) * a + alpha * r for a, r in zip(z_ann, z_rr)]
|
||||
for rec, fs, rr in zip(pool, blended, reranked_scores):
|
||||
rec["_score"] = float(fs)
|
||||
rec["_rerank"] = float(rr)
|
||||
out_candidates[: len(pool)] = sorted(pool, key=lambda r: r["_score"], reverse=True)
|
||||
else:
|
||||
print("[info] rerank disabled (worker failed).", file=sys.stderr)
|
||||
|
||||
# per-source cap and top-k
|
||||
ordered = apply_per_source_cap(out_candidates, args.per_source_limit)
|
||||
final = ordered[: max(1, min(args.k, len(ordered)))]
|
||||
return output_or_answer(final, args, on_stream=on_stream)
|
||||
|
||||
# -----------------------------
|
||||
# Rerank worker mode
|
||||
# -----------------------------
|
||||
def run_rerank_worker(args):
|
||||
"""
|
||||
Reads JSON from stdin: {"query": str, "docs": [str, ...]}
|
||||
Writes JSON to stdout: {"results": [{"index": int, "score": float}, ...]}
|
||||
"""
|
||||
try:
|
||||
import torch
|
||||
from sentence_transformers import CrossEncoder
|
||||
except Exception as e:
|
||||
# Gracefully tell parent we failed by returning empty results
|
||||
out = {"results": []}
|
||||
json.dump(out, sys.stdout)
|
||||
sys.stdout.flush()
|
||||
print(f"[worker] sentence_transformers unavailable: {e}", file=sys.stderr)
|
||||
return
|
||||
|
||||
try:
|
||||
torch.set_num_threads(1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
device = args.rerank_device
|
||||
if device == "auto":
|
||||
device = "mps" if torch.backends.mps.is_available() else "cpu"
|
||||
|
||||
if args.rerank_dtype == "auto":
|
||||
dtype = torch.float16 if device == "mps" else torch.float32
|
||||
else:
|
||||
dtype = torch.float16 if args.rerank_dtype == "float16" else torch.float32
|
||||
|
||||
model = CrossEncoder(
|
||||
args.rerank_model,
|
||||
device=device,
|
||||
max_length=args.rerank_maxlen,
|
||||
automodel_args={"torch_dtype": dtype},
|
||||
)
|
||||
|
||||
data = json.load(sys.stdin)
|
||||
query = data["query"]
|
||||
docs = data["docs"]
|
||||
|
||||
pairs = [(query, d) for d in docs]
|
||||
scores = model.predict(
|
||||
pairs,
|
||||
batch_size=args.rerank_batch,
|
||||
convert_to_numpy=True,
|
||||
show_progress_bar=False,
|
||||
).tolist()
|
||||
|
||||
ordered = sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
|
||||
out = {"results": [{"index": int(i), "score": float(s)} for i, s in ordered]}
|
||||
json.dump(out, sys.stdout)
|
||||
sys.stdout.flush()
|
||||
|
||||
# -----------------------------
|
||||
# Argparse
|
||||
# -----------------------------
|
||||
def build_parser():
|
||||
ap = argparse.ArgumentParser(allow_abbrev=False)
|
||||
ap.add_argument("--mode", default="cli", choices=["cli", "rerank-worker"])
|
||||
|
||||
# Legacy single-index I/O (kept for back-compat)
|
||||
ap.add_argument("--index", help="Single FAISS index (legacy)")
|
||||
ap.add_argument("--store", help="Single metadata JSONL (legacy)")
|
||||
ap.add_argument("--candidates", type=int, default=200, help="ANN neighbors to fetch (legacy or rerank pool).")
|
||||
|
||||
# Hybrid I/O
|
||||
ap.add_argument("--shadow-index", help="FAISS index over shadow_text")
|
||||
ap.add_argument("--shadow-store", help="Metadata JSONL for shadow index")
|
||||
ap.add_argument("--content-index", help="FAISS index over content chunks")
|
||||
ap.add_argument("--content-store", help="Metadata JSONL for content index")
|
||||
|
||||
ap.add_argument("--query", required=False)
|
||||
ap.add_argument("--ollama", default="http://localhost:11434")
|
||||
ap.add_argument("--embed-model", default="dengcao/Qwen3-Embedding-0.6B:F16")
|
||||
|
||||
# Shadow/content retrieval sizes (hybrid)
|
||||
ap.add_argument("--shadow-candidates", type=int, default=400, help="Shadow ANN pool size")
|
||||
ap.add_argument("--content-candidates", type=int, default=600, help="Content ANN pool size")
|
||||
ap.add_argument("--doc-top", type=int, default=40, help="Top-N documents from shadow shortlist")
|
||||
ap.add_argument("--per-doc-chunks", type=int, default=2, help="Max chunks per doc from content pool")
|
||||
ap.add_argument("--doc-blend", type=float, default=0.6, help="Weight for shadow score in final blend [0..1]")
|
||||
ap.add_argument("--chunk-blend", type=float, default=0.4, help="Weight for content-ANN score in final blend [0..1]")
|
||||
ap.add_argument("--shadow-kind-weights", default="image:1.2,code:1.1", help="Comma list 'kind:weight' to bias doc ranking")
|
||||
|
||||
# Rerank knobs
|
||||
ap.add_argument("--no-rerank", action="store_true", help="Disable reranking.")
|
||||
ap.add_argument("--blend", type=float, default=0.75, help="Blend weight for reranker in normalized score [0..1].")
|
||||
ap.add_argument("--rerank-model", default="cross-encoder/ms-marco-MiniLM-L-6-v2")
|
||||
ap.add_argument("--rerank-device", default="auto", choices=["auto", "mps", "cpu"])
|
||||
ap.add_argument("--rerank-dtype", default="auto", choices=["auto", "float16", "float32"])
|
||||
ap.add_argument("--rerank-batch", type=int, default=64)
|
||||
ap.add_argument("--rerank-maxlen", type=int, default=256)
|
||||
ap.add_argument("--stdio", action="store_true", help=argparse.SUPPRESS) # worker-only flag
|
||||
|
||||
# Output / answer
|
||||
ap.add_argument("--json", action="store_true", help="Print search results as JSON.")
|
||||
ap.add_argument("--pretty", action="store_true", help="Pretty-print search results.")
|
||||
ap.add_argument("--show-scores", action="store_true", help="Show ANN/rerank scores in pretty output.")
|
||||
ap.add_argument("--answer", action="store_true", help="Generate an answer with an LLM using top-k contexts.")
|
||||
ap.add_argument("--gen-model", default="qwen3:4b",
|
||||
help="Any chat-capable model in Ollama (e.g., 'qwen2.5:7b-instruct', 'llama3.1:8b-instruct').")
|
||||
ap.add_argument("--temperature", type=float, default=0.2)
|
||||
ap.add_argument("--k", type=int, default=10, help="Number of final results to return/use.")
|
||||
|
||||
# Misc
|
||||
ap.add_argument("--max-doc-chars", type=int, default=4000, help="Truncate each candidate before rerank.")
|
||||
ap.add_argument("--per-source-limit", type=int, default=3, help="Max results per source (url/doc) to diversify.")
|
||||
|
||||
return ap
|
||||
|
||||
def run_query(shadow_index: Path, shadow_store: Path,
|
||||
content_index: Path, content_store: Path,
|
||||
query: str, *, answer: bool = False,
|
||||
on_stream: Optional[Callable[[Dict], None]] = None, **opts) -> dict:
|
||||
|
||||
# Ensure all paths are strings for argparse.Namespace
|
||||
_shadow_index = str(shadow_index) if shadow_index else None
|
||||
_shadow_store = str(shadow_store) if shadow_store else None
|
||||
_content_index = str(content_index) if content_index else None
|
||||
_content_store = str(content_store) if content_store else None
|
||||
|
||||
args = argparse.Namespace(
|
||||
shadow_index=_shadow_index,
|
||||
shadow_store=_shadow_store,
|
||||
content_index=_content_index,
|
||||
content_store=_content_store,
|
||||
query=query,
|
||||
answer=answer,
|
||||
ollama=opts.get("ollama", "http://localhost:11434"),
|
||||
embed_model=opts.get("embed_model", "bge-m3:latest"),
|
||||
shadow_candidates=opts.get("shadow_candidates", 400),
|
||||
content_candidates=opts.get("content_candidates", 600),
|
||||
doc_top=opts.get("doc_top", 40),
|
||||
per_doc_chunks=opts.get("per_doc_chunks", 2),
|
||||
doc_blend=opts.get("doc_blend", 0.6),
|
||||
chunk_blend=opts.get("chunk_blend", 0.4),
|
||||
shadow_kind_weights=opts.get("shadow_kind_weights", "image:1.2,code:1.1"),
|
||||
no_rerank=opts.get("no_rerank", True), # Reranker OFF by default
|
||||
blend=opts.get("blend", 0.75),
|
||||
rerank_model=opts.get("rerank_model", "cross-encoder/ms-marco-MiniLM-L-6-v2"),
|
||||
rerank_device=opts.get("rerank_device", "auto"),
|
||||
rerank_dtype=opts.get("rerank_dtype", "auto"),
|
||||
rerank_batch=opts.get("rerank_batch", 64),
|
||||
rerank_maxlen=opts.get("rerank_maxlen", 256),
|
||||
gen_model=opts.get("gen_model", "qwen3:4b"),
|
||||
temperature=opts.get("temperature", 0.2),
|
||||
k=opts.get("k", 10),
|
||||
max_doc_chars=opts.get("max_doc_chars", 4000),
|
||||
per_source_limit=opts.get("per_source_limit", 3),
|
||||
json=True # Force JSON-like output dict
|
||||
)
|
||||
|
||||
return run_cli(args, on_stream=on_stream)
|
||||
|
||||
def main():
|
||||
ap = build_parser()
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.mode == "rerank-worker":
|
||||
return run_rerank_worker(args)
|
||||
|
||||
if not args.query:
|
||||
ap.error("--query is required in cli mode")
|
||||
|
||||
hybrid_ok = all([args.shadow_index, args.shadow_store, args.content_index, args.content_store])
|
||||
if not hybrid_ok:
|
||||
ap.error("For CLI use, all four index/store paths are required for hybrid retrieval.")
|
||||
|
||||
result = run_query(
|
||||
shadow_index=Path(args.shadow_index),
|
||||
shadow_store=Path(args.shadow_store),
|
||||
content_index=Path(args.content_index),
|
||||
content_store=Path(args.content_store),
|
||||
query=args.query,
|
||||
answer=args.answer,
|
||||
on_stream=lambda d: print(json.dumps(d, ensure_ascii=False), flush=True) if args.answer else None,
|
||||
**vars(args)
|
||||
)
|
||||
|
||||
if not args.answer:
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -3,4 +3,25 @@ fastapi==0.111.0
|
||||
uvicorn[standard]==0.30.1
|
||||
SQLAlchemy==2.0.32
|
||||
httpx==0.27.0
|
||||
pydantic==2.7.4
|
||||
pydantic==2.11.7
|
||||
requests>=2.32.0
|
||||
|
||||
# Web search enrichment dependencies
|
||||
beautifulsoup4==4.12.3
|
||||
httpx[http2]>=0.27.0
|
||||
numpy
|
||||
|
||||
# Local RAG pipeline dependencies
|
||||
faiss-cpu>=1.8.0
|
||||
PyMuPDF>=1.24.0
|
||||
ebooklib>=0.18
|
||||
chardet>=5.2.0
|
||||
Pillow>=10.0.0
|
||||
langid>=1.1.6
|
||||
langdetect>=1.0.9
|
||||
tqdm>=4.66.0
|
||||
openai-whisper
|
||||
|
||||
# Optional but recommended for richer ingestion / reranking:
|
||||
# opencv-python-headless
|
||||
# sentence-transformers
|
||||
|
||||
@@ -1,16 +1,39 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from typing import Any, Dict, List, Optional
|
||||
from datetime import datetime
|
||||
|
||||
class ChatAttachment(BaseModel):
|
||||
kind: Optional[str] = None
|
||||
name: str
|
||||
mime_type: Optional[str] = None
|
||||
data_url: Optional[str] = None
|
||||
source_path: Optional[str] = None
|
||||
size: Optional[int] = None
|
||||
record_type: Optional[str] = None
|
||||
text: Optional[str] = None
|
||||
|
||||
class Message(BaseModel):
|
||||
message_id: Optional[str] = None
|
||||
role: str
|
||||
content: str
|
||||
sources: Optional[List[Any]] = None
|
||||
attachments: Optional[List[ChatAttachment]] = None
|
||||
workflow_id: Optional[str] = None
|
||||
workflow_revision_id: Optional[str] = None
|
||||
workflow_run_id: Optional[str] = None
|
||||
agent_summary: Optional[Dict[str, Any]] = None
|
||||
usage: Optional[Dict[str, Any]] = None
|
||||
|
||||
class ChatRequest(BaseModel):
|
||||
session_id: str
|
||||
model: str
|
||||
message: str
|
||||
enriched_message: Optional[str] = None
|
||||
stream: Optional[bool] = False
|
||||
sources: Optional[List[str]] = None
|
||||
attachments: Optional[List[ChatAttachment]] = None
|
||||
vision_model: Optional[str] = None
|
||||
transcription_model: Optional[str] = None
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
reply: str
|
||||
@@ -18,6 +41,12 @@ class ChatResponse(BaseModel):
|
||||
class HistoryResponse(BaseModel):
|
||||
messages: List[Message]
|
||||
|
||||
|
||||
class SaveMessageToKnowledgeRequest(BaseModel):
|
||||
message_id: str
|
||||
title: Optional[str] = None
|
||||
content: Optional[str] = None
|
||||
|
||||
class GenerateTitleRequest(BaseModel):
|
||||
session_id: str
|
||||
message: str
|
||||
@@ -35,8 +64,7 @@ class ChatSession(BaseModel):
|
||||
name: str
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
class SessionsResponse(BaseModel):
|
||||
sessions: List[ChatSession]
|
||||
@@ -47,4 +75,40 @@ class EditMessageRequest(BaseModel):
|
||||
class RegenerateRequest(BaseModel):
|
||||
index: int
|
||||
model: Optional[str] = None
|
||||
stream: bool = True
|
||||
enriched_message: Optional[str] = None
|
||||
stream: bool = True
|
||||
sources: Optional[List[str]] = None
|
||||
vision_model: Optional[str] = None
|
||||
transcription_model: Optional[str] = None
|
||||
|
||||
# Request payload for the web search enrichment endpoint.
|
||||
class WebSearchRequest(BaseModel):
|
||||
prompt: str
|
||||
model: str
|
||||
messages: Optional[List[Message]] = None
|
||||
history_limit: Optional[int] = 8
|
||||
searx_url: Optional[str] = None
|
||||
engines: Optional[List[str]] = None
|
||||
|
||||
# Response payload for the web search enrichment endpoint.
|
||||
class WebSearchResponse(BaseModel):
|
||||
enriched_prompt: str
|
||||
sources: List[str] = []
|
||||
context_block: str = ""
|
||||
|
||||
|
||||
class OllamaPullRequest(BaseModel):
|
||||
model: Optional[str] = None
|
||||
|
||||
|
||||
class AudioTranscriptionRequest(BaseModel):
|
||||
mime_type: str
|
||||
audio_base64: str
|
||||
model: Optional[str] = None
|
||||
language: Optional[str] = None
|
||||
|
||||
|
||||
class AudioTranscriptionResponse(BaseModel):
|
||||
text: str
|
||||
language: Optional[str] = None
|
||||
model: str
|
||||
|
||||
27
backend/sidecar_main.py
Normal file
27
backend/sidecar_main.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import multiprocessing
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
|
||||
def main() -> None:
|
||||
multiprocessing.freeze_support()
|
||||
os.environ.setdefault("HEIMGEIST_BACKEND_SIDECAR", "1")
|
||||
host = os.getenv("HEIMGEIST_BACKEND_HOST", "127.0.0.1")
|
||||
port = int(os.getenv("HEIMGEIST_BACKEND_PORT", "8000"))
|
||||
log_level = os.getenv("HEIMGEIST_BACKEND_LOG_LEVEL", "info")
|
||||
|
||||
uvicorn.run(
|
||||
"backend.main:app",
|
||||
host=host,
|
||||
port=port,
|
||||
log_level=log_level,
|
||||
reload=False,
|
||||
workers=1,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
0
backend/tests/__init__.py
Normal file
0
backend/tests/__init__.py
Normal file
71
backend/tests/test_agent_chat_tool.py
Normal file
71
backend/tests/test_agent_chat_tool.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.agent.tools.chat import _drop_superseded_trailing_user_rows, chat_handler
|
||||
|
||||
|
||||
class ChatToolTests(unittest.TestCase):
|
||||
def test_drops_unanswered_trailing_user_messages_except_latest(self):
|
||||
rows = [
|
||||
SimpleNamespace(role="user", content="first question"),
|
||||
SimpleNamespace(role="assistant", content="first answer"),
|
||||
SimpleNamespace(role="user", content="interrupted follow-up"),
|
||||
SimpleNamespace(role="user", content="latest prompt"),
|
||||
]
|
||||
|
||||
result = _drop_superseded_trailing_user_rows(rows)
|
||||
|
||||
self.assertEqual([row.content for row in result], ["first question", "first answer", "latest prompt"])
|
||||
|
||||
def test_keeps_normal_alternating_history(self):
|
||||
rows = [
|
||||
SimpleNamespace(role="user", content="first question"),
|
||||
SimpleNamespace(role="assistant", content="first answer"),
|
||||
SimpleNamespace(role="user", content="latest prompt"),
|
||||
]
|
||||
|
||||
self.assertIs(_drop_superseded_trailing_user_rows(rows), rows)
|
||||
|
||||
|
||||
class ChatToolAsyncTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_chat_handler_returns_context_fallback_when_model_fails(self):
|
||||
async def emit(_event_type, _payload):
|
||||
return None
|
||||
|
||||
async def failing_stream(*_args, **_kwargs):
|
||||
raise RuntimeError("model returned 502")
|
||||
if False:
|
||||
yield None
|
||||
|
||||
context = SimpleNamespace(
|
||||
session_id=None,
|
||||
db_factory=lambda: None,
|
||||
emit=emit,
|
||||
cancellation_event=asyncio.Event(),
|
||||
show_thinking=False,
|
||||
)
|
||||
arguments = {
|
||||
"model": "broken-model",
|
||||
"messages": [{"role": "user", "content": "weather?"}],
|
||||
"context_blocks": [{
|
||||
"context_block": "<websearch_context>Weather context</websearch_context>",
|
||||
"sources": [{
|
||||
"type": "web",
|
||||
"title": "Schwäbisch Gmünd Weather",
|
||||
"snippet": "Sunny intervals and light wind.",
|
||||
"url": "https://weather.example/schwaebisch-gmuend",
|
||||
}],
|
||||
}],
|
||||
"generation_options": {},
|
||||
"reasoning": False,
|
||||
}
|
||||
|
||||
with patch("backend.agent.tools.chat.chat_stream_typed", failing_stream):
|
||||
result = await chat_handler(arguments, context)
|
||||
|
||||
self.assertIn("selected chat model failed", result["content"])
|
||||
self.assertIn("Schwäbisch Gmünd Weather", result["content"])
|
||||
self.assertIn("https://weather.example/schwaebisch-gmuend", result["content"])
|
||||
self.assertEqual(result["sources"][0]["url"], "https://weather.example/schwaebisch-gmuend")
|
||||
71
backend/tests/test_agent_registry.py
Normal file
71
backend/tests/test_agent_registry.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from backend.agent.registry import (
|
||||
NativeToolProvider,
|
||||
SchemaValidationError,
|
||||
ToolDefinition,
|
||||
ToolExecutionContext,
|
||||
)
|
||||
|
||||
|
||||
INPUT = {
|
||||
"type": "object",
|
||||
"properties": {"value": {"type": "string"}},
|
||||
"required": ["value"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
OUTPUT = {
|
||||
"type": "object",
|
||||
"properties": {"result": {"type": "string"}},
|
||||
"required": ["result"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
def context(registry):
|
||||
return ToolExecutionContext(
|
||||
run_id="run", workflow_id="workflow", node_id="node", session_id=None,
|
||||
selection_mode="explicit", explicit_user_action=True,
|
||||
emit=lambda *_args: asyncio.sleep(0), cancellation_event=asyncio.Event(),
|
||||
db_factory=lambda: None, registry=registry,
|
||||
)
|
||||
|
||||
|
||||
class RegistryTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_duplicate_names_are_rejected(self):
|
||||
async def handler(arguments, _context): return {"result": arguments["value"]}
|
||||
registry = NativeToolProvider()
|
||||
definition = ToolDefinition("test.echo", "echo", INPUT, OUTPUT, handler)
|
||||
registry.register(definition)
|
||||
with self.assertRaises(ValueError):
|
||||
registry.register(definition)
|
||||
|
||||
async def test_arguments_and_outputs_are_validated(self):
|
||||
async def handler(arguments, _context): return {"result": arguments["value"]}
|
||||
registry = NativeToolProvider()
|
||||
registry.register(ToolDefinition("test.echo", "echo", INPUT, OUTPUT, handler))
|
||||
self.assertEqual((await registry.call_tool("test.echo", {"value": "ok"}, context(registry)))["result"], "ok")
|
||||
with self.assertRaises(SchemaValidationError):
|
||||
await registry.call_tool("test.echo", {"value": 1}, context(registry))
|
||||
|
||||
async def invalid_output(_arguments, _context): return {"result": 1}
|
||||
invalid = NativeToolProvider()
|
||||
invalid.register(ToolDefinition("test.invalid", "invalid", INPUT, OUTPUT, invalid_output))
|
||||
with self.assertRaises(SchemaValidationError):
|
||||
await invalid.call_tool("test.invalid", {"value": "x"}, context(invalid))
|
||||
|
||||
async def test_timeout_and_result_size_are_enforced(self):
|
||||
async def slow(_arguments, _context):
|
||||
await asyncio.sleep(0.05)
|
||||
return {"result": "ok"}
|
||||
registry = NativeToolProvider()
|
||||
registry.register(ToolDefinition("test.slow", "slow", INPUT, OUTPUT, slow, timeout_seconds=0.01))
|
||||
with self.assertRaises(TimeoutError):
|
||||
await registry.call_tool("test.slow", {"value": "x"}, context(registry))
|
||||
|
||||
async def large(_arguments, _context): return {"result": "x" * 100}
|
||||
limited = NativeToolProvider()
|
||||
limited.register(ToolDefinition("test.large", "large", INPUT, OUTPUT, large, result_size_limit=20))
|
||||
with self.assertRaises(ValueError):
|
||||
await limited.call_tool("test.large", {"value": "x"}, context(limited))
|
||||
262
backend/tests/test_agent_web_tools.py
Normal file
262
backend/tests/test_agent_web_tools.py
Normal file
@@ -0,0 +1,262 @@
|
||||
import asyncio
|
||||
import json
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from backend.agent.registry import NativeToolProvider, ToolExecutionContext
|
||||
from backend.agent.tools.web import FETCH_TEXT_LIMIT, register_web_tools
|
||||
from backend.ollama_client import OllamaChatResult
|
||||
from backend.websearch import build_enriched_prompt, rerank
|
||||
|
||||
|
||||
def context(registry):
|
||||
return ToolExecutionContext(
|
||||
run_id="run",
|
||||
workflow_id="workflow",
|
||||
node_id="fetch",
|
||||
session_id=None,
|
||||
selection_mode="explicit",
|
||||
explicit_user_action=True,
|
||||
emit=lambda *_args: asyncio.sleep(0),
|
||||
cancellation_event=asyncio.Event(),
|
||||
db_factory=lambda: None,
|
||||
registry=registry,
|
||||
)
|
||||
|
||||
|
||||
class WebToolTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_generate_queries_returns_llm_queries_without_topic_parser(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
|
||||
result_payload = {"queries": [" latest ", "top stories", "latest Iran news headlines", "latest"]}
|
||||
with patch(
|
||||
"backend.agent.tools.web.chat_typed",
|
||||
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps(result_payload))),
|
||||
):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_generate_queries",
|
||||
{"prompt": "what's the news in iran today", "model": "model", "messages": []},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
queries = result["queries"]
|
||||
self.assertEqual(queries, ["latest", "top stories", "latest Iran news headlines"])
|
||||
|
||||
async def test_search_filters_dictionary_noise_for_current_lookup(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
|
||||
async def fake_search(_client, _query, **_kwargs):
|
||||
return [
|
||||
{"url": "https://dict.leo.org/englisch-deutsch/latest", "title": "latest - Deutsch-Uebersetzung", "engine": "bing"},
|
||||
{"url": "https://www.reuters.com/world/middle-east/iran-example", "title": "Iran latest news", "engine": "bing"},
|
||||
{"url": "https://consent.google.com/ml?continue=https://news.google.com/topics/iran", "title": "Before you continue", "engine": "bing"},
|
||||
]
|
||||
|
||||
with patch("backend.agent.tools.web.searx_search", new=AsyncMock(side_effect=fake_search)):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_search",
|
||||
{
|
||||
"query": None,
|
||||
"queries": ["latest Iran news headlines"],
|
||||
"engines": [],
|
||||
"maximum_results": 8,
|
||||
"searx_url": "http://127.0.0.1:8888",
|
||||
},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
urls = [item["url"] for item in result["results"]]
|
||||
self.assertEqual(urls, ["https://www.reuters.com/world/middle-east/iran-example"])
|
||||
|
||||
async def test_search_does_not_require_parsed_topic_terms(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
|
||||
async def fake_search(_client, _query, **_kwargs):
|
||||
return [
|
||||
{"url": "https://www.aljazeera.com/where/iran/", "title": "Iran news", "engine": "bing"},
|
||||
{"url": "https://www.bbc.com/news/world-middle-east", "title": "Middle East latest", "engine": "bing"},
|
||||
]
|
||||
|
||||
with patch("backend.agent.tools.web.searx_search", new=AsyncMock(side_effect=fake_search)):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_search",
|
||||
{
|
||||
"query": None,
|
||||
"queries": ["what happened in iran today"],
|
||||
"engines": [],
|
||||
"maximum_results": 8,
|
||||
"searx_url": "http://127.0.0.1:8888",
|
||||
},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
urls = [item["url"] for item in result["results"]]
|
||||
self.assertEqual(urls, ["https://www.aljazeera.com/where/iran/", "https://www.bbc.com/news/world-middle-east"])
|
||||
|
||||
async def test_fetch_accepts_search_result_batches_and_caps_page_text(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
urls = [{"url": f"https://example.test/{index}"} for index in range(16)]
|
||||
|
||||
async def fake_fetch(url):
|
||||
return {
|
||||
"requested_url": url,
|
||||
"url": url,
|
||||
"title": "Example",
|
||||
"text": "x" * (FETCH_TEXT_LIMIT + 500),
|
||||
}
|
||||
|
||||
with patch("backend.agent.tools.web.fetch_website_snapshot", new=AsyncMock(side_effect=fake_fetch)):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_fetch",
|
||||
{"url": None, "urls": urls, "maximum_pages": 6},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
self.assertEqual(len(result["pages"]), 6)
|
||||
self.assertTrue(all(len(page["cleaned_text"]) == FETCH_TEXT_LIMIT for page in result["pages"]))
|
||||
|
||||
async def test_fetch_filters_consent_pages_after_redirects(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
|
||||
async def fake_fetch(url):
|
||||
return {
|
||||
"requested_url": url,
|
||||
"url": "https://consent.google.com/ml?continue=https://news.google.com/topics/iran",
|
||||
"title": "Before you continue",
|
||||
"text": "Google privacy controls",
|
||||
}
|
||||
|
||||
with patch("backend.agent.tools.web.fetch_website_snapshot", new=AsyncMock(side_effect=fake_fetch)):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_fetch",
|
||||
{"url": None, "urls": [{"url": "https://example.test/iran"}], "maximum_pages": 1},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
self.assertEqual(result["pages"][0]["error"], "filtered_noise_page")
|
||||
self.assertEqual(result["pages"][0]["cleaned_text"], "")
|
||||
|
||||
async def test_rerank_filters_pages_without_prompt_topic(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
pages = [
|
||||
{
|
||||
"requested_url": "https://de.langenscheidt.com/englisch-deutsch/latest",
|
||||
"canonical_url": "https://de.langenscheidt.com/englisch-deutsch/latest",
|
||||
"title": "latest - Deutsch-Uebersetzung",
|
||||
"cleaned_text": "latest means occurring most recently",
|
||||
"error": None,
|
||||
},
|
||||
{
|
||||
"requested_url": "https://www.reuters.com/world/middle-east/iran-example",
|
||||
"canonical_url": "https://www.reuters.com/world/middle-east/iran-example",
|
||||
"title": "Iran latest news",
|
||||
"cleaned_text": "Iran officials and regional sources reported new developments today.",
|
||||
"error": None,
|
||||
},
|
||||
]
|
||||
|
||||
ranked = [
|
||||
("https://de.langenscheidt.com/englisch-deutsch/latest", "latest means occurring most recently", 99),
|
||||
("https://www.reuters.com/world/middle-east/iran-example", "Iran officials reported new developments today.", 60),
|
||||
]
|
||||
with patch("backend.agent.tools.web.rerank", new=AsyncMock(return_value=ranked)):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_rerank",
|
||||
{
|
||||
"prompt": "what's the news in iran today",
|
||||
"pages": pages,
|
||||
"model": "model",
|
||||
"rerank_model": None,
|
||||
"context_excerpt": "",
|
||||
"maximum_results": 6,
|
||||
"minimum_score": 55,
|
||||
},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
self.assertEqual(len(result["results"]), 1)
|
||||
self.assertEqual(result["results"][0]["url"], "https://www.reuters.com/world/middle-east/iran-example")
|
||||
|
||||
async def test_rerank_falls_back_when_embedding_model_is_unavailable(self):
|
||||
class FailingAsyncClient:
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return None
|
||||
|
||||
async def post(self, *_args, **_kwargs):
|
||||
raise RuntimeError("model not found")
|
||||
|
||||
docs = [
|
||||
(
|
||||
"https://example.test/weather",
|
||||
"A general weather page with forecasts and temperatures.",
|
||||
),
|
||||
(
|
||||
"https://www.reuters.com/world/middle-east/iran-example",
|
||||
"Iran officials reported new sanctions and regional developments today.",
|
||||
),
|
||||
]
|
||||
|
||||
with patch("backend.websearch.httpx.AsyncClient", FailingAsyncClient):
|
||||
ranked = await rerank(
|
||||
"latest Iran sanctions news",
|
||||
docs,
|
||||
model="chat-model",
|
||||
context_excerpt="",
|
||||
embed_model="missing-embed:latest",
|
||||
)
|
||||
|
||||
enriched, sources = build_enriched_prompt("latest Iran sanctions news", ranked, top_k=3)
|
||||
self.assertEqual(ranked[0][0], "https://www.reuters.com/world/middle-east/iran-example")
|
||||
self.assertIn("https://www.reuters.com/world/middle-east/iran-example", sources)
|
||||
self.assertIn("<websearch_context>", enriched)
|
||||
|
||||
async def test_rerank_tool_uses_fallback_when_rerank_errors(self):
|
||||
registry = NativeToolProvider()
|
||||
register_web_tools(registry)
|
||||
pages = [
|
||||
{
|
||||
"requested_url": "https://example.test/weather",
|
||||
"canonical_url": "https://example.test/weather",
|
||||
"title": "Weather",
|
||||
"cleaned_text": "A general weather page with forecasts and temperatures.",
|
||||
"error": None,
|
||||
},
|
||||
{
|
||||
"requested_url": "https://www.reuters.com/world/middle-east/iran-example",
|
||||
"canonical_url": "https://www.reuters.com/world/middle-east/iran-example",
|
||||
"title": "Iran latest news",
|
||||
"cleaned_text": "Iran officials reported new sanctions and regional developments today.",
|
||||
"error": None,
|
||||
},
|
||||
]
|
||||
|
||||
with patch("backend.agent.tools.web.rerank", new=AsyncMock(side_effect=RuntimeError("missing model"))):
|
||||
result = await registry.call_tool(
|
||||
"heimgeist.web_rerank",
|
||||
{
|
||||
"prompt": "latest Iran sanctions news",
|
||||
"pages": pages,
|
||||
"model": "model",
|
||||
"rerank_model": None,
|
||||
"context_excerpt": "",
|
||||
"maximum_results": 6,
|
||||
"minimum_score": 55,
|
||||
},
|
||||
context(registry),
|
||||
)
|
||||
|
||||
self.assertGreaterEqual(len(result["results"]), 1)
|
||||
self.assertEqual(result["results"][0]["url"], "https://www.reuters.com/world/middle-east/iran-example")
|
||||
self.assertIn("<websearch_context>", result["context_block"])
|
||||
203
backend/tests/test_chat_memory.py
Normal file
203
backend/tests/test_chat_memory.py
Normal file
@@ -0,0 +1,203 @@
|
||||
from pathlib import Path
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from backend.chat_memory import (
|
||||
build_chat_memory_context,
|
||||
ensure_chat_memory_schema,
|
||||
sync_all_chat_memory,
|
||||
sync_chat_memory_for_session,
|
||||
)
|
||||
from backend.agent.tools.memory import chat_memory_search_handler
|
||||
from backend.database import Base
|
||||
from backend.models import ChatMessage, ChatSession
|
||||
|
||||
|
||||
class ChatMemoryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.engine = create_engine(
|
||||
f"sqlite:///{Path(self.temp.name) / 'memory.db'}",
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
Base.metadata.create_all(self.engine)
|
||||
ensure_chat_memory_schema(self.engine)
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
|
||||
def tearDown(self):
|
||||
self.engine.dispose()
|
||||
self.temp.cleanup()
|
||||
|
||||
def _turn(self, db, session_id, title, user_content, assistant_content, created_at=None):
|
||||
created_at = created_at or datetime.utcnow()
|
||||
session = ChatSession(session_id=session_id, name=title, created_at=created_at)
|
||||
db.add(session)
|
||||
db.flush()
|
||||
db.add(ChatMessage(session_pk=session.id, role="user", content=user_content, created_at=created_at))
|
||||
db.flush()
|
||||
db.add(ChatMessage(session_pk=session.id, role="assistant", content=assistant_content, created_at=created_at + timedelta(seconds=1)))
|
||||
db.flush()
|
||||
return session
|
||||
|
||||
def _turn_with_sources(self, db, session_id, title, user_content, assistant_content, sources):
|
||||
session = ChatSession(session_id=session_id, name=title)
|
||||
db.add(session)
|
||||
db.flush()
|
||||
db.add(ChatMessage(session_pk=session.id, role="user", content=user_content))
|
||||
db.flush()
|
||||
db.add(ChatMessage(
|
||||
session_pk=session.id,
|
||||
role="assistant",
|
||||
content=assistant_content,
|
||||
sources_json=json.dumps(sources),
|
||||
))
|
||||
db.flush()
|
||||
return session
|
||||
|
||||
def test_retrieves_completed_past_turns(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
self._turn(
|
||||
db,
|
||||
"past",
|
||||
"Tauri Packaging",
|
||||
"What did we decide about mac packaging?",
|
||||
"Use the PyInstaller backend sidecar and keep app data outside the bundle.",
|
||||
)
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
|
||||
context = build_chat_memory_context(db, "remind me about the backend sidecar packaging plan")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self.assertIn("chat_memory_context", context["context_block"])
|
||||
self.assertIn("PyInstaller backend sidecar", context["context_block"])
|
||||
self.assertEqual(context["sources"][0]["source_session_id"], "past")
|
||||
|
||||
def test_excludes_active_session(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
self._turn(db, "current", "Current", "secret kiwi topic", "Only the current chat mentions kiwi.")
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
|
||||
excluded = build_chat_memory_context(db, "kiwi topic", exclude_session_id="current")
|
||||
included = build_chat_memory_context(db, "kiwi topic")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self.assertEqual(excluded["context_block"], "")
|
||||
self.assertIn("kiwi", included["context_block"])
|
||||
|
||||
def test_resync_removes_stale_turn_content(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
session = self._turn(db, "past", "Old Decision", "deployment detail", "Keep using the banana corridor plan.")
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
|
||||
assistant = db.query(ChatMessage).filter(ChatMessage.role == "assistant").one()
|
||||
assistant.content = "This turn now discusses an unrelated renderer detail."
|
||||
db.commit()
|
||||
sync_chat_memory_for_session(db, session.session_id)
|
||||
|
||||
context = build_chat_memory_context(db, "banana corridor plan")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self.assertEqual(context["context_block"], "")
|
||||
|
||||
def test_recent_mode_returns_most_recent_previous_session(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
base = datetime(2026, 1, 1, 12, 0, 0)
|
||||
self._turn(db, "older", "Weather", "what is the weather?", "It is rainy.", created_at=base)
|
||||
self._turn(db, "previous", "Crowley", "tell me about Crowley", "The previous chat discussed Crowley.", created_at=base + timedelta(minutes=1))
|
||||
current = ChatSession(session_id="current", name="Letztes Gespräch", created_at=base + timedelta(minutes=2))
|
||||
db.add(current)
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
|
||||
context = build_chat_memory_context(
|
||||
db,
|
||||
"worum ging es im letzten gespräch?",
|
||||
exclude_session_id="current",
|
||||
mode="recent",
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self.assertIn("Crowley", context["context_block"])
|
||||
self.assertNotIn("rainy", context["context_block"])
|
||||
|
||||
def test_search_mode_uses_supplied_query_terms(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
self._turn(db, "song", "Identify this song", "what is this song?", "We discussed a track by an electronic artist.")
|
||||
self._turn(db, "lied", "Lied: Hintergründe suchen", "suche hintergründe zu diesem lied", "Das Lied wurde im Kontext einer Band besprochen.")
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
|
||||
context = build_chat_memory_context(db, "song lied")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self.assertIn("song", context["context_block"].casefold())
|
||||
self.assertIn("lied", context["context_block"].casefold())
|
||||
|
||||
def test_chat_memory_tool_returns_context_block_and_sources(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
self._turn(
|
||||
db,
|
||||
"past",
|
||||
"Backend Sidecar",
|
||||
"What was the sidecar plan?",
|
||||
"Use PyInstaller for the backend sidecar and keep runtime data outside the app bundle.",
|
||||
)
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
context = type("Context", (), {
|
||||
"session_id": "current",
|
||||
"db_factory": self.Session,
|
||||
})()
|
||||
result = asyncio.run(chat_memory_search_handler({
|
||||
"prompt": "backend sidecar runtime data",
|
||||
"top_k": 3,
|
||||
"context_character_budget": 4000,
|
||||
"exclude_current_session": True,
|
||||
}, context))
|
||||
|
||||
self.assertIn("PyInstaller", result["context_block"])
|
||||
self.assertEqual(result["sources"][0]["type"], "chat_memory")
|
||||
self.assertEqual(result["hits"][0]["session_id"], "past")
|
||||
|
||||
def test_memory_only_answers_are_not_reindexed(self):
|
||||
db = self.Session()
|
||||
try:
|
||||
self._turn_with_sources(
|
||||
db,
|
||||
"poison",
|
||||
"Backfire Basics",
|
||||
"erzähl mir über backfire basics",
|
||||
"Backfire Basics is a hallucinated project description.",
|
||||
[{"type": "chat_memory", "source_session_id": "older", "source_message_id": "m1"}],
|
||||
)
|
||||
db.commit()
|
||||
sync_all_chat_memory(db)
|
||||
|
||||
context = build_chat_memory_context(db, "backfire basics")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
self.assertEqual(context["context_block"], "")
|
||||
162
backend/tests/test_workflow_api.py
Normal file
162
backend/tests/test_workflow_api.py
Normal file
@@ -0,0 +1,162 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from datetime import datetime
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from backend.agent import api
|
||||
from backend.agent.models import WorkflowDefinition, WorkflowRun
|
||||
from backend.agent.schemas import WorkflowRunRequest
|
||||
from backend.agent.workflows.builtins import seed_builtin_workflows
|
||||
from backend.database import Base
|
||||
from backend.models import ChatMessage, ChatSession
|
||||
|
||||
|
||||
class WorkflowApiTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.engine = create_engine(
|
||||
f"sqlite:///{Path(self.temp.name) / 'api.db'}",
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
Base.metadata.create_all(self.engine)
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
db = self.Session()
|
||||
seed_builtin_workflows(db)
|
||||
direct = db.query(WorkflowDefinition).filter_by(slug="input-output").one()
|
||||
chat = ChatSession(session_id="regenerate-chat")
|
||||
db.add(chat)
|
||||
db.flush()
|
||||
user = ChatMessage(session_pk=chat.id, role="user", content="original")
|
||||
db.add(user)
|
||||
db.flush()
|
||||
assistant = ChatMessage(
|
||||
session_pk=chat.id,
|
||||
role="assistant",
|
||||
content="old answer",
|
||||
workflow_id=direct.id,
|
||||
workflow_revision_id=direct.current_revision_id,
|
||||
)
|
||||
db.add(assistant)
|
||||
db.flush()
|
||||
db.commit()
|
||||
self.user_message_id = user.message_id
|
||||
self.assistant_message_id = assistant.message_id
|
||||
self.direct_workflow_id = direct.id
|
||||
self.direct_revision_id = direct.current_revision_id
|
||||
db.close()
|
||||
|
||||
async def asyncTearDown(self):
|
||||
self.engine.dispose()
|
||||
self.temp.cleanup()
|
||||
|
||||
async def test_regeneration_reuses_user_row_and_prunes_old_answer(self):
|
||||
started = []
|
||||
fake_runtime = SimpleNamespace(start=started.append)
|
||||
request = WorkflowRunRequest(
|
||||
session_id="regenerate-chat",
|
||||
message="edited",
|
||||
model="test-model",
|
||||
selection_mode="direct",
|
||||
workflow_revision_id=self.direct_revision_id,
|
||||
regenerate_index=0,
|
||||
)
|
||||
with patch.object(api, "SessionLocal", self.Session), patch.object(api, "runtime", fake_runtime):
|
||||
response = await api.create_workflow_run(request)
|
||||
|
||||
self.assertEqual(started, [response["run_id"]])
|
||||
db = self.Session()
|
||||
rows = db.query(ChatMessage).order_by(ChatMessage.id.asc()).all()
|
||||
self.assertEqual(len(rows), 1)
|
||||
self.assertEqual(rows[0].message_id, self.user_message_id)
|
||||
self.assertEqual(rows[0].content, "edited")
|
||||
run = db.query(WorkflowRun).filter_by(id=response["run_id"]).one()
|
||||
self.assertEqual(run.user_message_id, self.user_message_id)
|
||||
db.close()
|
||||
|
||||
async def test_run_resolves_previous_assistant_and_message_url_targets(self):
|
||||
fake_runtime = SimpleNamespace(start=lambda _run_id: None)
|
||||
request = WorkflowRunRequest(
|
||||
session_id="regenerate-chat",
|
||||
message="Save https://example.com/source for later.",
|
||||
model="test-model",
|
||||
selection_mode="explicit",
|
||||
workflow_id=self.direct_workflow_id,
|
||||
)
|
||||
with patch.object(api, "SessionLocal", self.Session), patch.object(api, "runtime", fake_runtime):
|
||||
response = await api.create_workflow_run(request)
|
||||
|
||||
db = self.Session()
|
||||
run = db.query(WorkflowRun).filter_by(id=response["run_id"]).one()
|
||||
run_values = json.loads(run.inputs_json)["run"]
|
||||
self.assertEqual(run_values["target_message_id"], self.assistant_message_id)
|
||||
self.assertEqual(run_values["target_url"], "https://example.com/source")
|
||||
db.close()
|
||||
|
||||
async def test_automatic_run_persists_router_web_search_inputs(self):
|
||||
db = self.Session()
|
||||
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
|
||||
web_id = web.id
|
||||
db.close()
|
||||
started = []
|
||||
fake_runtime = SimpleNamespace(start=started.append)
|
||||
router_result = {
|
||||
"workflow_id": web_id,
|
||||
"workflow_slug": "web-answer",
|
||||
"confidence": 0.95,
|
||||
"reason": "current information",
|
||||
"inputs": {"web_search_query": "Iran news today", "web_search_queries": ["Iran news today", "Iran latest news"]},
|
||||
"fallback": False,
|
||||
}
|
||||
request = WorkflowRunRequest(
|
||||
session_id=None,
|
||||
message="what happened in iran today",
|
||||
model="test-model",
|
||||
selection_mode="automatic",
|
||||
)
|
||||
with (
|
||||
patch.object(api, "SessionLocal", self.Session),
|
||||
patch.object(api, "runtime", fake_runtime),
|
||||
patch.object(api, "select_workflow", new=AsyncMock(return_value=router_result)),
|
||||
):
|
||||
response = await api.create_workflow_run(request)
|
||||
|
||||
self.assertEqual(started, [response["run_id"]])
|
||||
db = self.Session()
|
||||
run = db.query(WorkflowRun).filter_by(id=response["run_id"]).one()
|
||||
run_values = json.loads(run.inputs_json)["run"]
|
||||
self.assertEqual(run_values["web_search_query"], "Iran news today")
|
||||
self.assertEqual(run_values["web_search_queries"], ["Iran news today", "Iran latest news"])
|
||||
db.close()
|
||||
|
||||
async def test_interrupted_run_event_stream_emits_terminal_event(self):
|
||||
db = self.Session()
|
||||
workflow = db.query(WorkflowDefinition).filter_by(slug="research").one()
|
||||
run = WorkflowRun(
|
||||
workflow_id=workflow.id,
|
||||
workflow_revision_id=workflow.current_revision_id,
|
||||
status="interrupted",
|
||||
selection_mode="automatic",
|
||||
inputs_json=json.dumps({"input": {"prompt": "x"}, "run": {}}),
|
||||
error_json=json.dumps({"message": "Backend restarted before the workflow completed."}),
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.add(run)
|
||||
db.commit()
|
||||
run_id = run.id
|
||||
db.close()
|
||||
|
||||
with patch.object(api, "SessionLocal", self.Session):
|
||||
response = api.get_workflow_events(run_id, after_sequence=0, follow=True)
|
||||
body = b""
|
||||
async for chunk in response.body_iterator:
|
||||
body += chunk.encode("utf-8") if isinstance(chunk, str) else chunk
|
||||
|
||||
events = [json.loads(line) for line in body.decode("utf-8").splitlines() if line.strip()]
|
||||
interrupted = next(event for event in events if event["type"] == "run_interrupted")
|
||||
self.assertEqual(interrupted["payload"]["message"], "Backend restarted before the workflow completed.")
|
||||
253
backend/tests/test_workflow_router_builtins.py
Normal file
253
backend/tests/test_workflow_router_builtins.py
Normal file
@@ -0,0 +1,253 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from backend.agent.models import WorkflowDefinition
|
||||
from backend.agent.registry import NativeToolProvider
|
||||
from backend.agent.router import _format_message_for_router, _router_prompt, select_workflow
|
||||
from backend.agent.tools import register_native_tools
|
||||
from backend.agent.validation import validate_workflow_graph
|
||||
from backend.agent.workflows.builtins import BUILTIN_WORKFLOWS, seed_builtin_workflows
|
||||
from backend.database import Base
|
||||
from backend.ollama_client import OllamaChatResult
|
||||
|
||||
|
||||
class RouterAndBuiltinTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
engine = create_engine(f"sqlite:///{Path(self.temp.name) / 'router.db'}")
|
||||
Base.metadata.create_all(engine)
|
||||
self.Session = sessionmaker(bind=engine)
|
||||
self.engine = engine
|
||||
db = self.Session(); seed_builtin_workflows(db); db.close()
|
||||
|
||||
async def asyncTearDown(self):
|
||||
self.engine.dispose(); self.temp.cleanup()
|
||||
|
||||
async def test_valid_selection_malformed_disabled_and_low_confidence_fallback(self):
|
||||
db = self.Session()
|
||||
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
|
||||
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({"workflow_id": web.id, "confidence": 0.9, "reason": "current", "inputs": {}})))):
|
||||
result = await select_workflow(db, message="tell me something useful", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model")
|
||||
self.assertEqual(result["workflow_slug"], "web-answer")
|
||||
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content="not json"))):
|
||||
self.assertEqual((await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model"))["workflow_slug"], "input-output")
|
||||
web.enabled = False; db.commit()
|
||||
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({"workflow_id": web.id, "confidence": 0.9, "reason": "x", "inputs": {}})))):
|
||||
self.assertEqual((await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model"))["workflow_slug"], "input-output")
|
||||
web.enabled = True; db.commit()
|
||||
with patch("backend.agent.router.chat_typed", new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({"workflow_id": web.id, "confidence": 0.2, "reason": "x", "inputs": {}})))):
|
||||
self.assertEqual((await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model=None, chat_model="model"))["workflow_slug"], "input-output")
|
||||
db.close()
|
||||
|
||||
async def test_fast_paths_auto_select_or_force_web(self):
|
||||
db = self.Session()
|
||||
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
|
||||
combined = db.query(WorkflowDefinition).filter_by(slug="knowledge-web-answer").one()
|
||||
with patch(
|
||||
"backend.agent.router.chat_typed",
|
||||
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
|
||||
"workflow_id": web.id,
|
||||
"confidence": 0.95,
|
||||
"reason": "forced web",
|
||||
"inputs": {"web_search_query": "Iran news today", "web_search_queries": ["Iran news today", "Iran latest news"]},
|
||||
}))),
|
||||
) as mocked:
|
||||
result = await select_workflow(
|
||||
db, message="hello", recent_messages=[], attachments=[],
|
||||
library_slug=None, router_model=None, chat_model="model", web_search_enabled=True,
|
||||
)
|
||||
self.assertEqual(result["workflow_slug"], "web-answer")
|
||||
self.assertEqual(result["inputs"]["web_search_query"], "Iran news today")
|
||||
mocked.assert_awaited()
|
||||
|
||||
direct = db.query(WorkflowDefinition).filter_by(slug="input-output").one()
|
||||
with patch(
|
||||
"backend.agent.router.chat_typed",
|
||||
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
|
||||
"workflow_id": direct.id,
|
||||
"confidence": 0.95,
|
||||
"reason": "bad router choice",
|
||||
"inputs": {},
|
||||
}))),
|
||||
):
|
||||
result = await select_workflow(
|
||||
db, message="what happened in Iran today", recent_messages=[], attachments=[],
|
||||
library_slug=None, router_model=None, chat_model="model", web_search_enabled=True,
|
||||
)
|
||||
self.assertEqual(result["workflow_slug"], "web-answer")
|
||||
self.assertEqual(result["inputs"]["web_search_query"], "what happened in Iran today")
|
||||
|
||||
with patch(
|
||||
"backend.agent.router.chat_typed",
|
||||
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
|
||||
"workflow_id": web.id,
|
||||
"confidence": 0.95,
|
||||
"reason": "current",
|
||||
"inputs": {"web_search_queries": ["latest Iran news"]},
|
||||
}))),
|
||||
):
|
||||
result = await select_workflow(
|
||||
db, message="latest news today", recent_messages=[], attachments=[],
|
||||
library_slug=None, router_model=None, chat_model="model", web_search_enabled=False,
|
||||
)
|
||||
self.assertEqual(result["workflow_slug"], "web-answer")
|
||||
self.assertEqual(result["inputs"]["web_search_query"], "latest Iran news")
|
||||
|
||||
with patch(
|
||||
"backend.agent.router.chat_typed",
|
||||
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
|
||||
"workflow_id": combined.id,
|
||||
"confidence": 0.95,
|
||||
"reason": "forced web with knowledge",
|
||||
"inputs": {"web_search_query": "compare notes with latest docs", "web_search_queries": ["compare notes with latest docs"]},
|
||||
}))),
|
||||
):
|
||||
result = await select_workflow(
|
||||
db, message="hello", recent_messages=[], attachments=[],
|
||||
library_slug="notes", router_model=None, chat_model="model", web_search_enabled=True,
|
||||
)
|
||||
self.assertEqual(result["workflow_slug"], "knowledge-web-answer")
|
||||
self.assertEqual(result["inputs"]["web_search_query"], "compare notes with latest docs")
|
||||
|
||||
with patch("backend.agent.router.chat_typed", new=AsyncMock()) as mocked:
|
||||
result = await select_workflow(
|
||||
db, message="hello", recent_messages=[], attachments=[],
|
||||
library_slug=None, router_model=None, chat_model="model", web_search_enabled=False,
|
||||
)
|
||||
self.assertEqual(result["workflow_slug"], "input-output")
|
||||
mocked.assert_not_awaited()
|
||||
|
||||
result = await select_workflow(
|
||||
db, message="remember this: I prefer short answers", recent_messages=[], attachments=[],
|
||||
library_slug="memory", router_model=None, chat_model="model", web_search_enabled=False,
|
||||
)
|
||||
self.assertEqual(result["workflow_slug"], "remember-this")
|
||||
db.close()
|
||||
|
||||
async def test_missing_router_model_falls_back_to_chat_model(self):
|
||||
db = self.Session()
|
||||
with patch("backend.agent.router.list_model_catalog", new=AsyncMock(return_value={"chat_models": ["chat"]})), patch("backend.agent.router.chat_typed", new=AsyncMock(side_effect=RuntimeError("bad response"))) as mocked:
|
||||
result = await select_workflow(db, message="x", recent_messages=[], attachments=[], library_slug=None, router_model="missing", chat_model="chat")
|
||||
self.assertEqual(result["workflow_slug"], "input-output")
|
||||
self.assertEqual(mocked.await_args.args[0], "chat")
|
||||
db.close()
|
||||
|
||||
async def test_router_prompt_formats_followup_context_and_filters_for_forced_web(self):
|
||||
db = self.Session()
|
||||
web = db.query(WorkflowDefinition).filter_by(slug="web-answer").one()
|
||||
with patch(
|
||||
"backend.agent.router.chat_typed",
|
||||
new=AsyncMock(return_value=OllamaChatResult(content=json.dumps({
|
||||
"workflow_id": web.id,
|
||||
"confidence": 0.95,
|
||||
"reason": "current follow-up",
|
||||
"inputs": {"web_search_query": "Iran political news today", "web_search_queries": ["Iran political news today"]},
|
||||
}))),
|
||||
) as mocked:
|
||||
result = await select_workflow(
|
||||
db,
|
||||
message="and what's the news politically?",
|
||||
recent_messages=[
|
||||
{"role": "user", "content": "what's the weather in Iran today"},
|
||||
{"role": "assistant", "content": "The weather in Tehran, Iran today is clear."},
|
||||
],
|
||||
attachments=[],
|
||||
library_slug=None,
|
||||
router_model=None,
|
||||
chat_model="model",
|
||||
web_search_enabled=True,
|
||||
)
|
||||
|
||||
prompt = mocked.await_args.args[1][0]["content"]
|
||||
self.assertEqual(result["inputs"]["web_search_query"], "Iran political news today")
|
||||
self.assertIn("Recent conversation:\n1. User: what's the weather in Iran today", prompt)
|
||||
self.assertIn("Resolve the current message into a standalone request", prompt)
|
||||
self.assertIn("capabilities cover the required work", prompt)
|
||||
self.assertIn("Do not choose a workflow because an example sounds similar", prompt)
|
||||
self.assertIn("Choose a web-answer workflow when the missing capability is external facts", prompt)
|
||||
self.assertIn("Short follow-ups usually inherit the previous subject", prompt)
|
||||
self.assertIn("Routing contract:", prompt)
|
||||
self.assertIn("default web workflow for direct answer requests", prompt)
|
||||
self.assertIn("Choose only when the standalone request needs an investigation", prompt)
|
||||
self.assertIn("Allowed workflows. This list is already filtered", prompt)
|
||||
self.assertIn("web-answer", prompt)
|
||||
self.assertNotIn("input-output", prompt)
|
||||
self.assertNotIn("Cost:", prompt)
|
||||
self.assertNotIn("Web search mode:", prompt)
|
||||
self.assertNotIn("Selected knowledge database:", prompt)
|
||||
db.close()
|
||||
|
||||
async def test_long_message_digest_preserves_request_boundaries(self):
|
||||
message = (
|
||||
"Please summarize the pasted material and keep the answer short.\n"
|
||||
+ ("A" * 3600)
|
||||
+ "\nMiddle note: focus on the security implications.\n"
|
||||
+ ("B" * 3600)
|
||||
+ "\nActually, compare the risks and benefits instead."
|
||||
)
|
||||
|
||||
digest = _format_message_for_router(message)
|
||||
|
||||
self.assertLess(len(digest), len(message))
|
||||
self.assertIn("<long_user_message_digest>", digest)
|
||||
self.assertIn("Please summarize the pasted material", digest)
|
||||
self.assertIn("Middle note: focus on the security implications", digest)
|
||||
self.assertIn("Actually, compare the risks and benefits instead.", digest)
|
||||
self.assertIn("Original length:", digest)
|
||||
|
||||
async def test_router_prompt_uses_bounded_digest_and_attachment_summary(self):
|
||||
message = (
|
||||
"Instruction before payload: analyze this local document.\n"
|
||||
+ "\n".join(f"payload line {index} " + ("x" * 80) for index in range(400))
|
||||
+ "\nInstruction after payload: do not search the web unless needed."
|
||||
)
|
||||
manifest = {
|
||||
"workflow_id": "direct",
|
||||
"slug": "input-output",
|
||||
"name": "Input -> Output",
|
||||
"routing_description": "Use when no external tool is needed.",
|
||||
"examples": [],
|
||||
"required_capabilities": ["chat"],
|
||||
}
|
||||
|
||||
prompt = _router_prompt(
|
||||
message=message,
|
||||
recent_messages=[{"role": "assistant", "content": "previous " + ("y" * 2000)}],
|
||||
attachments=[{
|
||||
"kind": "file",
|
||||
"name": "large-report.pdf",
|
||||
"mime_type": "application/pdf",
|
||||
"size": 12345,
|
||||
"text": "attachment text " * 1000,
|
||||
}],
|
||||
manifests=[manifest],
|
||||
)
|
||||
|
||||
self.assertLess(len(prompt), 9000)
|
||||
self.assertIn("Current user message or routing digest:", prompt)
|
||||
self.assertIn("Instruction before payload", prompt)
|
||||
self.assertIn("Instruction after payload", prompt)
|
||||
self.assertIn("large-report.pdf", prompt)
|
||||
self.assertIn("text_chars=", prompt)
|
||||
self.assertNotIn("attachment text attachment text attachment text", prompt)
|
||||
|
||||
async def test_all_builtins_validate(self):
|
||||
registry = NativeToolProvider(); register_native_tools(registry)
|
||||
for item in BUILTIN_WORKFLOWS:
|
||||
with self.subTest(item=item["slug"]):
|
||||
self.assertTrue(validate_workflow_graph(item["graph"], registry).valid)
|
||||
|
||||
async def test_research_evaluator_contract_avoids_contradictory_followups(self):
|
||||
research = next(item for item in BUILTIN_WORKFLOWS if item["slug"] == "research")
|
||||
evaluate = next(node for node in research["graph"]["nodes"] if node["id"] == "evaluate")
|
||||
config = evaluate["config"]
|
||||
|
||||
self.assertIn("If sufficient=true, follow_up_query must be an empty string", config["system_template"])
|
||||
self.assertIn("If sufficient=false, follow_up_query must be one concise web search query", config["system_template"])
|
||||
self.assertIn("Resolved request and router inputs", config["user_template"])
|
||||
167
backend/tests/test_workflow_runtime.py
Normal file
167
backend/tests/test_workflow_runtime.py
Normal file
@@ -0,0 +1,167 @@
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from backend.agent.models import WorkflowDefinition, WorkflowEvent, WorkflowRevision, WorkflowRun
|
||||
from backend.agent.registry import NativeToolProvider, ToolDefinition
|
||||
from backend.agent.runtime import WorkflowRuntime
|
||||
from backend.database import Base
|
||||
from backend.models import ChatMessage, ChatSession
|
||||
|
||||
|
||||
def graph(nodes, edges, maximum_tool_calls=10):
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"inputs": {"prompt": {"type": "string"}},
|
||||
"outputs": {"content": {"type": "string"}},
|
||||
"nodes": nodes,
|
||||
"edges": edges,
|
||||
"limits": {"maximum_nodes": 20, "maximum_tool_calls": maximum_tool_calls, "maximum_llm_calls": 5, "maximum_runtime_seconds": 5, "maximum_result_chars": 20000, "maximum_concurrency": 4},
|
||||
}
|
||||
|
||||
|
||||
def node(node_id, node_type, config=None):
|
||||
return {"id": node_id, "type": node_type, "position": {"x": 0, "y": 0}, "config": config or {}}
|
||||
|
||||
|
||||
def edge(source, target, handle="output"):
|
||||
return {"id": f"{source}-{target}-{handle}", "source": source, "source_handle": handle, "target": target, "target_handle": "input"}
|
||||
|
||||
|
||||
class RuntimeTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.engine = create_engine(f"sqlite:///{Path(self.temp.name) / 'test.db'}", connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(self.engine)
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
self.registry = NativeToolProvider()
|
||||
|
||||
async def echo(arguments, _context):
|
||||
await asyncio.sleep(arguments.get("delay", 0))
|
||||
if arguments.get("fail"):
|
||||
raise RuntimeError("requested failure")
|
||||
return {"content": arguments.get("text", ""), "sources": arguments.get("sources", [])}
|
||||
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string"}, "delay": {"type": "number"}, "fail": {"type": "boolean"}, "sources": {"type": "array"}},
|
||||
"required": ["text"], "additionalProperties": False,
|
||||
}
|
||||
output = {"type": "object", "properties": {"content": {"type": "string"}, "sources": {"type": "array"}}, "required": ["content", "sources"], "additionalProperties": False}
|
||||
self.registry.register(ToolDefinition("test.echo", "echo", schema, output, echo))
|
||||
self.runtime = WorkflowRuntime(self.registry, self.Session)
|
||||
|
||||
async def asyncTearDown(self):
|
||||
self.engine.dispose()
|
||||
self.temp.cleanup()
|
||||
|
||||
def create_run(self, graph_value, session=True):
|
||||
db = self.Session()
|
||||
workflow = WorkflowDefinition(slug=f"w-{uuid.uuid4().hex}", name="Test", built_in=False, enabled=True)
|
||||
db.add(workflow); db.flush()
|
||||
revision = WorkflowRevision(workflow_id=workflow.id, version=1, graph_json=json.dumps(graph_value), checksum="x", created_by="test")
|
||||
db.add(revision); db.flush(); workflow.current_revision_id = revision.id
|
||||
session_id = None
|
||||
user_id = None
|
||||
if session:
|
||||
chat = ChatSession(session_id=f"s-{id(graph_value)}")
|
||||
db.add(chat); db.flush()
|
||||
user = ChatMessage(session_pk=chat.id, role="user", content="hello")
|
||||
db.add(user); db.flush(); session_id = chat.session_id; user_id = user.message_id
|
||||
run = WorkflowRun(
|
||||
workflow_id=workflow.id, workflow_revision_id=revision.id, session_id=session_id, user_message_id=user_id,
|
||||
selection_mode="explicit", inputs_json=json.dumps({"input": {"prompt": "hello"}, "run": {"messages": [{"role": "user", "content": "hello"}]}}),
|
||||
)
|
||||
db.add(run); db.commit(); run_id = run.id; db.close()
|
||||
return run_id
|
||||
|
||||
async def execute(self, run_id):
|
||||
await self.runtime.execute(run_id)
|
||||
db = self.Session(); run = db.query(WorkflowRun).filter_by(id=run_id).first(); db.expunge(run); db.close(); return run
|
||||
|
||||
async def test_basic_persistence_and_source_propagation(self):
|
||||
value = graph(
|
||||
[node("input", "input"), node("echo", "tool", {"tool": "test.echo", "arguments": {"text": {"$ref": "input.prompt"}, "sources": [{"url": "https://example.com"}]}}), node("output", "output", {"value": {"$ref": "nodes.echo.output"}})],
|
||||
[edge("input", "echo"), edge("echo", "output")],
|
||||
)
|
||||
run = await self.execute(self.create_run(value))
|
||||
self.assertEqual(run.status, "completed")
|
||||
db = self.Session()
|
||||
assistant = db.query(ChatMessage).filter(ChatMessage.role == "assistant").one()
|
||||
self.assertEqual(assistant.content, "hello")
|
||||
self.assertEqual(json.loads(assistant.sources_json)[0]["url"], "https://example.com")
|
||||
self.assertTrue(db.query(WorkflowEvent).filter(WorkflowEvent.event_type == "source_found").count())
|
||||
db.close()
|
||||
|
||||
test_run = await self.execute(self.create_run(value, session=False))
|
||||
self.assertEqual(test_run.status, "completed")
|
||||
|
||||
async def test_concurrent_nodes_and_condition_branch(self):
|
||||
value = graph(
|
||||
[
|
||||
node("input", "input"),
|
||||
node("a", "tool", {"tool": "test.echo", "arguments": {"text": "a", "delay": 0.04}}),
|
||||
node("b", "tool", {"tool": "test.echo", "arguments": {"text": "b", "delay": 0.04}}),
|
||||
node("condition", "condition", {"value": True, "operation": "equals", "compare_to": True}),
|
||||
node("yes", "template", {"template": "yes"}),
|
||||
node("no", "template", {"template": "no"}),
|
||||
node("output", "output", {"value": {"content": {"$ref": "nodes.yes.output"}, "sources": []}}),
|
||||
],
|
||||
[edge("input", "a"), edge("input", "b"), edge("a", "condition"), edge("b", "condition"), edge("condition", "yes", "true"), edge("condition", "no", "false"), edge("yes", "output")],
|
||||
)
|
||||
run = await self.execute(self.create_run(value))
|
||||
self.assertEqual(run.status, "completed")
|
||||
db = self.Session()
|
||||
statuses = {row.node_id: row.status for row in db.query(__import__('backend.agent.models', fromlist=['WorkflowNodeRun']).WorkflowNodeRun).all()}
|
||||
self.assertEqual(statuses["no"], "skipped")
|
||||
db.close()
|
||||
|
||||
async def test_limit_preserves_sources_from_merged_context(self):
|
||||
value = graph(
|
||||
[
|
||||
node("input", "input"),
|
||||
node("a", "tool", {"tool": "test.echo", "arguments": {"text": "a" * 2000, "sources": [{"url": "https://a.example", "snippet": "a" * 500}]}}),
|
||||
node("b", "tool", {"tool": "test.echo", "arguments": {"text": "b" * 2000, "sources": [{"url": "https://b.example", "snippet": "b" * 500}]}}),
|
||||
node("merge", "merge", {"values": [{"$ref": "nodes.a.output"}, {"$ref": "nodes.b.output"}], "deduplicate_by": "url"}),
|
||||
node("limit", "limit", {"value": {"$ref": "nodes.merge.output"}, "maximum_chars": 80}),
|
||||
node("output", "output", {"value": {"content": "done", "sources": {"$ref": "nodes.limit.output.sources"}}}),
|
||||
],
|
||||
[edge("input", "a"), edge("a", "b"), edge("b", "merge"), edge("merge", "limit"), edge("limit", "output")],
|
||||
)
|
||||
run = await self.execute(self.create_run(value))
|
||||
self.assertEqual(run.status, "completed")
|
||||
db = self.Session()
|
||||
assistant = db.query(ChatMessage).filter(ChatMessage.role == "assistant").one()
|
||||
self.assertEqual([item["url"] for item in json.loads(assistant.sources_json)], ["https://a.example", "https://b.example"])
|
||||
db.close()
|
||||
|
||||
async def test_failure_cancellation_and_tool_limit(self):
|
||||
failing = graph(
|
||||
[node("input", "input"), node("bad", "tool", {"tool": "test.echo", "arguments": {"text": "x", "fail": True}}), node("output", "output", {"value": {"$ref": "nodes.bad.output"}})],
|
||||
[edge("input", "bad"), edge("bad", "output")],
|
||||
)
|
||||
self.assertEqual((await self.execute(self.create_run(failing))).status, "failed")
|
||||
|
||||
limited = graph(
|
||||
[node("input", "input"), node("a", "tool", {"tool": "test.echo", "arguments": {"text": "a"}}), node("b", "tool", {"tool": "test.echo", "arguments": {"text": "b"}}), node("output", "output", {"value": {"$ref": "nodes.b.output"}})],
|
||||
[edge("input", "a"), edge("a", "b"), edge("b", "output")], maximum_tool_calls=1,
|
||||
)
|
||||
self.assertEqual((await self.execute(self.create_run(limited))).status, "failed")
|
||||
|
||||
slow = graph(
|
||||
[node("input", "input"), node("slow", "tool", {"tool": "test.echo", "arguments": {"text": "x", "delay": 0.3}}), node("output", "output", {"value": {"$ref": "nodes.slow.output"}})],
|
||||
[edge("input", "slow"), edge("slow", "output")],
|
||||
)
|
||||
run_id = self.create_run(slow)
|
||||
task = asyncio.create_task(self.runtime.execute(run_id))
|
||||
await asyncio.sleep(0.03)
|
||||
self.runtime.cancel(run_id)
|
||||
await task
|
||||
db = self.Session(); status = db.query(WorkflowRun).filter_by(id=run_id).one().status; db.close()
|
||||
self.assertEqual(status, "cancelled")
|
||||
72
backend/tests/test_workflow_validation.py
Normal file
72
backend/tests/test_workflow_validation.py
Normal file
@@ -0,0 +1,72 @@
|
||||
import copy
|
||||
import unittest
|
||||
|
||||
from backend.agent.registry import NativeToolProvider, ToolDefinition
|
||||
from backend.agent.validation import validate_workflow_graph
|
||||
|
||||
|
||||
async def handler(arguments, _context):
|
||||
return {"content": arguments["text"]}
|
||||
|
||||
|
||||
def registry():
|
||||
value = NativeToolProvider()
|
||||
value.register(ToolDefinition(
|
||||
"test.echo", "echo",
|
||||
{"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"], "additionalProperties": False},
|
||||
{"type": "object", "properties": {"content": {"type": "string"}}, "required": ["content"], "additionalProperties": False},
|
||||
handler,
|
||||
))
|
||||
return value
|
||||
|
||||
|
||||
def valid_graph():
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"inputs": {"prompt": {"type": "string"}},
|
||||
"outputs": {"content": {"type": "string"}},
|
||||
"nodes": [
|
||||
{"id": "input", "type": "input", "position": {"x": 0, "y": 0}, "config": {}},
|
||||
{"id": "echo", "type": "tool", "position": {"x": 200, "y": 0}, "config": {"tool": "test.echo", "arguments": {"text": {"$ref": "input.prompt"}}}},
|
||||
{"id": "output", "type": "output", "position": {"x": 400, "y": 0}, "config": {"value": {"$ref": "nodes.echo.output"}}},
|
||||
],
|
||||
"edges": [
|
||||
{"id": "a", "source": "input", "source_handle": "output", "target": "echo", "target_handle": "input"},
|
||||
{"id": "b", "source": "echo", "source_handle": "output", "target": "output", "target_handle": "input"},
|
||||
],
|
||||
"limits": {"maximum_nodes": 10, "maximum_tool_calls": 5, "maximum_llm_calls": 2, "maximum_runtime_seconds": 30, "maximum_result_chars": 10000, "maximum_concurrency": 2},
|
||||
}
|
||||
|
||||
|
||||
class ValidationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.registry = registry()
|
||||
|
||||
def codes(self, graph):
|
||||
return {item.code for item in validate_workflow_graph(graph, self.registry).errors}
|
||||
|
||||
def test_valid_dag(self):
|
||||
self.assertTrue(validate_workflow_graph(valid_graph(), self.registry).valid)
|
||||
|
||||
def test_unknown_tool_missing_reference_unreachable_duplicate_and_cycle(self):
|
||||
graph = valid_graph(); graph["nodes"][1]["config"]["tool"] = "missing"
|
||||
self.assertIn("unknown_tool", self.codes(graph))
|
||||
graph = valid_graph(); graph["nodes"][1]["config"]["arguments"]["text"] = {"$ref": "input.missing"}
|
||||
self.assertIn("missing_reference", self.codes(graph))
|
||||
graph = valid_graph(); graph["nodes"].append({"id": "orphan", "type": "template", "position": {"x": 0, "y": 0}, "config": {"template": "x"}})
|
||||
self.assertIn("unreachable_node", self.codes(graph))
|
||||
graph = valid_graph(); graph["nodes"].append(copy.deepcopy(graph["nodes"][1]))
|
||||
self.assertIn("duplicate_node_id", self.codes(graph))
|
||||
graph = valid_graph(); graph["edges"].append({"id": "cycle", "source": "output", "source_handle": "output", "target": "echo", "target_handle": "input"})
|
||||
self.assertIn("cycle", self.codes(graph))
|
||||
|
||||
def test_invalid_branch_limits_and_schema(self):
|
||||
graph = valid_graph()
|
||||
graph["nodes"].insert(2, {"id": "condition", "type": "condition", "position": {"x": 300, "y": 0}, "config": {"value": True, "operation": "equals", "compare_to": True}})
|
||||
graph["edges"][1]["target"] = "condition"
|
||||
graph["edges"].append({"id": "condition-output", "source": "condition", "source_handle": "true", "target": "output", "target_handle": "input"})
|
||||
self.assertIn("invalid_branch", self.codes(graph))
|
||||
graph = valid_graph(); graph["limits"]["maximum_nodes"] = 999
|
||||
self.assertIn("excessive_limit", self.codes(graph))
|
||||
graph = valid_graph(); graph["inputs"]["prompt"] = {"type": "made-up"}
|
||||
self.assertIn("malformed_schema", self.codes(graph))
|
||||
445
backend/video_ingest.py
Normal file
445
backend/video_ingest.py
Normal file
@@ -0,0 +1,445 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
import httpx
|
||||
|
||||
from .app_settings import (
|
||||
get_enrichment_model_preference,
|
||||
get_ollama_api_url,
|
||||
get_transcription_model_preference,
|
||||
)
|
||||
from .ollama_client import chat as ollama_chat
|
||||
from .paths import tool_root
|
||||
from .rag.corpus_builder import (
|
||||
_transcribe_slice,
|
||||
_whisper_pool_init,
|
||||
merge_transcripts,
|
||||
slice_audio,
|
||||
)
|
||||
from .whisper_admin import ensure_whisper_model_downloaded
|
||||
|
||||
|
||||
YTDLP_RELEASE_URL = "https://github.com/yt-dlp/yt-dlp/releases/latest/download"
|
||||
YTDLP_UPDATE_INTERVAL_SECONDS = 6 * 60 * 60
|
||||
YTDLP_STATUS_FILE = "update.json"
|
||||
SUMMARY_PROMPT_TEMPLATE = """You are an expert summarizer. Summarize the following video concisely:
|
||||
|
||||
Title: {title}
|
||||
|
||||
Transcript:
|
||||
{transcript}
|
||||
|
||||
Summary:"""
|
||||
OLLAMA_CHARS_PER_TOKEN = 3.5
|
||||
OLLAMA_OUTPUT_TOKEN_BUDGET = 2048
|
||||
OLLAMA_CONTEXT_BUCKETS = (4096, 8192, 16384, 32768, 65536)
|
||||
NUM_SLICES = 8
|
||||
OVERLAP_SECONDS = 1.0
|
||||
MAX_OVERLAP_WORDS = 7
|
||||
MEDIA_HOST_MARKERS = (
|
||||
"youtube.com",
|
||||
"youtu.be",
|
||||
"vimeo.com",
|
||||
"tiktok.com",
|
||||
"instagram.com",
|
||||
"twitch.tv",
|
||||
"soundcloud.com",
|
||||
"facebook.com",
|
||||
"fb.watch",
|
||||
"dailymotion.com",
|
||||
)
|
||||
|
||||
_YTDLP_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class UnsupportedVideoUrl(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _yt_dlp_asset_name() -> str:
|
||||
system = platform.system().lower()
|
||||
machine = platform.machine().lower()
|
||||
if system == "windows":
|
||||
return "yt-dlp_arm64.exe" if machine in {"arm64", "aarch64"} else "yt-dlp.exe"
|
||||
if system == "darwin":
|
||||
return "yt-dlp_macos"
|
||||
if system == "linux":
|
||||
if machine in {"arm64", "aarch64"}:
|
||||
return "yt-dlp_linux_aarch64"
|
||||
if machine.startswith("armv7"):
|
||||
return "yt-dlp_linux_armv7l"
|
||||
return "yt-dlp_linux"
|
||||
return "yt-dlp"
|
||||
|
||||
|
||||
def _yt_dlp_binary_name() -> str:
|
||||
return "yt-dlp.exe" if os.name == "nt" else "yt-dlp"
|
||||
|
||||
|
||||
def _executable_version(path: Path) -> Optional[str]:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[str(path), "--version"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=20,
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return (result.stdout or result.stderr).strip().splitlines()[0].strip() or None
|
||||
|
||||
|
||||
def _read_update_status(status_path: Path) -> Dict[str, Any]:
|
||||
try:
|
||||
payload = json.loads(status_path.read_text(encoding="utf-8"))
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _update_due(binary_path: Path, status_path: Path) -> bool:
|
||||
if not binary_path.exists() or not _executable_version(binary_path):
|
||||
return True
|
||||
last_check = _read_update_status(status_path).get("last_check")
|
||||
if not isinstance(last_check, (int, float)):
|
||||
return True
|
||||
return (time.time() - float(last_check)) >= YTDLP_UPDATE_INTERVAL_SECONDS
|
||||
|
||||
|
||||
def _download_latest_yt_dlp(binary_path: Path, status_path: Path) -> Optional[str]:
|
||||
url = f"{YTDLP_RELEASE_URL}/{_yt_dlp_asset_name()}"
|
||||
tmp_path = binary_path.with_suffix(binary_path.suffix + ".download")
|
||||
try:
|
||||
timeout = httpx.Timeout(120.0, connect=10.0)
|
||||
with httpx.stream("GET", url, follow_redirects=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
with tmp_path.open("wb") as handle:
|
||||
for chunk in response.iter_bytes(chunk_size=1024 * 1024):
|
||||
if chunk:
|
||||
handle.write(chunk)
|
||||
if os.name != "nt":
|
||||
tmp_path.chmod(0o755)
|
||||
version = _executable_version(tmp_path)
|
||||
if not version:
|
||||
raise RuntimeError("Downloaded yt-dlp executable did not run.")
|
||||
os.replace(tmp_path, binary_path)
|
||||
if os.name != "nt":
|
||||
binary_path.chmod(0o755)
|
||||
status_path.write_text(
|
||||
json.dumps({"last_check": time.time(), "version": version, "source": url}, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return version
|
||||
except Exception:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def resolve_yt_dlp() -> Tuple[str, str]:
|
||||
override = str(os.getenv("HEIMGEIST_YTDLP_PATH") or "").strip()
|
||||
if override:
|
||||
path = Path(override).expanduser()
|
||||
version = _executable_version(path)
|
||||
if not version:
|
||||
raise RuntimeError(f"Configured yt-dlp executable is unavailable: {path}")
|
||||
return str(path), version
|
||||
|
||||
with _YTDLP_LOCK:
|
||||
target_dir = tool_root() / "yt-dlp"
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
binary_path = target_dir / _yt_dlp_binary_name()
|
||||
status_path = target_dir / YTDLP_STATUS_FILE
|
||||
version = _executable_version(binary_path)
|
||||
if _update_due(binary_path, status_path):
|
||||
updated = _download_latest_yt_dlp(binary_path, status_path)
|
||||
if updated:
|
||||
return str(binary_path), updated
|
||||
if version := _executable_version(binary_path):
|
||||
return str(binary_path), version
|
||||
|
||||
system_path = shutil.which("yt-dlp")
|
||||
if system_path and (version := _executable_version(Path(system_path))):
|
||||
return system_path, version
|
||||
raise RuntimeError("Heimgeist could not download or locate yt-dlp.")
|
||||
|
||||
|
||||
def _ffmpeg_binary() -> str:
|
||||
candidate = str(os.getenv("HEIMGEIST_FFMPEG_PATH") or shutil.which("ffmpeg") or "").strip()
|
||||
if not candidate:
|
||||
raise RuntimeError("Video ingestion requires ffmpeg.")
|
||||
return candidate
|
||||
|
||||
|
||||
def _ffprobe_binary() -> str:
|
||||
candidate = str(os.getenv("HEIMGEIST_FFPROBE_PATH") or shutil.which("ffprobe") or "").strip()
|
||||
if not candidate:
|
||||
raise RuntimeError("Video ingestion requires ffprobe.")
|
||||
return candidate
|
||||
|
||||
|
||||
def _run_yt_dlp(args: List[str], *, timeout: Optional[float] = None) -> subprocess.CompletedProcess:
|
||||
executable, _version = resolve_yt_dlp()
|
||||
env = os.environ.copy()
|
||||
ffmpeg_dir = str(Path(_ffmpeg_binary()).parent)
|
||||
path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry]
|
||||
if ffmpeg_dir and ffmpeg_dir not in path_entries:
|
||||
path_entries.insert(0, ffmpeg_dir)
|
||||
env["PATH"] = os.pathsep.join(path_entries)
|
||||
result = subprocess.run(
|
||||
[executable, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=timeout,
|
||||
env=env,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout or "yt-dlp failed").strip()
|
||||
if "Unsupported URL" in detail:
|
||||
raise UnsupportedVideoUrl(detail)
|
||||
raise RuntimeError(detail)
|
||||
return result
|
||||
|
||||
|
||||
def _parse_metadata(stdout: str) -> Dict[str, Any]:
|
||||
for line in reversed([line.strip() for line in stdout.splitlines() if line.strip()]):
|
||||
try:
|
||||
payload = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(payload, dict):
|
||||
return payload
|
||||
raise RuntimeError("yt-dlp returned no usable metadata.")
|
||||
|
||||
|
||||
def _looks_like_video_metadata(metadata: Dict[str, Any]) -> bool:
|
||||
formats = metadata.get("formats")
|
||||
if not isinstance(formats, list) or not formats:
|
||||
return False
|
||||
return bool(
|
||||
metadata.get("duration")
|
||||
or metadata.get("acodec") not in {None, "none"}
|
||||
or metadata.get("vcodec") not in {None, "none"}
|
||||
)
|
||||
|
||||
|
||||
def is_likely_media_url(url: str) -> bool:
|
||||
lowered = str(url or "").lower()
|
||||
return any(marker in lowered for marker in MEDIA_HOST_MARKERS)
|
||||
|
||||
|
||||
def probe_video_url(url: str) -> Optional[Dict[str, Any]]:
|
||||
result = _run_yt_dlp(
|
||||
["--no-playlist", "--skip-download", "--dump-single-json", "--no-warnings", url],
|
||||
timeout=180,
|
||||
)
|
||||
metadata = _parse_metadata(result.stdout)
|
||||
return metadata if _looks_like_video_metadata(metadata) else None
|
||||
|
||||
|
||||
def _download_audio(url: str, temp_dir: Path) -> Path:
|
||||
output_template = str(temp_dir / "audio.%(ext)s")
|
||||
args = [
|
||||
"--no-playlist",
|
||||
"--format", "bestaudio/best",
|
||||
"--output", output_template,
|
||||
"--no-progress",
|
||||
"--no-part",
|
||||
"--no-continue",
|
||||
"--force-overwrites",
|
||||
"--retries", "3",
|
||||
"--fragment-retries", "3",
|
||||
"--extract-audio",
|
||||
"--audio-format", "wav",
|
||||
"--ffmpeg-location", str(Path(_ffmpeg_binary()).parent),
|
||||
url,
|
||||
]
|
||||
_run_yt_dlp(args, timeout=60 * 60)
|
||||
expected = temp_dir / "audio.wav"
|
||||
if expected.exists():
|
||||
return expected
|
||||
matches = list(temp_dir.glob("audio*.wav"))
|
||||
if matches:
|
||||
return matches[0]
|
||||
raise RuntimeError("yt-dlp completed without producing an audio file.")
|
||||
|
||||
|
||||
def _transcription_workers(model_name: str, slice_count: int) -> int:
|
||||
override = str(os.getenv("HEIMGEIST_VIDEO_WHISPER_WORKERS") or "").strip()
|
||||
if override:
|
||||
try:
|
||||
return max(1, min(slice_count, int(override)))
|
||||
except ValueError:
|
||||
pass
|
||||
if any(marker in model_name.lower() for marker in ("medium", "large")):
|
||||
return 1
|
||||
return max(1, min(slice_count, 2, max(1, (os.cpu_count() or 2) // 2)))
|
||||
|
||||
|
||||
def _transcribe_audio(audio_path: Path, temp_dir: Path, model_name: str) -> Tuple[str, Dict[str, Any]]:
|
||||
ensure_whisper_model_downloaded(model_name)
|
||||
slice_dir = temp_dir / "slices"
|
||||
slice_dir.mkdir(parents=True, exist_ok=True)
|
||||
slices = slice_audio(
|
||||
audio_path,
|
||||
slice_dir,
|
||||
NUM_SLICES,
|
||||
OVERLAP_SECONDS,
|
||||
_ffprobe_binary(),
|
||||
_ffmpeg_binary(),
|
||||
)
|
||||
workers = _transcription_workers(model_name, len(slices))
|
||||
context = mp.get_context("spawn")
|
||||
pool = context.Pool(
|
||||
processes=workers,
|
||||
initializer=_whisper_pool_init,
|
||||
initargs=(model_name, "cpu"),
|
||||
)
|
||||
try:
|
||||
jobs = [(path, index, audio_path.stem) for index, (path, _start, _end) in enumerate(slices)]
|
||||
results = pool.starmap(_transcribe_slice, [("transcribe", job) for job in jobs])
|
||||
except BaseException:
|
||||
pool.terminate()
|
||||
pool.join()
|
||||
raise
|
||||
else:
|
||||
pool.close()
|
||||
pool.join()
|
||||
transcript = merge_transcripts(results, MAX_OVERLAP_WORDS).strip()
|
||||
if not transcript:
|
||||
raise RuntimeError("Whisper returned an empty transcript.")
|
||||
return transcript, {"model": model_name, "workers": workers, "slices": len(slices)}
|
||||
|
||||
|
||||
def _choose_num_ctx(prompt: str) -> int:
|
||||
estimated_input_tokens = math.ceil(len(prompt) / OLLAMA_CHARS_PER_TOKEN)
|
||||
needed = estimated_input_tokens + OLLAMA_OUTPUT_TOKEN_BUDGET
|
||||
for bucket in OLLAMA_CONTEXT_BUCKETS:
|
||||
if needed <= bucket:
|
||||
return bucket
|
||||
return OLLAMA_CONTEXT_BUCKETS[-1]
|
||||
|
||||
|
||||
async def _summarize(title: str, transcript: str, model_name: str) -> str:
|
||||
prompt = SUMMARY_PROMPT_TEMPLATE.replace("{title}", title).replace("{transcript}", transcript)
|
||||
summary = await ollama_chat(
|
||||
model_name,
|
||||
[
|
||||
{"role": "system", "content": "You are an intelligent summarizer."},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
options={"num_ctx": _choose_num_ctx(prompt)},
|
||||
)
|
||||
clean = re.sub(r"<think>.*?</think>", "", str(summary or ""), flags=re.DOTALL | re.IGNORECASE).strip()
|
||||
clean = re.sub(r"^\s*Summary:\s*", "", clean, flags=re.IGNORECASE).strip()
|
||||
if not clean:
|
||||
raise RuntimeError("Ollama returned an empty video summary.")
|
||||
return clean
|
||||
|
||||
|
||||
def _format_duration(value: Any) -> str:
|
||||
try:
|
||||
total = max(0, int(float(value)))
|
||||
except Exception:
|
||||
return ""
|
||||
hours, remainder = divmod(total, 3600)
|
||||
minutes, seconds = divmod(remainder, 60)
|
||||
return f"{hours:d}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes:d}:{seconds:02d}"
|
||||
|
||||
|
||||
def build_video_document(metadata: Dict[str, Any], summary: str, transcript: str) -> str:
|
||||
title = str(metadata.get("title") or "Video").strip()
|
||||
url = str(metadata.get("webpage_url") or metadata.get("original_url") or "").strip()
|
||||
uploader = str(metadata.get("channel") or metadata.get("uploader") or "").strip()
|
||||
duration = _format_duration(metadata.get("duration"))
|
||||
lines = [f"# {title}"]
|
||||
if url:
|
||||
lines.append(f"Source: {url}")
|
||||
if uploader:
|
||||
lines.append(f"Channel: {uploader}")
|
||||
if duration:
|
||||
lines.append(f"Duration: {duration}")
|
||||
lines.extend(["", "## Summary", summary.strip(), "", "## Transcript", transcript.strip()])
|
||||
return "\n".join(lines).strip() + "\n"
|
||||
|
||||
|
||||
async def ingest_video_url(
|
||||
url: str,
|
||||
metadata: Dict[str, Any],
|
||||
*,
|
||||
progress: Optional[Callable[[str, float, str], None]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
def report(phase: str, pct: float, detail: str) -> None:
|
||||
if progress:
|
||||
progress(phase, pct, detail)
|
||||
|
||||
title = str(metadata.get("title") or metadata.get("id") or "Video").strip()
|
||||
transcription_model = get_transcription_model_preference()
|
||||
summary_model = get_enrichment_model_preference()
|
||||
_executable, yt_dlp_version = await _to_thread(resolve_yt_dlp)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="heimgeist-video-") as raw_temp_dir:
|
||||
temp_dir = Path(raw_temp_dir)
|
||||
report("download", 0.08, "Downloading video audio...")
|
||||
audio_path = await _to_thread(_download_audio, url, temp_dir)
|
||||
report("transcribe", 0.25, f"Transcribing audio with Whisper {transcription_model}...")
|
||||
transcript, transcription = await _to_thread(
|
||||
_transcribe_audio,
|
||||
audio_path,
|
||||
temp_dir,
|
||||
transcription_model,
|
||||
)
|
||||
report("summarize", 0.72, f"Summarizing transcript with {summary_model}...")
|
||||
summary = await _summarize(title, transcript, summary_model)
|
||||
|
||||
report("save", 0.9, "Saving transcript and metadata...")
|
||||
canonical_url = str(metadata.get("webpage_url") or metadata.get("original_url") or url).strip()
|
||||
return {
|
||||
"title": title,
|
||||
"url": canonical_url,
|
||||
"requested_url": url,
|
||||
"video_id": str(metadata.get("id") or "").strip() or None,
|
||||
"extractor": str(metadata.get("extractor_key") or metadata.get("extractor") or "").strip() or None,
|
||||
"channel": str(metadata.get("channel") or metadata.get("uploader") or "").strip() or None,
|
||||
"duration": metadata.get("duration"),
|
||||
"duration_text": _format_duration(metadata.get("duration")),
|
||||
"upload_date": metadata.get("upload_date"),
|
||||
"thumbnail_url": metadata.get("thumbnail"),
|
||||
"transcript": transcript,
|
||||
"summary": summary,
|
||||
"document": build_video_document(metadata, summary, transcript),
|
||||
"transcription_model": transcription["model"],
|
||||
"transcription_workers": transcription["workers"],
|
||||
"transcription_slices": transcription["slices"],
|
||||
"summary_model": summary_model,
|
||||
"yt_dlp_version": yt_dlp_version,
|
||||
"fetched_at": datetime.utcnow().isoformat(timespec="seconds") + "Z",
|
||||
}
|
||||
|
||||
|
||||
async def _to_thread(fn, *args):
|
||||
import asyncio
|
||||
|
||||
return await asyncio.to_thread(fn, *args)
|
||||
825
backend/websearch.py
Normal file
825
backend/websearch.py
Normal file
@@ -0,0 +1,825 @@
|
||||
import asyncio
|
||||
from typing import List, Tuple, Dict, Any, Optional
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
import re
|
||||
import json
|
||||
import traceback
|
||||
import hashlib
|
||||
|
||||
from .app_settings import get_ollama_api_url, get_rerank_model_preference
|
||||
from .ollama_client import chat as ollama_chat
|
||||
|
||||
# Configure your local SearXNG instance URL (no trailing slash)
|
||||
SEARX_URL = "http://127.0.0.1:8888"
|
||||
|
||||
# ----- Utilities ----------------------------------------------------------------
|
||||
|
||||
def clean_text(html: str, max_len: int = 120_000) -> str:
|
||||
# Prefer lxml parser if available (significantly faster); fall back gracefully.
|
||||
try:
|
||||
soup = BeautifulSoup(html, "lxml")
|
||||
except Exception:
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
for tag in soup.select("script,style,noscript"):
|
||||
tag.decompose()
|
||||
|
||||
# Fast text extraction
|
||||
text = soup.get_text("\n", strip=True)
|
||||
text = re.sub(r"[ \t]+", " ", text)
|
||||
text = re.sub(r"\n{3,}", "\n\n", text)
|
||||
|
||||
return text[:max_len] if len(text) > max_len else text
|
||||
|
||||
def render_recent_context(messages: Optional[List[Dict[str, str]]], char_limit: int = 1200) -> str:
|
||||
"""
|
||||
Turn the last few turns into a compact excerpt:
|
||||
user: ...
|
||||
assistant: ...
|
||||
Truncate aggressively for resource-friendliness.
|
||||
"""
|
||||
if not messages:
|
||||
return ""
|
||||
# Keep as-is order (oldest->newest). We assume caller already sliced last N.
|
||||
lines: List[str] = []
|
||||
for m in messages:
|
||||
role = m.get("role", "user")
|
||||
content = (m.get("content") or "").strip()
|
||||
if not content:
|
||||
continue
|
||||
# compactify each line
|
||||
content = re.sub(r"\s+", " ", content)
|
||||
lines.append(f"{role}: {content}")
|
||||
joined = "\n".join(lines)
|
||||
if len(joined) > char_limit:
|
||||
return joined[-char_limit:] # keep tail (most recent part)
|
||||
return joined
|
||||
|
||||
# ----- SearXNG search & fetching -------------------------------------------------
|
||||
|
||||
from urllib.parse import urljoin, urlparse
|
||||
import itertools
|
||||
|
||||
# HTTP client tuning (keep-alive pool + HTTP/2)
|
||||
HTTP_LIMITS = httpx.Limits(max_keepalive_connections=32, max_connections=64)
|
||||
HTTP_TIMEOUT = httpx.Timeout(connect=5.0, read=10.0, write=10.0, pool=5.0)
|
||||
DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome Safari",
|
||||
"Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",
|
||||
}
|
||||
|
||||
# Fetch policy
|
||||
MAX_PAGES_FETCH = 8 # lower cap of pages we’ll fetch per enrichment
|
||||
FETCH_CONCURRENCY = 8 # concurrent page fetches
|
||||
MAX_BYTES_PER_PAGE = 1_500_000 # ~1.5 MB read cap per page (streamed)
|
||||
MIN_TEXT_LENGTH = 500 # discard useless pages early
|
||||
|
||||
SKIP_EXTS = {
|
||||
".pdf", ".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg",
|
||||
".mp4", ".mp3", ".mov", ".avi", ".zip", ".gz", ".7z", ".tar", ".rar",
|
||||
".woff", ".woff2", ".ttf", ".otf"
|
||||
}
|
||||
|
||||
_PAGE_CACHE: Dict[str, str] = {} # naive in-proc cache (speeds repeated calls)
|
||||
_EMB_CACHE: Dict[str, List[float]] = {} # NEW: embedding cache by SHA1 of snippet
|
||||
|
||||
_RANK_STOPWORDS = {
|
||||
"about", "after", "again", "against", "also", "and", "any", "are", "because",
|
||||
"been", "before", "being", "but", "can", "could", "current", "does", "for",
|
||||
"from", "had", "has", "have", "how", "into", "its", "latest", "more", "most",
|
||||
"new", "news", "not", "now", "off", "out", "over", "please", "should", "than",
|
||||
"that", "the", "their", "them", "then", "there", "these", "they", "this",
|
||||
"today", "was", "were", "what", "when", "where", "which", "while", "who",
|
||||
"why", "will", "with", "would", "you", "your",
|
||||
}
|
||||
|
||||
|
||||
def _rank_tokens(text: str) -> List[str]:
|
||||
return [
|
||||
token.casefold()
|
||||
for token in re.findall(r"\b[\w-]{3,}\b", text or "", flags=re.UNICODE)
|
||||
if token.casefold() not in _RANK_STOPWORDS
|
||||
]
|
||||
|
||||
|
||||
def fallback_rerank(
|
||||
prompt: str,
|
||||
docs: List[Tuple[str, str]],
|
||||
context_excerpt: str = "",
|
||||
*,
|
||||
reason: str = "embedding_unavailable",
|
||||
) -> List[Tuple[str, str, float]]:
|
||||
"""
|
||||
Rank pages without embeddings so web search can still produce context when
|
||||
the configured embedding/reranking model is missing or Ollama is offline.
|
||||
"""
|
||||
if not docs:
|
||||
return []
|
||||
|
||||
query_text = f"{prompt or ''} {context_excerpt[-600:] if context_excerpt else ''}"
|
||||
query_terms = list(dict.fromkeys(_rank_tokens(query_text)))[:36]
|
||||
prompt_phrase = " ".join(str(prompt or "").casefold().split())
|
||||
if len(prompt_phrase) < 6 or len(prompt_phrase) > 160:
|
||||
prompt_phrase = ""
|
||||
|
||||
scored: List[Tuple[str, str, float]] = []
|
||||
doc_count = max(1, len(docs))
|
||||
for index, (url, text) in enumerate(docs):
|
||||
sample = f"{url} {(text or '')[:6000]}"
|
||||
sample_lower = sample.casefold()
|
||||
sample_tokens = _rank_tokens(sample)
|
||||
sample_set = set(sample_tokens)
|
||||
|
||||
coverage = 0.0
|
||||
frequency = 0.0
|
||||
if query_terms:
|
||||
matches = [term for term in query_terms if term in sample_set or term in sample_lower]
|
||||
coverage = len(matches) / len(query_terms)
|
||||
frequency = min(
|
||||
1.0,
|
||||
sum(min(sample_lower.count(term), 3) for term in query_terms)
|
||||
/ max(1, len(query_terms) * 2),
|
||||
)
|
||||
|
||||
order_signal = 1.0 - (index / doc_count)
|
||||
length_signal = min(1.0, len(text or "") / 2500.0)
|
||||
phrase_signal = 1.0 if prompt_phrase and prompt_phrase in sample_lower else 0.0
|
||||
raw = (
|
||||
0.52 * coverage
|
||||
+ 0.18 * frequency
|
||||
+ 0.16 * order_signal
|
||||
+ 0.08 * length_signal
|
||||
+ 0.06 * phrase_signal
|
||||
)
|
||||
score = 58.0 + min(1.0, raw) * 34.0
|
||||
if coverage > 0 or phrase_signal > 0:
|
||||
score = max(score, 72.0 - min(index, 4) * 1.25)
|
||||
scored.append((url, text, max(0.0, min(100.0, score))))
|
||||
|
||||
scored.sort(key=lambda item: item[2], reverse=True)
|
||||
|
||||
if scored and scored[0][2] < 70.0:
|
||||
# SearXNG already ranked these URLs. If lexical signals are weak, keep
|
||||
# web search usable by passing through a small ordered sample.
|
||||
adjusted: List[Tuple[str, str, float]] = []
|
||||
for rank, (url, text, score) in enumerate(scored):
|
||||
passthrough_score = 72.0 - rank
|
||||
adjusted.append((url, text, max(score, passthrough_score if rank < 3 else score)))
|
||||
scored = adjusted
|
||||
|
||||
print(f"[web] embedding rerank unavailable ({reason}); using lexical fallback over {len(docs)} docs")
|
||||
return scored
|
||||
|
||||
|
||||
def _is_probably_html_url(url: str) -> bool:
|
||||
try:
|
||||
path = urlparse(url).path.lower()
|
||||
ext = (path.rsplit(".", 1)[-1] if "." in path else "")
|
||||
return (("." not in path) or (ext and f".{ext}" not in SKIP_EXTS))
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
async def searx_search(
|
||||
client: httpx.AsyncClient,
|
||||
query: str,
|
||||
max_results: int = 6,
|
||||
*,
|
||||
searx_url: Optional[str] = None,
|
||||
engines: Optional[List[str]] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
base_url = (searx_url or SEARX_URL).rstrip("/")
|
||||
params = {"q": query, "format": "json", "safesearch": 1}
|
||||
if engines:
|
||||
# SearXNG accepts a comma-separated 'engines' filter
|
||||
params["engines"] = ",".join(engines)
|
||||
|
||||
try:
|
||||
r = await client.get(f"{base_url}/search", params=params)
|
||||
r.raise_for_status()
|
||||
except Exception as e:
|
||||
print(f"[web] searx_search error for {base_url} q='{query}': {repr(e)}")
|
||||
return []
|
||||
|
||||
try:
|
||||
data = r.json()
|
||||
except Exception as e:
|
||||
print(f"[web] searx_search JSON parse failed q='{query}': {repr(e)} | content-type={r.headers.get('content-type')}")
|
||||
return []
|
||||
|
||||
seen = set()
|
||||
out = []
|
||||
for item in data.get("results", []):
|
||||
url = item.get("url")
|
||||
if not url or url in seen:
|
||||
continue
|
||||
seen.add(url)
|
||||
out.append({"url": url, "title": item.get("title", ""), "engine": item.get("engine")})
|
||||
if len(out) >= max_results:
|
||||
break
|
||||
if not out:
|
||||
print(f"[web] searx_search returned 0 urls for q='{query}' (engines={engines})")
|
||||
return out
|
||||
|
||||
async def searx_search_many(
|
||||
client: httpx.AsyncClient,
|
||||
queries: List[str],
|
||||
per_query_max: int = 6,
|
||||
overall_max: int = 32,
|
||||
*,
|
||||
searx_url: Optional[str] = None,
|
||||
engines: Optional[List[str]] = None,
|
||||
) -> List[str]:
|
||||
print(f"[web] searx_search_many: {len(queries)} queries -> {searx_url or SEARX_URL} engines={engines or 'default'}")
|
||||
tasks = [searx_search(client, q, max_results=per_query_max, searx_url=searx_url, engines=engines) for q in queries]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
urls: List[str] = []
|
||||
seen = set()
|
||||
for q, res in zip(queries, results):
|
||||
if isinstance(res, Exception):
|
||||
print(f"[web] searx_search_many task error q='{q}': {repr(res)}")
|
||||
continue
|
||||
for item in res:
|
||||
u = item.get("url")
|
||||
if not u or u in seen:
|
||||
continue
|
||||
if not _is_probably_html_url(u):
|
||||
print(f"[web] skip non-HTML url: {u}")
|
||||
continue
|
||||
seen.add(u)
|
||||
urls.append(u)
|
||||
if len(urls) >= overall_max:
|
||||
print(f"[web] searx_search_many hit overall_max={overall_max}")
|
||||
return urls
|
||||
print(f"[web] searx_search_many collected {len(urls)} urls")
|
||||
return urls
|
||||
|
||||
async def fetch_page(client: httpx.AsyncClient, url: str) -> str:
|
||||
if url in _PAGE_CACHE:
|
||||
return _PAGE_CACHE[url]
|
||||
if not _is_probably_html_url(url):
|
||||
return ""
|
||||
|
||||
try:
|
||||
async with client.stream("GET", url, headers=DEFAULT_HEADERS) as r:
|
||||
ctype = (r.headers.get("content-type") or "").lower()
|
||||
if ctype and not ("text/html" in ctype or "application/xhtml+xml" in ctype or ctype.startswith("text/")):
|
||||
print(f"[web] skip content-type {ctype} url={url}")
|
||||
return ""
|
||||
|
||||
buf = bytearray()
|
||||
async for chunk in r.aiter_bytes():
|
||||
if not chunk:
|
||||
break
|
||||
buf.extend(chunk)
|
||||
if len(buf) >= MAX_BYTES_PER_PAGE:
|
||||
break
|
||||
|
||||
try:
|
||||
text = buf.decode(r.encoding or "utf-8", errors="ignore")
|
||||
except Exception:
|
||||
text = buf.decode("utf-8", errors="ignore")
|
||||
|
||||
_PAGE_CACHE[url] = text
|
||||
return text
|
||||
except Exception as e:
|
||||
print(f"[web] fetch_page error url={url}: {repr(e)}")
|
||||
return ""
|
||||
|
||||
|
||||
async def fetch_website_snapshot(url: str) -> Dict[str, Any]:
|
||||
"""Fetch one user-supplied web page and return a durable text snapshot."""
|
||||
requested_url = str(url or "").strip()
|
||||
parsed = urlparse(requested_url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("Enter a valid http:// or https:// website URL.")
|
||||
if not _is_probably_html_url(requested_url):
|
||||
raise ValueError("This URL does not appear to point to a web page.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
headers=DEFAULT_HEADERS,
|
||||
follow_redirects=True,
|
||||
http2=True,
|
||||
limits=HTTP_LIMITS,
|
||||
timeout=HTTP_TIMEOUT,
|
||||
) as client:
|
||||
async with client.stream("GET", requested_url) as response:
|
||||
response.raise_for_status()
|
||||
content_type = (response.headers.get("content-type") or "").lower()
|
||||
if content_type and not (
|
||||
"text/html" in content_type
|
||||
or "application/xhtml+xml" in content_type
|
||||
or content_type.startswith("text/")
|
||||
):
|
||||
raise ValueError(f"Unsupported website content type: {content_type.split(';', 1)[0]}")
|
||||
|
||||
payload = bytearray()
|
||||
async for chunk in response.aiter_bytes():
|
||||
if not chunk:
|
||||
continue
|
||||
remaining = MAX_BYTES_PER_PAGE - len(payload)
|
||||
if remaining <= 0:
|
||||
break
|
||||
payload.extend(chunk[:remaining])
|
||||
|
||||
encoding = response.encoding or "utf-8"
|
||||
html = bytes(payload).decode(encoding, errors="ignore")
|
||||
final_url = str(response.url)
|
||||
|
||||
try:
|
||||
soup = BeautifulSoup(html, "lxml")
|
||||
except Exception:
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
title = ""
|
||||
if soup.title:
|
||||
title = re.sub(r"\s+", " ", soup.title.get_text(" ", strip=True)).strip()
|
||||
if not title:
|
||||
heading = soup.find(["h1", "h2"])
|
||||
if heading:
|
||||
title = re.sub(r"\s+", " ", heading.get_text(" ", strip=True)).strip()
|
||||
|
||||
canonical_url = final_url
|
||||
canonical = soup.find("link", rel=lambda value: value and "canonical" in str(value).lower())
|
||||
if canonical and canonical.get("href"):
|
||||
candidate = urljoin(final_url, str(canonical.get("href")).strip())
|
||||
candidate_parsed = urlparse(candidate)
|
||||
if candidate_parsed.scheme in {"http", "https"} and candidate_parsed.netloc:
|
||||
canonical_url = candidate
|
||||
|
||||
text = clean_text(html)
|
||||
if len(text.strip()) < 80:
|
||||
raise ValueError("The website did not contain enough readable text to save.")
|
||||
if not title:
|
||||
first_line = next((line.strip() for line in text.splitlines() if line.strip()), "")
|
||||
title = re.sub(r"^[#>*_`\-\s]+", "", first_line).strip()[:240]
|
||||
|
||||
return {
|
||||
"requested_url": requested_url,
|
||||
"url": canonical_url,
|
||||
"final_url": final_url,
|
||||
"title": title or urlparse(final_url).netloc,
|
||||
"text": text.strip(),
|
||||
"html": html,
|
||||
"content_type": content_type.split(";", 1)[0] or "text/html",
|
||||
"etag": response.headers.get("etag"),
|
||||
"last_modified": response.headers.get("last-modified"),
|
||||
}
|
||||
|
||||
async def gather_pages(
|
||||
client: httpx.AsyncClient,
|
||||
urls: List[str],
|
||||
max_pages: int = MAX_PAGES_FETCH,
|
||||
) -> Dict[str, str]:
|
||||
urls = list(itertools.islice(urls, 0, max_pages))
|
||||
sem = asyncio.Semaphore(FETCH_CONCURRENCY)
|
||||
out: Dict[str, str] = {}
|
||||
counters = {"tried": 0, "ok": 0, "too_short": 0, "empty": 0}
|
||||
|
||||
async def _one(u: str):
|
||||
async with sem:
|
||||
counters["tried"] += 1
|
||||
html = await fetch_page(client, u)
|
||||
if not html:
|
||||
counters["empty"] += 1
|
||||
return
|
||||
txt = clean_text(html)
|
||||
if len(txt) < MIN_TEXT_LENGTH:
|
||||
counters["too_short"] += 1
|
||||
return
|
||||
out[u] = txt
|
||||
counters["ok"] += 1
|
||||
|
||||
await asyncio.gather(*(_one(u) for u in urls))
|
||||
print(f"[web] gather_pages summary: {counters} / returned={len(out)}")
|
||||
return out
|
||||
|
||||
# ----- LLM helpers ---------------------------------------------------------------
|
||||
|
||||
async def generate_queries(prompt: str, model: str, context_excerpt: str) -> List[str]:
|
||||
"""
|
||||
Single LLM call that *already* incorporates recent chat context to
|
||||
resolve ellipses/pronouns. No extra rounds.
|
||||
"""
|
||||
ctx_block = f"\nRecent conversation (latest last):\n{context_excerpt}\n" if context_excerpt else ""
|
||||
ask = f"""You are a search query generator.
|
||||
Given the new user message and recent conversation, produce 3 diverse, terse web search queries that best address the user's *current* intent.
|
||||
Rules:
|
||||
- Resolve ambiguous references using the recent conversation when present.
|
||||
- No quotes, no site: operators, no overly long queries.
|
||||
- Return each query on its own line.
|
||||
|
||||
User message:
|
||||
{prompt}
|
||||
|
||||
{ctx_block}"""
|
||||
resp = await ollama_chat(model, [{"role": "user", "content": ask}])
|
||||
lines = [l.strip(" -\t") for l in resp.splitlines() if l.strip()]
|
||||
uniq, seen = [], set()
|
||||
for l in lines:
|
||||
k = l.lower()
|
||||
if k in seen:
|
||||
continue
|
||||
uniq.append(l)
|
||||
seen.add(k)
|
||||
if len(uniq) >= 3:
|
||||
break
|
||||
return uniq or [prompt]
|
||||
|
||||
async def rerank(
|
||||
prompt: str,
|
||||
docs: List[Tuple[str, str]],
|
||||
model: str, # kept for signature compatibility (unused here)
|
||||
context_excerpt: str,
|
||||
embed_model: Optional[str] = None,
|
||||
) -> List[Tuple[str, str, float]]:
|
||||
"""
|
||||
Embedding-based reranker via Ollama using cosine similarity.
|
||||
|
||||
Robustness upgrades:
|
||||
- Try embed_model; if needed fallback to the ':latest' or untagged alias.
|
||||
- Normalize multiple possible response schemas from Ollama.
|
||||
- If the query vector is empty, retry the query alone.
|
||||
- If only the query is returned, retry passages in a second call.
|
||||
- Detailed logging of counts and dimensions.
|
||||
"""
|
||||
import time
|
||||
t0 = time.perf_counter()
|
||||
embed_model = (embed_model or get_rerank_model_preference()).strip()
|
||||
ollama_url = get_ollama_api_url().rstrip("/")
|
||||
|
||||
# --- optional fast cosine via NumPy ---------------------------------------
|
||||
try:
|
||||
import numpy as _np # optional
|
||||
except Exception:
|
||||
_np = None
|
||||
|
||||
def _cosine(a: List[float], b: List[float]) -> float:
|
||||
if _np is not None:
|
||||
va = _np.asarray(a, dtype="float32")
|
||||
vb = _np.asarray(b, dtype="float32")
|
||||
n = min(va.size, vb.size)
|
||||
if n == 0:
|
||||
return 0.0
|
||||
va = va[:n]; vb = vb[:n]
|
||||
na = _np.linalg.norm(va); nb = _np.linalg.norm(vb)
|
||||
if na <= 0.0 or nb <= 0.0:
|
||||
return 0.0
|
||||
return float(va.dot(vb) / (na * nb))
|
||||
# pure Python fallback
|
||||
n = min(len(a), len(b))
|
||||
if n == 0:
|
||||
return 0.0
|
||||
dot = na = nb = 0.0
|
||||
for i in range(n):
|
||||
x = a[i]; y = b[i]
|
||||
dot += x * y
|
||||
na += x * x
|
||||
nb += y * y
|
||||
if na <= 0.0 or nb <= 0.0:
|
||||
return 0.0
|
||||
return dot / ((na ** 0.5) * (nb ** 0.5))
|
||||
|
||||
# --- build query + passages ------------------------------------------------
|
||||
ctx_tail = (("\ncontext: " + context_excerpt[-400:]) if context_excerpt else "")
|
||||
q_text = f"query: {prompt.strip()}{ctx_tail}"
|
||||
|
||||
DOC_SNIPPET_CHARS = 800 # keep short & fast
|
||||
passages: List[str] = []
|
||||
raw_snippets: List[str] = [] # for cache keys
|
||||
for (_u, t) in docs:
|
||||
snippet = t.replace("\n", " ")
|
||||
if len(snippet) > DOC_SNIPPET_CHARS:
|
||||
snippet = snippet[:DOC_SNIPPET_CHARS]
|
||||
passages.append(f"passage: {snippet}")
|
||||
raw_snippets.append(snippet)
|
||||
|
||||
# --- embedding cache -------------------------------------------------------
|
||||
emb_cache: Dict[str, List[float]] = globals().get("_EMB_CACHE", {})
|
||||
try:
|
||||
import hashlib
|
||||
keys = [hashlib.sha1(s.encode("utf-8", errors="ignore")).hexdigest() for s in raw_snippets]
|
||||
except Exception:
|
||||
keys = [f"nocache-{i}" for i in range(len(raw_snippets))]
|
||||
|
||||
# Prepare inputs:
|
||||
# 0 -> query; >=1 -> only passages NOT present in cache
|
||||
to_embed_inputs: List[str] = [q_text]
|
||||
pos_to_passage_idx: Dict[int, int] = {}
|
||||
p_cached = 0
|
||||
for i, (p, k) in enumerate(zip(passages, keys)):
|
||||
if k in emb_cache:
|
||||
p_cached += 1
|
||||
continue
|
||||
pos = len(to_embed_inputs)
|
||||
to_embed_inputs.append(p)
|
||||
pos_to_passage_idx[pos] = i
|
||||
|
||||
# --- helpers to call Ollama embeddings ------------------------------------
|
||||
async def _embed_inputs(inputs: List[str], model_name: str) -> Tuple[List[List[float]], Dict[str, Any]]:
|
||||
"""
|
||||
Call Ollama /api/embeddings once per input with {"model", "prompt"}.
|
||||
Keeps order; returns [[]] for failures at a given index.
|
||||
"""
|
||||
timeout = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)
|
||||
sem = asyncio.Semaphore(8) # cap concurrency a bit
|
||||
|
||||
async def _one(text: str) -> Tuple[List[float], Optional[str]]:
|
||||
payload = {"model": model_name, "prompt": text}
|
||||
try:
|
||||
async with sem:
|
||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||
r = await client.post(f"{ollama_url}/api/embeddings", json=payload)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
except httpx.HTTPStatusError as e:
|
||||
return [], f"http_error:{e}"
|
||||
except Exception as e:
|
||||
return [], f"request_error:{e}"
|
||||
|
||||
# normalize common shapes
|
||||
if isinstance(data, dict):
|
||||
if "error" in data:
|
||||
return [], f"model_error:{data.get('error')}"
|
||||
if "embedding" in data and isinstance(data["embedding"], list):
|
||||
return data["embedding"], None
|
||||
if "data" in data and isinstance(data["data"], list) and data["data"]:
|
||||
em = data["data"][0].get("embedding", [])
|
||||
return (em if isinstance(em, list) else []), None
|
||||
if "embeddings" in data and isinstance(data["embeddings"], list):
|
||||
# some servers may return {"embeddings":[vector]} even for single prompt
|
||||
emb0 = data["embeddings"][0]
|
||||
if isinstance(emb0, dict):
|
||||
emb0 = emb0.get("embedding", [])
|
||||
return (emb0 if isinstance(emb0, list) else []), None
|
||||
|
||||
return [], "parse_error"
|
||||
|
||||
tasks = [_one(t) for t in inputs]
|
||||
results = await asyncio.gather(*tasks, return_exceptions=False)
|
||||
|
||||
embs: List[List[float]] = []
|
||||
errs: List[str] = []
|
||||
for emb, err in results:
|
||||
embs.append(emb)
|
||||
if err:
|
||||
errs.append(err)
|
||||
|
||||
meta: Dict[str, Any] = {}
|
||||
if errs:
|
||||
# light meta summary
|
||||
meta["errors"] = {k: errs.count(k) for k in set(errs)}
|
||||
return embs, meta
|
||||
|
||||
# --- do the embedding calls ------------------------------------------------
|
||||
t_embed = time.perf_counter()
|
||||
inputs_all = to_embed_inputs # [query] + uncached passages
|
||||
embeddings, meta = await _embed_inputs(inputs_all, embed_model)
|
||||
|
||||
# simple model fallback if *all* returned empty
|
||||
if not any(len(e) for e in embeddings):
|
||||
tried = [embed_model]
|
||||
alt = (embed_model.split(":", 1)[0] if ":" in embed_model else embed_model + ":latest")
|
||||
if alt != embed_model:
|
||||
embeddings, meta2 = await _embed_inputs(inputs_all, alt)
|
||||
if any(len(e) for e in embeddings):
|
||||
print(f"[web] embed() recovered with fallback model {alt} (meta={meta or meta2})")
|
||||
embed_model = alt
|
||||
else:
|
||||
print(f"[web] embed() FAILED (models tried={tried + [alt]}, meta={meta or meta2})")
|
||||
return fallback_rerank(
|
||||
prompt,
|
||||
docs,
|
||||
context_excerpt,
|
||||
reason=f"model_failed:{embed_model}",
|
||||
)
|
||||
|
||||
# split q vs passages and update cache
|
||||
q_emb = embeddings[0] if embeddings else []
|
||||
if not q_emb:
|
||||
print("[web] embed() empty query vector — aborting rerank")
|
||||
return fallback_rerank(prompt, docs, context_excerpt, reason="empty_query_vector")
|
||||
|
||||
# positions >=1 correspond to passages (only those that weren’t cached)
|
||||
for pos, emb_vec in enumerate(embeddings[1:], start=1):
|
||||
i = pos_to_passage_idx.get(pos)
|
||||
if i is None:
|
||||
continue
|
||||
if not keys[i].startswith("nocache-"):
|
||||
emb_cache[keys[i]] = emb_vec
|
||||
|
||||
# build aligned passage vectors
|
||||
p_emb_list: List[List[float]] = [emb_cache.get(k, []) for k in keys]
|
||||
if docs and not any(len(vec) for vec in p_emb_list):
|
||||
print("[web] embed() empty passage vectors — aborting rerank")
|
||||
return fallback_rerank(prompt, docs, context_excerpt, reason="empty_passage_vectors")
|
||||
|
||||
# logging
|
||||
q_dim = len(q_emb)
|
||||
p_dims = [len(v) for v in p_emb_list]
|
||||
print(f"[web] embed() took {time.perf_counter() - t_embed:.3f}s "
|
||||
f"(model='{embed_model}', q_dim={q_dim}, p_cached={p_cached}, "
|
||||
f"p_fresh={sum(1 for d in p_dims if d>0)}, total_p={len(p_emb_list)})")
|
||||
|
||||
# --- score + rank ----------------------------------------------------------
|
||||
t_score = time.perf_counter()
|
||||
scored: List[Tuple[str, str, float]] = []
|
||||
for (u, t), p_emb in zip(docs, p_emb_list):
|
||||
cos = _cosine(q_emb, p_emb)
|
||||
score_0_100 = max(0.0, min(100.0, (cos + 1.0) * 50.0))
|
||||
scored.append((u, t, score_0_100))
|
||||
scored.sort(key=lambda x: x[2], reverse=True)
|
||||
print(f"[web] cosine scoring took {time.perf_counter() - t_score:.3f}s; rerank total {time.perf_counter() - t0:.3f}s")
|
||||
|
||||
return scored
|
||||
|
||||
def build_enriched_prompt(user_prompt: str, ranked: List[Tuple[str, str, float]], top_k: int = 6) -> Tuple[str, List[str]]:
|
||||
"""
|
||||
Build an enriched prompt using only high-quality documents.
|
||||
- Keep at most `top_k` docs with score >= MIN_SCORE.
|
||||
- If none survive, return a <websearch_context> telling the assistant that
|
||||
a web search was performed but no good results were found.
|
||||
"""
|
||||
MIN_SCORE = 70.0
|
||||
|
||||
# Sort defensively (should already be sorted desc)
|
||||
ranked = sorted(ranked, key=lambda x: x[2], reverse=True)
|
||||
|
||||
# Strict cutoff
|
||||
selected = [(u, t, sc) for (u, t, sc) in ranked if sc >= MIN_SCORE][:top_k]
|
||||
|
||||
# Debug summary
|
||||
try:
|
||||
all_scores = [sc for (_u, _t, sc) in ranked]
|
||||
sel_scores = [sc for (_u, _t, sc) in selected]
|
||||
if all_scores:
|
||||
print(f"[web] selection ≥{MIN_SCORE} → total={len(all_scores)}, selected={len(selected)}, "
|
||||
f"top_sel={max(sel_scores) if sel_scores else 0:.1f}, "
|
||||
f"min_sel={min(sel_scores) if sel_scores else 0:.1f}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not selected:
|
||||
# No “good” results → still enrich with an explicit no-results message
|
||||
parts = [
|
||||
"<websearch_context>",
|
||||
f"No suitable web results found (score < {MIN_SCORE}). "
|
||||
"Tell the user you performed a web search but couldn't find any good results. "
|
||||
"If you can answer from prior context or general knowledge, say so clearly and "
|
||||
"do not fabricate citations or URLs.",
|
||||
"</websearch_context>",
|
||||
]
|
||||
enriched = f"{user_prompt}\n\n" + "\n".join(parts)
|
||||
return enriched, []
|
||||
|
||||
# Build normal context
|
||||
sources = [u for (u, _, _) in selected]
|
||||
parts = ["<websearch_context>"]
|
||||
for i, (u, t, _) in enumerate(selected, 1):
|
||||
snippet = t.strip().replace("\n", " ")
|
||||
if len(snippet) > 1200:
|
||||
snippet = snippet[:1200]
|
||||
parts.append(f"[{i}] {snippet} (source: {u})")
|
||||
parts.append("</websearch_context>")
|
||||
parts.append("\nAnswer the user using the context when relevant.\nMake your response long enough to reflect all interesting information found. No duplicate information.\nUnless related to the topic, don't mention the source from the web search.")
|
||||
|
||||
enriched = f"{user_prompt}\n\n" + "\n".join(parts)
|
||||
return enriched, sources
|
||||
|
||||
# ----- Public API ----------------------------------------------------------------
|
||||
|
||||
async def enrich_prompt(
|
||||
user_prompt: str,
|
||||
model: str,
|
||||
messages: Optional[List[Dict[str, str]]] = None,
|
||||
*,
|
||||
searx_url: Optional[str] = None,
|
||||
engines: Optional[List[str]] = None,
|
||||
) -> Tuple[str, List[str]]:
|
||||
import time # local import to avoid touching global imports
|
||||
start_all = time.perf_counter()
|
||||
|
||||
def _no_results_enriched(reason: str, queries: Optional[List[str]] = None) -> Tuple[str, List[str]]:
|
||||
parts = ["<websearch_context>"]
|
||||
parts.append(
|
||||
"Web search was performed but no suitable results were found. "
|
||||
"Tell the user you searched the web but couldn't find any good results. "
|
||||
"If you can still answer from prior context or general knowledge, say so clearly, "
|
||||
"and do not fabricate citations or URLs."
|
||||
)
|
||||
if queries:
|
||||
try:
|
||||
qshow = ", ".join(queries[:3])
|
||||
parts.append(f"Queries attempted: {qshow}")
|
||||
except Exception:
|
||||
pass
|
||||
if engines:
|
||||
try:
|
||||
eshow = ", ".join(engines)
|
||||
parts.append(f"Engines selected: {eshow}")
|
||||
except Exception:
|
||||
pass
|
||||
parts.append(f"(reason: {reason})")
|
||||
parts.append("</websearch_context>")
|
||||
return f"{user_prompt}\n\n" + "\n".join(parts), []
|
||||
|
||||
context_excerpt = render_recent_context(messages, char_limit=1200)
|
||||
|
||||
# 1) queries
|
||||
try:
|
||||
t0 = time.perf_counter()
|
||||
queries = await generate_queries(user_prompt, model=model, context_excerpt=context_excerpt)
|
||||
print(f"[web] queries: {queries} (took {time.perf_counter() - t0:.3f}s)")
|
||||
except Exception:
|
||||
print("[web] ERROR in generate_queries:\n" + traceback.format_exc())
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return _no_results_enriched("query_generation_failed")
|
||||
|
||||
# 2) search + fetch
|
||||
try:
|
||||
print("[web] opening httpx client")
|
||||
async with httpx.AsyncClient(
|
||||
headers=DEFAULT_HEADERS,
|
||||
follow_redirects=True,
|
||||
http2=True,
|
||||
limits=HTTP_LIMITS,
|
||||
timeout=HTTP_TIMEOUT,
|
||||
) as client:
|
||||
t1 = time.perf_counter()
|
||||
print("[web] calling searx_search_many() …")
|
||||
all_urls = await searx_search_many(
|
||||
client,
|
||||
queries,
|
||||
per_query_max=6,
|
||||
overall_max=MAX_PAGES_FETCH * 2,
|
||||
searx_url=searx_url,
|
||||
engines=engines,
|
||||
)
|
||||
print(f"[web] searx_search_many() -> {len(all_urls)} urls (took {time.perf_counter() - t1:.3f}s)")
|
||||
|
||||
if not all_urls:
|
||||
print("[web] no URLs from SearX — emitting no-results context")
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return _no_results_enriched("no_urls", queries)
|
||||
|
||||
t2 = time.perf_counter()
|
||||
print("[web] calling gather_pages() …")
|
||||
pages = await gather_pages(client, all_urls, max_pages=MAX_PAGES_FETCH)
|
||||
print(f"[web] gather_pages() -> {len(pages)} pages (cap={MAX_PAGES_FETCH}, took {time.perf_counter() - t2:.3f}s)")
|
||||
except Exception:
|
||||
print("[web] ERROR during search/fetch:\n" + traceback.format_exc())
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return _no_results_enriched("search_fetch_error")
|
||||
|
||||
# 3) docs
|
||||
try:
|
||||
t3 = time.perf_counter()
|
||||
docs = [(u, pages[u]) for u in all_urls if u in pages]
|
||||
print(f"[web] docs for rerank: {len(docs)} (built in {time.perf_counter() - t3:.3f}s)")
|
||||
if not docs:
|
||||
print("[web] no docs after fetch/filter — emitting no-results context")
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return _no_results_enriched("no_docs_after_fetch", queries)
|
||||
except Exception:
|
||||
print("[web] ERROR building docs list:\n" + traceback.format_exc())
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return _no_results_enriched("docs_build_failed", queries)
|
||||
|
||||
# 4) rerank
|
||||
try:
|
||||
t4 = time.perf_counter()
|
||||
print("[web] calling rerank() …")
|
||||
ranked = await rerank(user_prompt, docs, model=model, context_excerpt=context_excerpt)
|
||||
print(f"[web] rerank() -> {len(ranked)} scored docs (took {time.perf_counter() - t4:.3f}s)")
|
||||
try:
|
||||
scores_only = [sc for (_u, _t, sc) in ranked]
|
||||
if scores_only:
|
||||
scores_sorted = sorted(scores_only)
|
||||
n = len(scores_sorted)
|
||||
p50 = scores_sorted[n // 2]
|
||||
p75 = scores_sorted[int(n * 0.75) - 1 if n > 3 else n - 1]
|
||||
print(f"[web] score stats → min={scores_sorted[0]:.1f}, p50={p50:.1f}, p75={p75:.1f}, max={scores_sorted[-1]:.1f}")
|
||||
print(f"[web] top scores → {[round(s,1) for s in scores_only[:min(6,len(scores_only))]]}")
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
print("[web] ERROR in rerank:\n" + traceback.format_exc())
|
||||
ranked = fallback_rerank(
|
||||
user_prompt,
|
||||
docs,
|
||||
context_excerpt,
|
||||
reason="rerank_exception",
|
||||
)
|
||||
|
||||
# 5) build prompt
|
||||
try:
|
||||
t5 = time.perf_counter()
|
||||
enriched = build_enriched_prompt(user_prompt, ranked, top_k=6)
|
||||
print(f"[web] build_enriched_prompt() done (took {time.perf_counter() - t5:.3f}s)")
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return enriched
|
||||
except Exception:
|
||||
print("[web] ERROR in build_enriched_prompt:\n" + traceback.format_exc())
|
||||
print(f"[web] enrich_prompt total: {time.perf_counter() - start_all:.3f}s")
|
||||
return _no_results_enriched("build_enriched_failed", queries)
|
||||
326
backend/whisper_admin.py
Normal file
326
backend/whisper_admin.py
Normal file
@@ -0,0 +1,326 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
DEFAULT_WHISPER_MODEL = "base"
|
||||
_WHISPER_DOWNLOAD_LOCK = threading.Lock()
|
||||
_WHISPER_MODEL_LOCK = threading.Lock()
|
||||
_WHISPER_MODELS: Dict[tuple[str, str], Any] = {}
|
||||
_AUDIO_SUFFIXES = {
|
||||
"audio/aac": ".aac",
|
||||
"audio/flac": ".flac",
|
||||
"audio/mp4": ".m4a",
|
||||
"audio/mpeg": ".mp3",
|
||||
"audio/mpga": ".mp3",
|
||||
"audio/ogg": ".ogg",
|
||||
"audio/wav": ".wav",
|
||||
"audio/wave": ".wav",
|
||||
"audio/webm": ".webm",
|
||||
"audio/x-wav": ".wav",
|
||||
}
|
||||
|
||||
|
||||
def _default_download_root() -> Path:
|
||||
default_cache = Path.home() / ".cache"
|
||||
return Path(os.getenv("XDG_CACHE_HOME", str(default_cache))) / "whisper"
|
||||
|
||||
|
||||
def _load_whisper_module():
|
||||
try:
|
||||
return importlib.import_module("whisper")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _load_torch_module():
|
||||
try:
|
||||
return importlib.import_module("torch")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def whisper_runtime_error() -> Optional[str]:
|
||||
if importlib.util.find_spec("whisper") is None:
|
||||
return (
|
||||
"Audio/video transcription requires the optional 'openai-whisper' package. "
|
||||
"Install it in backend/.venv, for example: pip install -U openai-whisper"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _official_model_target(whisper_mod: Any, model_name: str) -> Optional[Path]:
|
||||
url = str(getattr(whisper_mod, "_MODELS", {}).get(model_name) or "").strip()
|
||||
if not url:
|
||||
return None
|
||||
return _default_download_root() / os.path.basename(url)
|
||||
|
||||
|
||||
def inspect_whisper_model(model_name: str = DEFAULT_WHISPER_MODEL) -> Dict[str, Any]:
|
||||
error = whisper_runtime_error()
|
||||
if error:
|
||||
return {
|
||||
"model": model_name,
|
||||
"package_available": False,
|
||||
"available": False,
|
||||
"downloaded": False,
|
||||
"path": None,
|
||||
"error": error,
|
||||
}
|
||||
|
||||
whisper_mod = _load_whisper_module()
|
||||
if whisper_mod is None:
|
||||
return {
|
||||
"model": model_name,
|
||||
"package_available": False,
|
||||
"available": False,
|
||||
"downloaded": False,
|
||||
"path": None,
|
||||
"error": "Failed to import the Whisper runtime.",
|
||||
}
|
||||
|
||||
target = _official_model_target(whisper_mod, model_name)
|
||||
if target is not None:
|
||||
return {
|
||||
"model": model_name,
|
||||
"package_available": True,
|
||||
"available": target.is_file(),
|
||||
"downloaded": False,
|
||||
"path": str(target),
|
||||
"error": "",
|
||||
}
|
||||
|
||||
custom_path = Path(model_name).expanduser()
|
||||
return {
|
||||
"model": model_name,
|
||||
"package_available": True,
|
||||
"available": custom_path.is_file(),
|
||||
"downloaded": False,
|
||||
"path": str(custom_path),
|
||||
"error": "",
|
||||
}
|
||||
|
||||
|
||||
def list_whisper_models() -> Dict[str, Any]:
|
||||
error = whisper_runtime_error()
|
||||
if error:
|
||||
return {
|
||||
"models": [
|
||||
{
|
||||
"name": DEFAULT_WHISPER_MODEL,
|
||||
"available": False,
|
||||
"downloaded": False,
|
||||
}
|
||||
],
|
||||
"error": error,
|
||||
}
|
||||
|
||||
whisper_mod = _load_whisper_module()
|
||||
if whisper_mod is None:
|
||||
return {
|
||||
"models": [
|
||||
{
|
||||
"name": DEFAULT_WHISPER_MODEL,
|
||||
"available": False,
|
||||
"downloaded": False,
|
||||
}
|
||||
],
|
||||
"error": "Failed to import the Whisper runtime.",
|
||||
}
|
||||
|
||||
try:
|
||||
names = list(whisper_mod.available_models())
|
||||
except Exception:
|
||||
names = [DEFAULT_WHISPER_MODEL]
|
||||
|
||||
out = []
|
||||
for name in names:
|
||||
status = inspect_whisper_model(name)
|
||||
out.append(
|
||||
{
|
||||
"name": name,
|
||||
"available": bool(status.get("available")),
|
||||
"downloaded": bool(status.get("available")),
|
||||
}
|
||||
)
|
||||
|
||||
return {"models": out, "error": ""}
|
||||
|
||||
|
||||
def ensure_whisper_model_downloaded(model_name: str = DEFAULT_WHISPER_MODEL) -> Dict[str, Any]:
|
||||
status = inspect_whisper_model(model_name)
|
||||
if status["error"]:
|
||||
raise RuntimeError(status["error"])
|
||||
|
||||
whisper_mod = _load_whisper_module()
|
||||
if whisper_mod is None:
|
||||
raise RuntimeError("Failed to import the Whisper runtime.")
|
||||
|
||||
target = _official_model_target(whisper_mod, model_name)
|
||||
if target is None:
|
||||
custom_path = Path(model_name).expanduser()
|
||||
if custom_path.is_file():
|
||||
return {
|
||||
**status,
|
||||
"available": True,
|
||||
"downloaded": False,
|
||||
"path": str(custom_path),
|
||||
}
|
||||
raise RuntimeError(f"Model {model_name} not found; available models = {whisper_mod.available_models()}")
|
||||
|
||||
with _WHISPER_DOWNLOAD_LOCK:
|
||||
existed_before = target.is_file()
|
||||
download_fn = getattr(whisper_mod, "_download", None)
|
||||
if callable(download_fn):
|
||||
download_fn(whisper_mod._MODELS[model_name], str(_default_download_root()), False)
|
||||
else:
|
||||
model = whisper_mod.load_model(model_name, device="cpu")
|
||||
del model
|
||||
|
||||
return {
|
||||
"model": model_name,
|
||||
"package_available": True,
|
||||
"available": target.is_file(),
|
||||
"downloaded": target.is_file() and not existed_before,
|
||||
"path": str(target),
|
||||
"error": "",
|
||||
}
|
||||
|
||||
|
||||
def _resolve_whisper_device() -> str:
|
||||
try:
|
||||
torch_mod = _load_torch_module()
|
||||
if torch_mod is not None and getattr(torch_mod.cuda, "is_available", lambda: False)():
|
||||
return "cuda"
|
||||
|
||||
backends = getattr(torch_mod, "backends", None)
|
||||
mps_backend = getattr(backends, "mps", None)
|
||||
if mps_backend is not None and getattr(mps_backend, "is_available", lambda: False)():
|
||||
return "mps"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return "cpu"
|
||||
|
||||
|
||||
def _resolve_ffmpeg_binary() -> Optional[str]:
|
||||
candidate = os.getenv("HEIMGEIST_FFMPEG_PATH") or shutil.which("ffmpeg") or "/usr/bin/ffmpeg"
|
||||
if not candidate:
|
||||
return None
|
||||
if Path(candidate).exists() or shutil.which(candidate):
|
||||
return str(candidate)
|
||||
return None
|
||||
|
||||
|
||||
def _audio_suffix_for_mime_type(mime_type: str) -> str:
|
||||
base_mime = str(mime_type or "").split(";", 1)[0].strip().lower()
|
||||
return _AUDIO_SUFFIXES.get(base_mime, ".webm")
|
||||
|
||||
|
||||
def _load_transcription_model(model_name: str = DEFAULT_WHISPER_MODEL) -> tuple[Any, str]:
|
||||
error = whisper_runtime_error()
|
||||
if error:
|
||||
raise RuntimeError(error)
|
||||
|
||||
whisper_mod = _load_whisper_module()
|
||||
if whisper_mod is None:
|
||||
raise RuntimeError("Failed to import the Whisper runtime.")
|
||||
|
||||
ensure_whisper_model_downloaded(model_name)
|
||||
device = _resolve_whisper_device()
|
||||
cache_key = (model_name, device)
|
||||
|
||||
with _WHISPER_MODEL_LOCK:
|
||||
model = _WHISPER_MODELS.get(cache_key)
|
||||
if model is None:
|
||||
try:
|
||||
model = whisper_mod.load_model(model_name, device=device)
|
||||
except TypeError:
|
||||
model = whisper_mod.load_model(model_name)
|
||||
_WHISPER_MODELS[cache_key] = model
|
||||
|
||||
return model, device
|
||||
|
||||
|
||||
def _convert_audio_to_wav(input_path: Path, output_path: Path) -> None:
|
||||
ffmpeg_bin = _resolve_ffmpeg_binary()
|
||||
if not ffmpeg_bin:
|
||||
raise RuntimeError(
|
||||
"Audio transcription requires ffmpeg. Heimgeist could not resolve it from HEIMGEIST_FFMPEG_PATH or PATH."
|
||||
)
|
||||
|
||||
process = subprocess.run(
|
||||
[
|
||||
ffmpeg_bin,
|
||||
"-y",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-i",
|
||||
str(input_path),
|
||||
"-ac",
|
||||
"1",
|
||||
"-ar",
|
||||
"16000",
|
||||
"-f",
|
||||
"wav",
|
||||
str(output_path),
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
if process.returncode != 0:
|
||||
detail = (process.stderr or process.stdout or "ffmpeg audio conversion failed").strip()
|
||||
raise RuntimeError(detail)
|
||||
|
||||
|
||||
def transcribe_audio_bytes(
|
||||
audio_bytes: bytes,
|
||||
mime_type: str,
|
||||
model_name: str = DEFAULT_WHISPER_MODEL,
|
||||
language: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
if not audio_bytes:
|
||||
raise RuntimeError("Recorded audio was empty.")
|
||||
|
||||
model, device = _load_transcription_model(model_name)
|
||||
input_path = Path(tempfile.mkstemp(suffix=_audio_suffix_for_mime_type(mime_type))[1])
|
||||
wav_path = Path(tempfile.mkstemp(suffix=".wav")[1])
|
||||
|
||||
try:
|
||||
input_path.write_bytes(audio_bytes)
|
||||
source_path = input_path
|
||||
if input_path.suffix.lower() != ".wav":
|
||||
_convert_audio_to_wav(input_path, wav_path)
|
||||
source_path = wav_path
|
||||
|
||||
transcription_options = {
|
||||
"task": "transcribe",
|
||||
"fp16": device == "cuda",
|
||||
}
|
||||
if language:
|
||||
transcription_options["language"] = str(language).strip().lower()
|
||||
|
||||
result = model.transcribe(str(source_path), **transcription_options)
|
||||
return {
|
||||
"model": model_name,
|
||||
"device": device,
|
||||
"language": str(result.get("language") or "").strip(),
|
||||
"text": str(result.get("text") or "").strip(),
|
||||
}
|
||||
finally:
|
||||
for path in (input_path, wav_path):
|
||||
try:
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
200
deck-logs/heimgeist-user-journal.txt
Normal file
200
deck-logs/heimgeist-user-journal.txt
Normal file
@@ -0,0 +1,200 @@
|
||||
Mar 20 10:34:46 steamdeck systemd[1357]: Started flatpak session helper.
|
||||
Mar 20 10:34:46 steamdeck systemd[1357]: Started app-flatpak-org.mozilla.firefox-14968.scope.
|
||||
Mar 20 10:34:47 steamdeck flatpak[14988]: [2] Sandbox: CanCreateUserNamespace() clone() failure: EPERM
|
||||
Mar 20 10:34:47 steamdeck firefox-bin[14988]: Failed to load module "canberra-gtk-module"
|
||||
Mar 20 10:34:47 steamdeck firefox-bin[14988]: Failed to load module "colorreload-gtk-module"
|
||||
Mar 20 10:34:47 steamdeck firefox-bin[14988]: Failed to load module "window-decorations-gtk-module"
|
||||
Mar 20 10:34:48 steamdeck flatpak[14988]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 10:34:53 steamdeck systemd[1357]: Started Thunderbird - Mail Client.
|
||||
Mar 20 10:34:53 steamdeck systemd[1357]: Started app-flatpak-org.mozilla.Thunderbird-15395.scope.
|
||||
Mar 20 10:34:53 steamdeck flatpak[15407]: [2] Sandbox: CanCreateUserNamespace() clone() failure: EPERM
|
||||
Mar 20 10:34:53 steamdeck thunderbird-bin[15407]: Failed to load module "canberra-gtk-module"
|
||||
Mar 20 10:34:54 steamdeck flatpak[15407]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 10:34:56 steamdeck systemd[1357]: app-flatpak-org.mozilla.firefox-14968.scope: Consumed 8.220s CPU time, 821.5M memory peak.
|
||||
Mar 20 10:35:08 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 10:35:12 steamdeck kwin_x11[3347]: kwin_core: XCB error: 152 (BadDamage), sequence: 62511, resource id: 23105910, major code: 143 (DAMAGE), minor code: 3 (Subtract)
|
||||
Mar 20 10:35:36 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 10:35:36 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 10:35:36 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 10:35:37 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 10:38:57 steamdeck flatpak[15407]: [GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt
|
||||
Mar 20 10:39:17 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 10:42:05 steamdeck systemd[1357]: app-flatpak-org.mozilla.Thunderbird-15395.scope: Consumed 7min 16.070s CPU time, 557.5M memory peak.
|
||||
Mar 20 10:53:53 steamdeck polkit-agent-helper-1[16894]: pam_unix(polkit-1:auth): authentication failure; logname=deck uid=1000 euid=0 tty= ruser=deck rhost= user=deck
|
||||
Mar 20 10:54:46 steamdeck systemd[1357]: Created slice Slice /user.
|
||||
Mar 20 10:54:46 steamdeck systemd[1357]: Started podman-16977.scope.
|
||||
Mar 20 10:54:46 steamdeck systemd[1357]: Started podman-pause-508fa5b2.scope.
|
||||
Mar 20 10:54:53 steamdeck sudo[17001]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/podman logs -f searxng
|
||||
Mar 20 10:54:53 steamdeck sudo[17001]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 10:54:53 steamdeck sudo[17001]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 10:54:59 steamdeck systemd[1357]: Started podman-17031.scope.
|
||||
Mar 20 10:55:36 steamdeck sudo[17050]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/ufw allow 8080
|
||||
Mar 20 10:55:36 steamdeck sudo[17050]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 10:55:36 steamdeck sudo[17050]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 10:55:47 steamdeck sudo[17081]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/ufw disable
|
||||
Mar 20 10:55:47 steamdeck sudo[17081]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 10:55:47 steamdeck sudo[17081]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 10:55:56 steamdeck sshd-session[16809]: Received disconnect from 172.20.10.3 port 62526:11: disconnected by user
|
||||
Mar 20 10:55:56 steamdeck sshd-session[16809]: Disconnected from user deck 172.20.10.3 port 62526
|
||||
Mar 20 10:56:18 steamdeck systemd[1357]: Started podman-17298.scope.
|
||||
Mar 20 10:56:28 steamdeck sudo[17317]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/ufw enable
|
||||
Mar 20 10:56:28 steamdeck sudo[17317]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 10:56:32 steamdeck sudo[17317]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 10:57:10 steamdeck systemd[1357]: Started podman-17481.scope.
|
||||
Mar 20 11:03:15 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:03:17 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:03:17 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:03:17 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:03:18 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:03:18 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:13:13 steamdeck sudo[22399]: deck : TTY=pts/4 ; PWD=/home/deck/searxng/config ; USER=root ; COMMAND=/usr/bin/nano settings.yml
|
||||
Mar 20 11:13:13 steamdeck sudo[22399]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 11:13:52 steamdeck sudo[22399]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 11:13:55 steamdeck sudo[22414]: deck : TTY=pts/4 ; PWD=/home/deck/searxng/config ; USER=root ; COMMAND=/usr/bin/systemctl restart searxng
|
||||
Mar 20 11:13:55 steamdeck sudo[22414]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 11:13:55 steamdeck sudo[22414]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 11:14:04 steamdeck systemd[1357]: Started podman-22433.scope.
|
||||
Mar 20 11:14:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:14:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:18:16 steamdeck systemd[1357]: Started podman-23220.scope.
|
||||
Mar 20 11:18:54 steamdeck systemd[1357]: Started podman-23250.scope.
|
||||
Mar 20 11:18:54 steamdeck systemd[1357]: Started podman-23273.scope.
|
||||
Mar 20 11:18:54 steamdeck systemd[1357]: Started podman-23292.scope.
|
||||
Mar 20 11:19:21 steamdeck sudo[23329]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/nano searxng/config/settings.yml
|
||||
Mar 20 11:19:21 steamdeck sudo[23329]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 11:19:58 steamdeck sudo[23329]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 11:20:05 steamdeck systemd[1357]: Started podman-23350.scope.
|
||||
Mar 20 11:21:55 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:24:22 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:24:22 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:24:22 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:24:22 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:29:06 steamdeck sudo[28938]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/nano searxng/config/settings.yml
|
||||
Mar 20 11:29:06 steamdeck sudo[28938]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 11:29:43 steamdeck sudo[28938]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 11:29:45 steamdeck systemd[1357]: Started podman-28958.scope.
|
||||
Mar 20 11:29:54 steamdeck kglobalacceld[3289]: kf.globalaccel.kglobalacceld: KKeyServer::xcbKeyPressEventToQt failed
|
||||
Mar 20 11:31:14 steamdeck sudo[31682]: deck : TTY=pts/4 ; PWD=/home/deck ; USER=root ; COMMAND=/usr/bin/ufw status verbose
|
||||
Mar 20 11:31:14 steamdeck sudo[31682]: pam_unix(sudo:session): session opened for user root(uid=0) by deck(uid=1000)
|
||||
Mar 20 11:31:15 steamdeck sudo[31682]: pam_unix(sudo:session): session closed for user root
|
||||
Mar 20 11:32:24 steamdeck systemd[1357]: Started podman-33094.scope.
|
||||
Mar 20 11:32:25 steamdeck systemd[1357]: Started podman-33170.scope.
|
||||
Mar 20 11:34:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:34:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:34:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:34:14 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device Steam Deck Motion Sensors (/dev/input/js1)\n(II) No input driver specified, ignoring this device.\n(II) This device may have been added with another device file.\n"
|
||||
Mar 20 11:34:14 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device Steam Deck (/dev/input/js0)\n(II) No input driver specified, ignoring this device.\n(II) This device may have been added with another device file.\n"
|
||||
Mar 20 11:34:14 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device Steam Deck (/dev/input/event19)\n"
|
||||
Mar 20 11:34:14 steamdeck sddm-helper-start-x11user[3199]: "(II) No input driver specified, ignoring this device.\n(II) This device may have been added with another device file.\n"
|
||||
Mar 20 11:34:14 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device Steam Deck Motion Sensors (/dev/input/event22)\n"
|
||||
Mar 20 11:34:14 steamdeck sddm-helper-start-x11user[3199]: "(II) No input driver specified, ignoring this device.\n(II) This device may have been added with another device file.\n"
|
||||
Mar 20 11:34:15 steamdeck steam[3909]: [2026-03-20 11:34:15] Shutdown
|
||||
Mar 20 11:34:15 steamdeck kded6[3346]: Service ":1.91" unregistered
|
||||
Mar 20 11:34:27 steamdeck systemd[1357]: app-steam@autostart.service: Consumed 7min 38.983s CPU time, 1G memory peak, 283.2M memory swap peak.
|
||||
Mar 20 11:35:36 steamdeck systemd[1357]: Started Firefox - Web Browser.
|
||||
Mar 20 11:35:36 steamdeck systemd[1357]: Started app-flatpak-org.mozilla.firefox-35291.scope.
|
||||
Mar 20 11:35:36 steamdeck flatpak[35304]: [2] Sandbox: CanCreateUserNamespace() clone() failure: EPERM
|
||||
Mar 20 11:35:37 steamdeck firefox-bin[35304]: Failed to load module "canberra-gtk-module"
|
||||
Mar 20 11:35:37 steamdeck firefox-bin[35304]: Failed to load module "colorreload-gtk-module"
|
||||
Mar 20 11:35:37 steamdeck firefox-bin[35304]: Failed to load module "window-decorations-gtk-module"
|
||||
Mar 20 11:35:37 steamdeck flatpak[35304]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: VA-API version 1.22.0
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: User environment variable requested driver 'radeonsi'
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/radeonsi_drv_video.so
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/intel-vaapi-driver/radeonsi_drv_video.so
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: Trying to open /usr/lib/x86_64-linux-gnu/GL/lib/dri/radeonsi_drv_video.so
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: Found init function __vaDriverInit_1_22
|
||||
Mar 20 11:35:42 steamdeck flatpak[35437]: libva info: va_openDriver() returns 0
|
||||
Mar 20 11:35:44 steamdeck systemd[1357]: app-flatpak-org.mozilla.firefox-35291.scope: Consumed 13.250s CPU time, 1G memory peak.
|
||||
Mar 20 11:37:16 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:37:16 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:37:16 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:37:16 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:38:21 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:38:21 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:38:21 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:38:22 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:38:22 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:46:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:46:13 steamdeck plasmashell[3407]: kf.plasma.quick: Exposed with no visual parent. Window positioning broken.
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device removed\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: removing device USB OPTICAL MOUSE\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"fd\" \"137\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II)"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: " UnloadModule: \"libinput\"\n(II) systemd-logind: releasing fd for 13:74\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device USB OPTICAL MOUSE (/dev/input/mouse1)\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: Applying InputClass \"Pointer\"\n(II) Using input driver 'libinput' for ' USB OPTICAL MOUSE'\n(**) USB OPTICAL MOUSE: always reports core events\n(**) Option \"Device\" \"/dev/input/mouse1\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) mouse1 - not using input device '/dev/input/mouse1'.\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(EE) libinput: USB OPTICAL MOUSE: Failed to create a device for /dev/input/mouse1\n(EE) PreInit returned 2 for \" USB OPTICAL MOUSE\"\n(II) UnloadModule: \"libinput\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device USB OPTICAL MOUSE (/dev/input/event10)\n(**) USB OPTICAL MOUSE: Applying InputClass \"libinput pointer catchall\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: Applying InputClass \"Pointer\"\n(II) Using input driver 'libinput' for ' USB OPTICAL MOUSE'\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) systemd-logind: got fd for /dev/input/event10 13:74 fd 81 paused 0\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: always reports core events\n(**) Option \"Device\" \"/dev/input/event10\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: is tagged by udev as: Mouse\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device is a pointer\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device removed\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"AccelSpeed\" \"0\"\n(**) Option \"AccelProfile\" \"flat\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) libinput: USB OPTICAL MOUSE: Step value 0 was provided, libinput Fallback acceleration function is used.\n(II) libinput: USB OPTICAL MOUSE: Step value 0 was provided, libinput Fallback acceleration function is used.\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) libinput: USB OPTICAL MOUSE: Step value 0 was provided, libinput Fallback acceleration function is used.\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"config_info\" \"udev:/sys/devices/pci0000:00/0000:00:08.1/0000:04:00.3/usb1/1-1/1-1.2/1-1.2:1.0/0003:0000:3825.0011/input/input48/event10\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) XINPUT: Adding extended input device \" USB OPTICAL MOUSE\" (type: MOUSE, id 11)\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"AccelerationScheme\" \"none\"\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: (accel) selected scheme none/0\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: (accel) acceleration factor: 2.000\n(**) USB OPTICAL MOUSE: (accel) acceleration threshold: 4\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: is tagged by udev as: Mouse\n"
|
||||
Mar 20 11:51:58 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device is a pointer\n"
|
||||
Mar 20 11:51:59 steamdeck kcminit[35959]: Initializing "/usr/lib/qt6/plugins/plasma/kcms/systemsettings/kcm_mouse.so"
|
||||
Mar 20 11:51:59 steamdeck kcminit[35959]: Initializing "/usr/lib/qt6/plugins/plasma/kcms/systemsettings/kcm_touchpad.so"
|
||||
Mar 20 11:51:59 steamdeck kcminit[35959]: kcm_touchpad: Using X11 backend
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device removed\n"
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: removing device USB OPTICAL MOUSE\n"
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"fd\" \"81\""
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "\n"
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "(II)"
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: " UnloadModule: \"libinput\"\n(II) systemd-logind: releasing fd for 13:74\n"
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device USB OPTICAL MOUSE (/dev/input/mouse1)\n"
|
||||
Mar 20 11:52:00 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: Applying InputClass \"Pointer\"\n(II) Using input driver 'libinput' for ' USB OPTICAL MOUSE'\n(**) USB OPTICAL MOUSE: always reports core events\n(**) Option \"Device\" \"/dev/input/mouse1\"\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) mouse1 - not using input device '/dev/input/mouse1'.\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(EE) libinput: USB OPTICAL MOUSE: Failed to create a device for /dev/input/mouse1\n(EE) PreInit returned 2 for \" USB OPTICAL MOUSE\"\n(II) UnloadModule: \"libinput\"\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) config/udev: Adding input device USB OPTICAL MOUSE (/dev/input/event10)\n(**) USB OPTICAL MOUSE: Applying InputClass \"libinput pointer catchall\"\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: Applying InputClass \"Pointer\"\n(II) Using input driver 'libinput' for ' USB OPTICAL MOUSE'\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) systemd-logind: got fd for /dev/input/event10 13:74 fd 81 paused 0\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: always reports core events\n(**) Option \"Device\" \"/dev/input/event10\"\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: is tagged by udev as: Mouse\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device is a pointer\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device removed\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"AccelSpeed\" \"0\"\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"AccelProfile\" \"flat\"\n(II) libinput: USB OPTICAL MOUSE: Step value 0 was provided, libinput Fallback acceleration function is used.\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) libinput: USB OPTICAL MOUSE: Step value 0 was provided, libinput Fallback acceleration function is used.\n(II) libinput: USB OPTICAL MOUSE: Step value 0 was provided, libinput Fallback acceleration function is used.\n(**) Option \"config_info\" \"udev:/sys/devices/pci0000:00/0000:00:08.1/0000:04:00.3/usb1/1-1/1-1.2/1-1.2:1.0/0003:0000:3825.0012/input/input49/event10\"\n(II) XINPUT: Adding extended input device \" USB OPTICAL MOUSE\" (type: MOUSE, id 11)\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) Option \"AccelerationScheme\" \"none\"\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: (accel) selected scheme none/0\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(**) USB OPTICAL MOUSE: (accel) acceleration factor: 2.000\n(**) USB OPTICAL MOUSE: (accel) acceleration threshold: 4\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: is tagged by udev as: Mouse\n"
|
||||
Mar 20 11:52:01 steamdeck sddm-helper-start-x11user[3199]: "(II) event10 - USB OPTICAL MOUSE: device is a pointer\n"
|
||||
Mar 20 11:52:01 steamdeck kcminit[36008]: Initializing "/usr/lib/qt6/plugins/plasma/kcms/systemsettings/kcm_mouse.so"
|
||||
Mar 20 11:52:01 steamdeck kcminit[36008]: Initializing "/usr/lib/qt6/plugins/plasma/kcms/systemsettings/kcm_touchpad.so"
|
||||
Mar 20 11:52:01 steamdeck kcminit[36008]: kcm_touchpad: Using X11 backend
|
||||
Mar 20 12:06:13 steamdeck kwin_x11[3347]: kwin_core: XCB error: 152 (BadDamage), sequence: 55769, resource id: 23207116, major code: 143 (DAMAGE), minor code: 2 (Destroy)
|
||||
Mar 20 12:06:13 steamdeck kwin_x11[3347]: kwin_core: XCB error: 3 (BadWindow), sequence: 55770, resource id: 2097186, major code: 129 (SHAPE), minor code: 6 (Input)
|
||||
Mar 20 12:06:23 steamdeck kwin_x11[3347]: kwin_core: XCB error: 152 (BadDamage), sequence: 60041, resource id: 23207786, major code: 143 (DAMAGE), minor code: 2 (Destroy)
|
||||
Mar 20 12:06:23 steamdeck kwin_x11[3347]: kwin_core: XCB error: 3 (BadWindow), sequence: 60042, resource id: 2097187, major code: 129 (SHAPE), minor code: 6 (Input)
|
||||
Mar 20 12:06:35 steamdeck kwin_x11[3347]: kwin_core: XCB error: 152 (BadDamage), sequence: 65013, resource id: 23208486, major code: 143 (DAMAGE), minor code: 2 (Destroy)
|
||||
Mar 20 12:06:35 steamdeck kwin_x11[3347]: kwin_core: XCB error: 3 (BadWindow), sequence: 65014, resource id: 2097189, major code: 129 (SHAPE), minor code: 6 (Input)
|
||||
Mar 20 12:13:19 steamdeck systemd[1357]: Started Firefox - Web Browser.
|
||||
Mar 20 12:13:19 steamdeck systemd[1357]: Started app-flatpak-org.mozilla.firefox-38192.scope.
|
||||
Mar 20 12:13:19 steamdeck flatpak[38205]: [2] Sandbox: CanCreateUserNamespace() clone() failure: EPERM
|
||||
Mar 20 12:13:19 steamdeck firefox-bin[38205]: Failed to load module "canberra-gtk-module"
|
||||
Mar 20 12:13:19 steamdeck firefox-bin[38205]: Failed to load module "colorreload-gtk-module"
|
||||
Mar 20 12:13:19 steamdeck firefox-bin[38205]: Failed to load module "window-decorations-gtk-module"
|
||||
Mar 20 12:13:20 steamdeck flatpak[38205]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 12:13:28 steamdeck flatpak[38205]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 12:13:28 steamdeck flatpak[38205]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 12:13:28 steamdeck flatpak[38205]: ATTENTION: default value of option mesa_glthread overridden by environment.
|
||||
Mar 20 12:14:12 steamdeck systemd[1357]: app-flatpak-org.mozilla.firefox-38192.scope: Consumed 29.493s CPU time, 941.7M memory peak.
|
||||
Mar 20 12:17:17 steamdeck kwin_x11[3347]: kwin_core: XCB error: 152 (BadDamage), sequence: 15998, resource id: 23239729, major code: 143 (DAMAGE), minor code: 2 (Destroy)
|
||||
Mar 20 12:17:17 steamdeck kwin_x11[3347]: kwin_core: XCB error: 3 (BadWindow), sequence: 15999, resource id: 2097188, major code: 129 (SHAPE), minor code: 6 (Input)
|
||||
Mar 20 12:25:55 steamdeck podman[42059]: 2026-03-20 12:25:55.838940074 +0100 CET m=+0.035206979 system refresh
|
||||
Mar 20 12:25:55 steamdeck systemd[1357]: Started podman-42059.scope.
|
||||
Mar 20 12:25:55 steamdeck systemd[1357]: Started podman-pause-044fa0d2.scope.
|
||||
Mar 20 12:25:55 steamdeck sshd-session[42034]: Received disconnect from 172.20.10.3 port 63993:11: disconnected by user
|
||||
Mar 20 12:25:55 steamdeck sshd-session[42034]: Disconnected from user deck 172.20.10.3 port 63993
|
||||
0
deck-logs/heimgeist-websearch.txt
Normal file
0
deck-logs/heimgeist-websearch.txt
Normal file
2
deck-logs/searxng-weather.txt
Normal file
2
deck-logs/searxng-weather.txt
Normal file
File diff suppressed because one or more lines are too long
90
docs/tauri-migration.md
Normal file
90
docs/tauri-migration.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Tauri Migration Notes
|
||||
|
||||
Tauri is now Heimgeist's active desktop shell for local development. The former desktop shell runtime files and npm scripts have been removed from active development code.
|
||||
|
||||
## Current Development Workflow
|
||||
|
||||
- Primary dev command: `npm run dev`.
|
||||
- Compatibility alias: `npm run dev:tauri`.
|
||||
- The dev wrapper is `scripts/run-tauri-dev.cjs`.
|
||||
- The wrapper starts or reuses FastAPI on `127.0.0.1:8000`, waits for `/health`, then launches Tauri.
|
||||
- The Vite renderer runs on strict port `127.0.0.1:5174`.
|
||||
- `npm run dev:tauri:shell` launches raw `tauri dev` when the backend lifecycle is managed separately.
|
||||
|
||||
The development backend is still the normal FastAPI backend started from the repository root through `scripts/run-backend.cjs`.
|
||||
|
||||
## User Data Continuity
|
||||
|
||||
- Chats continue to use `backend/app.db` through the existing FastAPI backend.
|
||||
- Local RAG libraries continue to use `backend/libraries` through the existing FastAPI backend.
|
||||
- No database or library state is moved, rewritten, or migrated by the Tauri shell.
|
||||
- `HEIMGEIST_SETTINGS_FILE` remains an explicit shared settings override. When set, Tauri reads and writes that file directly and skips first-run import.
|
||||
- Without `HEIMGEIST_SETTINGS_FILE`, Tauri stores settings in its app config `settings.json`.
|
||||
- On first Tauri run only, when the Tauri settings file does not exist, Tauri attempts to import the historical Electron settings file from the platform config directory, including `Heimgeist/settings.json`.
|
||||
- Existing Tauri settings are never overwritten by imported settings.
|
||||
|
||||
## Packaged Backend Data Paths
|
||||
|
||||
The backend now centralizes runtime data paths in `backend/paths.py`.
|
||||
|
||||
- Development remains unchanged when no internal deployment hooks are set: chat data uses `backend/app.db` and local RAG data uses `backend/libraries`.
|
||||
- Packaged Tauri builds launch the backend with an app-managed data root so the backend stores data under the OS-appropriate app data directory.
|
||||
- The intended packaged locations are Application Support on macOS, LocalAppData on Windows, and the XDG data directory or `~/.local/share` equivalent on Linux.
|
||||
- `HEIMGEIST_DATA_DIR`, `HEIMGEIST_DB_PATH`, and `HEIMGEIST_LIB_ROOT` are internal app/sidecar plumbing hooks for packaged launchers and developer verification. They are not user-facing settings.
|
||||
- Packaging does not move or migrate existing development data.
|
||||
|
||||
## macOS Packaged App
|
||||
|
||||
The first local macOS `.app` flow is implemented.
|
||||
|
||||
- Packaging command: `npm run package:mac`.
|
||||
- Sidecar build command: `npm run build:sidecar`.
|
||||
- Output app: `src-tauri/target/release/bundle/macos/Heimgeist.app`.
|
||||
- `backend/sidecar_main.py` starts Uvicorn for `backend.main:app` on `127.0.0.1:8000`.
|
||||
- `scripts/build-backend-sidecar.cjs` uses `backend/.venv`, installs PyInstaller there if needed, detects the Rust host target triple, and writes Tauri external binaries under `src-tauri/binaries/`.
|
||||
- `src-tauri/tauri.conf.json` bundles the backend sidecar plus ffmpeg/ffprobe helper binaries through `bundle.externalBin`.
|
||||
- In release builds, `src-tauri/src/main.rs` starts the bundled sidecar when no compatible Heimgeist backend is already healthy on `127.0.0.1:8000`, waits for `/health`, and fails clearly if the port is occupied by a different service.
|
||||
- The Tauri shell passes `HEIMGEIST_DATA_DIR` and `HEIMGEIST_SETTINGS_FILE` to the sidecar. ffmpeg and ffprobe paths are passed when the bundled helpers exist.
|
||||
- The sidecar is stopped when the Tauri app exits.
|
||||
|
||||
Ollama remains an external service. SearXNG remains optional.
|
||||
|
||||
## Desktop Bridge Surface
|
||||
|
||||
Renderer code should continue to call only `src/desktop/desktopApi.js` for desktop functions. That bridge owns direct access to the Tauri global and maps the renderer API to Tauri commands/events.
|
||||
|
||||
Current Tauri-backed desktop methods:
|
||||
|
||||
- `getSettings`
|
||||
- `setSetting`
|
||||
- `updateSettings`
|
||||
- `pickPaths`
|
||||
- `openPath`
|
||||
- `openExternalLink`
|
||||
- `onWindowFocus`
|
||||
- `offWindowFocus`
|
||||
- `applyUiScale`
|
||||
- update/changelog placeholders
|
||||
|
||||
## Historical Removal Notes
|
||||
|
||||
This pass removed the former Electron runtime and development entry points:
|
||||
|
||||
- `electron/main.cjs`
|
||||
- `electron/preload.cjs`
|
||||
- `scripts/run-electron-dev.cjs`
|
||||
- Electron npm metadata, dependencies, and scripts from `package.json`
|
||||
- Electron-specific branches from `src/desktop/desktopApi.js`
|
||||
|
||||
The only remaining Electron references should be historical migration documentation or the Tauri first-run settings import note.
|
||||
|
||||
## Remaining Production-Release Tasks
|
||||
|
||||
- Replace update/changelog placeholders with a signed Tauri update flow or another release strategy.
|
||||
- Finalize signing and notarization for macOS distribution.
|
||||
- Implement updater/changelog parity or decide on a different release strategy.
|
||||
- Add full Windows/Linux sidecar and bundle scripts, including platform-specific helper binaries and process shutdown behavior.
|
||||
- Polish installer behavior and final bundle metadata/icons.
|
||||
- Audit the PyInstaller sidecar contents and size before public release.
|
||||
- Decide whether the settings route needs a dedicated Tauri window for production parity.
|
||||
- Expand the basic Tauri menu if product-specific app menu actions are needed.
|
||||
@@ -1,192 +0,0 @@
|
||||
|
||||
const { app, BrowserWindow, Menu, ipcMain, shell } = require('electron')
|
||||
const path = require('path')
|
||||
const { is } = require('@electron-toolkit/utils')
|
||||
const fs = require('fs')
|
||||
|
||||
let mainWindow
|
||||
let settingsWindow = null
|
||||
|
||||
const settingsFilePath = path.join(app.getPath('userData'), 'settings.json')
|
||||
let appSettings = {}
|
||||
|
||||
// Default settings
|
||||
const defaultSettings = {
|
||||
ollamaApiUrl: 'http://127.0.0.1:8000',
|
||||
colorScheme: 'Default',
|
||||
chatModel: 'llama3' // Set a default model here
|
||||
}
|
||||
|
||||
function loadSettings() {
|
||||
try {
|
||||
if (fs.existsSync(settingsFilePath)) {
|
||||
const data = fs.readFileSync(settingsFilePath, 'utf8')
|
||||
appSettings = { ...defaultSettings, ...JSON.parse(data) }
|
||||
} else {
|
||||
appSettings = { ...defaultSettings }
|
||||
saveSettings() // Create the file with default settings
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load settings:', error)
|
||||
appSettings = { ...defaultSettings }
|
||||
}
|
||||
}
|
||||
|
||||
function saveSettings() {
|
||||
try {
|
||||
fs.writeFileSync(settingsFilePath, JSON.stringify(appSettings, null, 2), 'utf8')
|
||||
} catch (error) {
|
||||
console.error('Failed to save settings:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function createMainWindow () {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1000,
|
||||
height: 720,
|
||||
minWidth: 680,
|
||||
minHeight: 300,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.cjs'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
})
|
||||
|
||||
mainWindow.on('ready-to-show', () => {
|
||||
mainWindow.show()
|
||||
})
|
||||
|
||||
mainWindow.on('focus', () => {
|
||||
mainWindow.webContents.send('window-focused');
|
||||
});
|
||||
|
||||
if (is.dev && process.env.VITE_DEV_SERVER_URL) {
|
||||
await mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
|
||||
mainWindow.webContents.openDevTools({ mode: 'detach' })
|
||||
} else {
|
||||
await mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
|
||||
}
|
||||
|
||||
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
}
|
||||
|
||||
async function createSettingsWindow () {
|
||||
if (settingsWindow) {
|
||||
settingsWindow.focus()
|
||||
return
|
||||
}
|
||||
|
||||
settingsWindow = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600,
|
||||
title: 'Settings',
|
||||
parent: mainWindow,
|
||||
modal: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.cjs'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
})
|
||||
|
||||
settingsWindow.on('ready-to-show', () => {
|
||||
settingsWindow.show()
|
||||
})
|
||||
|
||||
settingsWindow.on('closed', () => {
|
||||
settingsWindow = null
|
||||
})
|
||||
|
||||
if (is.dev && process.env.VITE_DEV_SERVER_URL) {
|
||||
await settingsWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#/settings`)
|
||||
settingsWindow.webContents.openDevTools({ mode: 'detach' })
|
||||
} else {
|
||||
await settingsWindow.loadFile(path.join(__dirname, '../dist/index.html'), { hash: '/settings' })
|
||||
}
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
loadSettings() // Load settings when the app is ready
|
||||
createMainWindow()
|
||||
|
||||
const menuTemplate = [
|
||||
{
|
||||
label: 'File',
|
||||
submenu: [
|
||||
{
|
||||
label: 'Settings',
|
||||
accelerator: 'CmdOrCtrl+,',
|
||||
click: createSettingsWindow
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit' }
|
||||
]
|
||||
},
|
||||
{
|
||||
label: 'Edit',
|
||||
submenu: [
|
||||
{ role: 'undo' },
|
||||
{ role: 'redo' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'cut' },
|
||||
{ role: 'copy' },
|
||||
{ role: 'paste' },
|
||||
{ role: 'delete' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'selectAll' }
|
||||
]
|
||||
},
|
||||
{
|
||||
label: 'View',
|
||||
submenu: [
|
||||
{ role: 'reload' },
|
||||
{ role: 'forcereload' },
|
||||
{ role: 'toggledevtools' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'resetzoom' },
|
||||
{ role: 'zoomin' },
|
||||
{ role: 'zoomout' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'togglefullscreen' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const menu = Menu.buildFromTemplate(menuTemplate)
|
||||
Menu.setApplicationMenu(menu)
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
|
||||
})
|
||||
})
|
||||
|
||||
// IPC handlers for settings
|
||||
ipcMain.handle('get-settings', () => {
|
||||
return appSettings
|
||||
})
|
||||
|
||||
ipcMain.handle('set-setting', (event, key, value) => {
|
||||
appSettings[key] = value
|
||||
saveSettings()
|
||||
return true
|
||||
})
|
||||
|
||||
ipcMain.handle('update-settings', (event, settings) => {
|
||||
appSettings = { ...appSettings, ...settings }
|
||||
saveSettings()
|
||||
return true
|
||||
})
|
||||
|
||||
ipcMain.on('open-external-link', (event, url) => {
|
||||
shell.openExternal(url)
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') app.quit()
|
||||
})
|
||||
@@ -1,15 +0,0 @@
|
||||
|
||||
const { contextBridge, ipcRenderer } = require('electron')
|
||||
|
||||
// Expose a secure API to the renderer process
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
getSettings: () => ipcRenderer.invoke('get-settings'),
|
||||
setSetting: (key, value) => ipcRenderer.invoke('set-setting', key, value),
|
||||
updateSettings: (settings) => ipcRenderer.invoke('update-settings', settings),
|
||||
openExternalLink: (event) => {
|
||||
event.preventDefault();
|
||||
const url = event.currentTarget.href;
|
||||
ipcRenderer.send('open-external-link', url);
|
||||
},
|
||||
onWindowFocus: (callback) => ipcRenderer.on('window-focused', callback)
|
||||
})
|
||||
24
package.json
24
package.json
@@ -2,28 +2,32 @@
|
||||
"name": "Heimgeist",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"main": "electron/main.cjs",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "concurrently -k \"npm:dev:backend\" \"npm:dev:renderer\" \"npm:dev:electron\"",
|
||||
"dev:backend": "python3 -m uvicorn backend.main:app --host 127.0.0.1 --port 8000 --reload",
|
||||
"dev:renderer": "vite --port 5173 --strictPort",
|
||||
"dev:electron": "wait-on http://localhost:5173 tcp:8000 && cross-env VITE_DEV_SERVER_URL=http://localhost:5173 electron .",
|
||||
"dev": "node scripts/run-tauri-dev.cjs",
|
||||
"dev:tauri": "node scripts/run-tauri-dev.cjs",
|
||||
"dev:backend": "node scripts/run-backend.cjs",
|
||||
"dev:renderer": "vite --host 127.0.0.1 --port 5174 --strictPort",
|
||||
"dev:tauri:shell": "tauri dev",
|
||||
"tauri": "tauri",
|
||||
"build": "vite build",
|
||||
"start": "electron ."
|
||||
"build:sidecar": "node scripts/build-backend-sidecar.cjs",
|
||||
"package:mac": "npm run build:sidecar && tauri build --bundles app",
|
||||
"build:app": "npm run package:mac",
|
||||
"start": "npm run dev"
|
||||
},
|
||||
"dependencies": {
|
||||
"@electron-toolkit/utils": "^4.0.0",
|
||||
"@xyflow/react": "^12.11.0",
|
||||
"ffmpeg-static": "^5.3.0",
|
||||
"ffprobe-static": "^3.1.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^7.8.1",
|
||||
"react-textarea-autosize": "^8.5.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.11.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"concurrently": "^9.0.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"electron": "^31.2.0",
|
||||
"vite": "^5.4.2",
|
||||
"wait-on": "^7.2.0"
|
||||
}
|
||||
|
||||
767
run.sh
767
run.sh
@@ -1,6 +1,763 @@
|
||||
#!/bin/sh
|
||||
python -m venv backend/.venv
|
||||
source backend/.venv/bin/activate
|
||||
pip install -r backend/requirements.txt
|
||||
npm install
|
||||
npm run dev
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR="$(CDPATH= cd "$(dirname "$0")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
PYTHON_BIN_WAS_SET=0
|
||||
if [ -n "${PYTHON_BIN:-}" ]; then
|
||||
PYTHON_BIN_WAS_SET=1
|
||||
fi
|
||||
PYTHON_BIN="${PYTHON_BIN:-python3.13}"
|
||||
VENV_DIR="backend/.venv"
|
||||
TORCH_FLAVOR_FILE="$VENV_DIR/.heimgeist-torch-flavor"
|
||||
TORCH_STATE_FILE="$VENV_DIR/.heimgeist-torch-state"
|
||||
PYTHON_DEPS_STATE_FILE="$VENV_DIR/.heimgeist-python-deps-state"
|
||||
NODE_DEPS_STATE_FILE="node_modules/.heimgeist-node-deps-state"
|
||||
HEIMGEIST_NODE_MAJOR="${HEIMGEIST_NODE_MAJOR:-22}"
|
||||
HEIMGEIST_NODE_DIR="${HEIMGEIST_NODE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/heimgeist/node-v$HEIMGEIST_NODE_MAJOR}"
|
||||
HEIMGEIST_TOOL_BIN_DIR="${HEIMGEIST_TOOL_BIN_DIR:-$HOME/.local/bin}"
|
||||
HEIMGEIST_SKIP_SYSTEM_DEPS="${HEIMGEIST_SKIP_SYSTEM_DEPS:-0}"
|
||||
HEIMGEIST_STRICT_SYSTEM_DEPS="${HEIMGEIST_STRICT_SYSTEM_DEPS:-0}"
|
||||
HEIMGEIST_BOOTSTRAP_ONLY="${HEIMGEIST_BOOTSTRAP_ONLY:-0}"
|
||||
HEIMGEIST_STEAMOS_DEVMODE="${HEIMGEIST_STEAMOS_DEVMODE:-auto}"
|
||||
HEIMGEIST_TORCH_FLAVOR="${HEIMGEIST_TORCH_FLAVOR:-auto}"
|
||||
HEIMGEIST_TORCH_INDEX_URL="${HEIMGEIST_TORCH_INDEX_URL:-}"
|
||||
HEIMGEIST_FORCE_BOOTSTRAP="${HEIMGEIST_FORCE_BOOTSTRAP:-0}"
|
||||
CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}"
|
||||
RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}"
|
||||
PATH="$HEIMGEIST_TOOL_BIN_DIR:$CARGO_HOME/bin:$PATH"
|
||||
export CARGO_HOME RUSTUP_HOME PATH
|
||||
|
||||
as_root() {
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
"$@"
|
||||
return
|
||||
fi
|
||||
if ! command -v sudo >/dev/null 2>&1; then
|
||||
echo "Installing native build dependencies requires root access, but sudo is unavailable." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! sudo -v; then
|
||||
if is_steamos; then
|
||||
echo "SteamOS needs a local user password for sudo. Run 'passwd', then rerun ./run.sh." >&2
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
sudo "$@"
|
||||
}
|
||||
|
||||
is_steamos() {
|
||||
[ -r /etc/os-release ] \
|
||||
&& grep -Eiq '(^ID=steamos$|^NAME=.*SteamOS|^PRETTY_NAME=.*SteamOS)' /etc/os-release
|
||||
}
|
||||
|
||||
linux_native_deps_usable() {
|
||||
command -v cc >/dev/null 2>&1 \
|
||||
&& command -v file >/dev/null 2>&1 \
|
||||
&& command -v pkg-config >/dev/null 2>&1 \
|
||||
&& pkg-config --exists webkit2gtk-4.1 gtk+-3.0 openssl librsvg-2.0
|
||||
}
|
||||
|
||||
print_native_dependency_report() {
|
||||
echo "Native dependency preflight report:" >&2
|
||||
for command_name in cc file pkg-config; do
|
||||
if command -v "$command_name" >/dev/null 2>&1; then
|
||||
echo " ok: command '$command_name' -> $(command -v "$command_name")" >&2
|
||||
else
|
||||
echo " missing: command '$command_name'" >&2
|
||||
fi
|
||||
done
|
||||
|
||||
if ! command -v pkg-config >/dev/null 2>&1; then
|
||||
return
|
||||
fi
|
||||
|
||||
for pkg_config_name in webkit2gtk-4.1 gtk+-3.0 openssl librsvg-2.0; do
|
||||
if pkg-config --exists "$pkg_config_name"; then
|
||||
pkg_config_version="$(pkg-config --modversion "$pkg_config_name" 2>/dev/null || true)"
|
||||
echo " ok: pkg-config '$pkg_config_name' ${pkg_config_version}" >&2
|
||||
else
|
||||
echo " missing: pkg-config '$pkg_config_name'" >&2
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
handle_incomplete_native_dependencies() {
|
||||
echo "The native Tauri dependency preflight is still incomplete after package installation." >&2
|
||||
print_native_dependency_report
|
||||
if [ "$HEIMGEIST_STRICT_SYSTEM_DEPS" = "1" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Continuing because the package manager reported success." >&2
|
||||
echo "If the Tauri build still fails, rerun with HEIMGEIST_STRICT_SYSTEM_DEPS=1 for a hard preflight failure." >&2
|
||||
}
|
||||
|
||||
STEAMOS_RESTORE_READONLY=0
|
||||
|
||||
restore_steamos_readonly() {
|
||||
if [ "$STEAMOS_RESTORE_READONLY" -eq 1 ]; then
|
||||
echo "Re-enabling the SteamOS read-only filesystem"
|
||||
as_root steamos-readonly enable
|
||||
STEAMOS_RESTORE_READONLY=0
|
||||
fi
|
||||
}
|
||||
|
||||
prepare_steamos_package_install() {
|
||||
if ! is_steamos || ! command -v steamos-readonly >/dev/null 2>&1; then
|
||||
return
|
||||
fi
|
||||
|
||||
readonly_status="$(as_root steamos-readonly status || true)"
|
||||
if printf '%s\n' "$readonly_status" | grep -Eqi '(^|[[:space:]])enable(d)?($|[[:space:]])'; then
|
||||
echo "Temporarily disabling the SteamOS read-only filesystem"
|
||||
as_root steamos-readonly disable
|
||||
STEAMOS_RESTORE_READONLY=1
|
||||
fi
|
||||
}
|
||||
|
||||
pacman_keyring_names() {
|
||||
for keyring_file in /usr/share/pacman/keyrings/*.gpg; do
|
||||
[ -e "$keyring_file" ] || continue
|
||||
keyring_name="$(basename "$keyring_file" .gpg)"
|
||||
printf ' %s' "$keyring_name"
|
||||
done
|
||||
}
|
||||
|
||||
ensure_steamos_pacman_keyring() {
|
||||
if ! is_steamos; then
|
||||
return
|
||||
fi
|
||||
if ! command -v pacman-key >/dev/null 2>&1; then
|
||||
echo "SteamOS package signing cannot be repaired because pacman-key is unavailable." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Initializing and populating the SteamOS pacman keyring"
|
||||
as_root pacman-key --init
|
||||
|
||||
keyring_names="$(pacman_keyring_names)"
|
||||
if [ -n "$keyring_names" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
as_root pacman-key --populate $keyring_names
|
||||
else
|
||||
as_root pacman-key --populate
|
||||
fi
|
||||
}
|
||||
|
||||
run_steamos_devmode_bootstrap() {
|
||||
if ! is_steamos || [ "$HEIMGEIST_STEAMOS_DEVMODE" = "0" ]; then
|
||||
return 1
|
||||
fi
|
||||
if ! command -v steamos-devmode >/dev/null 2>&1; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "Pacman still cannot install packages; running SteamOS devmode bootstrap"
|
||||
as_root steamos-devmode enable
|
||||
}
|
||||
|
||||
install_pacman_packages() {
|
||||
if as_root pacman "$@"; then
|
||||
return
|
||||
fi
|
||||
|
||||
if ! is_steamos; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "Pacman failed on SteamOS. Refreshing package-signing trust and retrying once."
|
||||
ensure_steamos_pacman_keyring
|
||||
if as_root pacman "$@"; then
|
||||
return
|
||||
fi
|
||||
|
||||
if run_steamos_devmode_bootstrap && as_root pacman "$@"; then
|
||||
return
|
||||
fi
|
||||
|
||||
echo "SteamOS pacman package installation still failed." >&2
|
||||
echo "This is usually a broken SteamOS pacman keyring, not a corrupt Heimgeist download." >&2
|
||||
echo "Try running 'sudo steamos-devmode enable' manually, then rerun ./run.sh." >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
install_arch_native_deps() {
|
||||
set -- \
|
||||
webkit2gtk-4.1 \
|
||||
base-devel \
|
||||
pkgconf \
|
||||
gtk3 \
|
||||
curl \
|
||||
wget \
|
||||
file \
|
||||
openssl \
|
||||
appmenu-gtk-module \
|
||||
libappindicator-gtk3 \
|
||||
librsvg \
|
||||
xdotool
|
||||
|
||||
missing_packages=""
|
||||
for package_name in "$@"; do
|
||||
if ! pacman -Q "$package_name" >/dev/null 2>&1; then
|
||||
missing_packages="$missing_packages $package_name"
|
||||
fi
|
||||
done
|
||||
if [ -z "$missing_packages" ]; then
|
||||
return
|
||||
fi
|
||||
|
||||
echo "Installing missing Tauri/Arch packages:$missing_packages"
|
||||
echo "SteamOS/Arch may ask for your sudo password."
|
||||
prepare_steamos_package_install
|
||||
trap 'restore_steamos_readonly' EXIT
|
||||
trap 'restore_steamos_readonly; exit 130' HUP INT TERM
|
||||
ensure_steamos_pacman_keyring
|
||||
|
||||
install_status=0
|
||||
if is_steamos; then
|
||||
# SteamOS system updates own the base image, so only install missing packages.
|
||||
install_pacman_packages -S --needed --noconfirm $missing_packages || install_status=$?
|
||||
else
|
||||
# Arch requires a full upgrade when synchronizing/installing packages.
|
||||
install_pacman_packages -Syu --needed --noconfirm $missing_packages || install_status=$?
|
||||
fi
|
||||
|
||||
restore_steamos_readonly
|
||||
trap - EXIT HUP INT TERM
|
||||
return "$install_status"
|
||||
}
|
||||
|
||||
install_debian_native_deps() {
|
||||
set -- \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
build-essential \
|
||||
curl \
|
||||
wget \
|
||||
file \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
libayatana-appindicator3-dev \
|
||||
librsvg2-dev \
|
||||
pkg-config
|
||||
|
||||
missing_packages=""
|
||||
for package_name in "$@"; do
|
||||
if ! dpkg-query -W -f='${Status}' "$package_name" 2>/dev/null | grep -q 'ok installed'; then
|
||||
missing_packages="$missing_packages $package_name"
|
||||
fi
|
||||
done
|
||||
if [ -z "$missing_packages" ]; then
|
||||
return
|
||||
fi
|
||||
|
||||
echo "Installing missing Tauri/Debian packages:$missing_packages"
|
||||
as_root apt-get update
|
||||
as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y $missing_packages
|
||||
}
|
||||
|
||||
ensure_native_build_dependencies() {
|
||||
if [ "$HEIMGEIST_SKIP_SYSTEM_DEPS" = "1" ]; then
|
||||
return
|
||||
fi
|
||||
|
||||
case "$(uname -s)" in
|
||||
Darwin)
|
||||
if ! xcode-select -p >/dev/null 2>&1; then
|
||||
echo "Installing the Xcode Command Line Tools required by Tauri."
|
||||
xcode-select --install || true
|
||||
echo "Complete the Xcode Command Line Tools installation, then run ./run.sh again." >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
Linux)
|
||||
if linux_native_deps_usable; then
|
||||
return
|
||||
fi
|
||||
if command -v pacman >/dev/null 2>&1; then
|
||||
install_arch_native_deps
|
||||
elif command -v apt-get >/dev/null 2>&1 && command -v dpkg-query >/dev/null 2>&1; then
|
||||
install_debian_native_deps
|
||||
else
|
||||
echo "Native dependency installation currently supports Arch/SteamOS and Debian/Ubuntu." >&2
|
||||
echo "Install your distribution's Tauri 2 system prerequisites, then run ./run.sh again." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! linux_native_deps_usable; then
|
||||
handle_incomplete_native_dependencies
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
node_runtime_usable() {
|
||||
command -v node >/dev/null 2>&1 \
|
||||
&& command -v npm >/dev/null 2>&1 \
|
||||
&& node -e 'const major = Number(process.versions.node.split(".")[0]); process.exit(major >= 18 ? 0 : 1)' >/dev/null 2>&1
|
||||
}
|
||||
|
||||
download_file() {
|
||||
download_url="$1"
|
||||
download_target="$2"
|
||||
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
curl --fail --location --silent --show-error "$download_url" --output "$download_target"
|
||||
return
|
||||
fi
|
||||
if command -v wget >/dev/null 2>&1; then
|
||||
wget --quiet --output-document="$download_target" "$download_url"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "A required tool is missing and neither curl nor wget is available to download it." >&2
|
||||
echo "Install curl or wget, then run ./run.sh again." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
file_sha256() {
|
||||
checksum_file="$1"
|
||||
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
sha256sum "$checksum_file" | awk '{print $1}'
|
||||
return
|
||||
fi
|
||||
if command -v shasum >/dev/null 2>&1; then
|
||||
shasum -a 256 "$checksum_file" | awk '{print $1}'
|
||||
return
|
||||
fi
|
||||
|
||||
echo "Cannot verify the Node.js download because sha256sum/shasum is unavailable." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
install_uv() {
|
||||
uv_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimgeist-uv.XXXXXX")"
|
||||
trap 'rm -rf "$uv_tmp_dir"' EXIT HUP INT TERM
|
||||
|
||||
echo "Python 3.13 is missing; installing the uv runtime manager locally"
|
||||
download_file "https://astral.sh/uv/install.sh" "$uv_tmp_dir/install.sh"
|
||||
mkdir -p "$HEIMGEIST_TOOL_BIN_DIR"
|
||||
UV_UNMANAGED_INSTALL="$HEIMGEIST_TOOL_BIN_DIR" UV_NO_MODIFY_PATH=1 sh "$uv_tmp_dir/install.sh"
|
||||
|
||||
rm -rf "$uv_tmp_dir"
|
||||
trap - EXIT HUP INT TERM
|
||||
}
|
||||
|
||||
ensure_uv() {
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
return
|
||||
fi
|
||||
|
||||
install_uv
|
||||
if ! command -v uv >/dev/null 2>&1; then
|
||||
echo "The local uv installation did not provide an executable." >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
python_runtime_usable() {
|
||||
command -v "$PYTHON_BIN" >/dev/null 2>&1 \
|
||||
&& "$PYTHON_BIN" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 13) else 1)' >/dev/null 2>&1
|
||||
}
|
||||
|
||||
ensure_python_runtime() {
|
||||
if python_runtime_usable; then
|
||||
return
|
||||
fi
|
||||
if [ "$PYTHON_BIN_WAS_SET" -eq 1 ]; then
|
||||
echo "PYTHON_BIN '$PYTHON_BIN' is unavailable or is not Python 3.13." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ensure_uv
|
||||
echo "Installing Python 3.13 locally"
|
||||
uv python install 3.13
|
||||
PYTHON_BIN="$(uv python find 3.13)"
|
||||
|
||||
if ! python_runtime_usable; then
|
||||
echo "The local Python 3.13 installation is incomplete." >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
rust_runtime_usable() {
|
||||
command -v cargo >/dev/null 2>&1 \
|
||||
&& command -v rustc >/dev/null 2>&1 \
|
||||
&& rustc --version | awk '
|
||||
{
|
||||
split($2, version, ".")
|
||||
exit !((version[1] > 1) || (version[1] == 1 && version[2] >= 77))
|
||||
}
|
||||
'
|
||||
}
|
||||
|
||||
install_rustup() {
|
||||
rustup_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimgeist-rustup.XXXXXX")"
|
||||
trap 'rm -rf "$rustup_tmp_dir"' EXIT HUP INT TERM
|
||||
|
||||
echo "Rust/Cargo 1.77+ was not found; installing the stable Rust toolchain locally"
|
||||
download_file "https://sh.rustup.rs" "$rustup_tmp_dir/rustup-init.sh"
|
||||
sh "$rustup_tmp_dir/rustup-init.sh" -y --profile minimal --default-toolchain stable --no-modify-path
|
||||
|
||||
rm -rf "$rustup_tmp_dir"
|
||||
trap - EXIT HUP INT TERM
|
||||
}
|
||||
|
||||
ensure_rust_runtime() {
|
||||
if rust_runtime_usable; then
|
||||
return
|
||||
fi
|
||||
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
echo "Installing/updating the stable Rust toolchain"
|
||||
rustup toolchain install stable --profile minimal
|
||||
rustup default stable
|
||||
else
|
||||
install_rustup
|
||||
fi
|
||||
|
||||
if ! rust_runtime_usable; then
|
||||
echo "The Rust installation is incomplete; cargo and rustc 1.77+ are required." >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
install_project_node() {
|
||||
case "$(uname -s)" in
|
||||
Linux) node_platform="linux" ;;
|
||||
Darwin) node_platform="darwin" ;;
|
||||
*)
|
||||
echo "Automatic Node.js installation is only supported on Linux and macOS." >&2
|
||||
echo "Install Node.js 18+ and npm, then run ./run.sh again." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$(uname -m)" in
|
||||
x86_64|amd64) node_arch="x64" ;;
|
||||
arm64|aarch64) node_arch="arm64" ;;
|
||||
*)
|
||||
echo "Automatic Node.js installation does not support architecture $(uname -m)." >&2
|
||||
echo "Install Node.js 18+ and npm, then run ./run.sh again." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
node_release_url="https://nodejs.org/dist/latest-v$HEIMGEIST_NODE_MAJOR.x"
|
||||
node_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimgeist-node.XXXXXX")"
|
||||
trap 'rm -rf "$node_tmp_dir"' EXIT HUP INT TERM
|
||||
|
||||
echo "Node.js 18+ with npm was not found; installing Node.js v$HEIMGEIST_NODE_MAJOR locally"
|
||||
download_file "$node_release_url/SHASUMS256.txt" "$node_tmp_dir/SHASUMS256.txt"
|
||||
|
||||
node_archive="$(awk -v suffix="-$node_platform-$node_arch.tar.xz" '
|
||||
length($2) >= length(suffix) && substr($2, length($2) - length(suffix) + 1) == suffix {
|
||||
print $2
|
||||
exit
|
||||
}
|
||||
' "$node_tmp_dir/SHASUMS256.txt")"
|
||||
if [ -z "$node_archive" ]; then
|
||||
echo "No Node.js v$HEIMGEIST_NODE_MAJOR archive is available for $node_platform-$node_arch." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
expected_sha256="$(awk -v archive="$node_archive" '$2 == archive {print $1; exit}' "$node_tmp_dir/SHASUMS256.txt")"
|
||||
download_file "$node_release_url/$node_archive" "$node_tmp_dir/$node_archive"
|
||||
actual_sha256="$(file_sha256 "$node_tmp_dir/$node_archive")"
|
||||
if [ "$actual_sha256" != "$expected_sha256" ]; then
|
||||
echo "Node.js download checksum verification failed." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
tar -xJf "$node_tmp_dir/$node_archive" -C "$node_tmp_dir"
|
||||
mkdir -p "$(dirname "$HEIMGEIST_NODE_DIR")"
|
||||
rm -rf "$HEIMGEIST_NODE_DIR"
|
||||
mv "$node_tmp_dir/${node_archive%.tar.xz}" "$HEIMGEIST_NODE_DIR"
|
||||
rm -rf "$node_tmp_dir"
|
||||
trap - EXIT HUP INT TERM
|
||||
}
|
||||
|
||||
ensure_node_runtime() {
|
||||
if node_runtime_usable; then
|
||||
return
|
||||
fi
|
||||
|
||||
if [ -x "$HEIMGEIST_NODE_DIR/bin/node" ] && [ -x "$HEIMGEIST_NODE_DIR/bin/npm" ]; then
|
||||
original_path="$PATH"
|
||||
PATH="$HEIMGEIST_NODE_DIR/bin:$PATH"
|
||||
export PATH
|
||||
if node_runtime_usable; then
|
||||
return
|
||||
fi
|
||||
PATH="$original_path"
|
||||
export PATH
|
||||
fi
|
||||
|
||||
install_project_node
|
||||
PATH="$HEIMGEIST_NODE_DIR/bin:$PATH"
|
||||
export PATH
|
||||
|
||||
if ! node_runtime_usable; then
|
||||
echo "The local Node.js installation is incomplete or older than version 18." >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
manifest_state() {
|
||||
for manifest_path in "$@"; do
|
||||
if [ -f "$manifest_path" ]; then
|
||||
checksum="$(cksum "$manifest_path" | awk '{print $1 ":" $2}')"
|
||||
printf '%s %s\n' "$manifest_path" "$checksum"
|
||||
else
|
||||
printf '%s missing\n' "$manifest_path"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
state_matches() {
|
||||
state_file="$1"
|
||||
shift
|
||||
[ -r "$state_file" ] || return 1
|
||||
current_state="$(manifest_state "$@")"
|
||||
saved_state="$(cat "$state_file")"
|
||||
[ "$saved_state" = "$current_state" ]
|
||||
}
|
||||
|
||||
write_state() {
|
||||
state_file="$1"
|
||||
shift
|
||||
manifest_state "$@" > "$state_file"
|
||||
}
|
||||
|
||||
current_torch_state() {
|
||||
printf 'flavor=%s\nindex=%s\n' "$TORCH_FLAVOR" "$HEIMGEIST_TORCH_INDEX_URL"
|
||||
}
|
||||
|
||||
torch_state_matches() {
|
||||
[ -r "$TORCH_STATE_FILE" ] || return 1
|
||||
saved_state="$(cat "$TORCH_STATE_FILE")"
|
||||
[ "$saved_state" = "$(current_torch_state)" ]
|
||||
}
|
||||
|
||||
write_torch_state() {
|
||||
current_torch_state > "$TORCH_STATE_FILE"
|
||||
}
|
||||
|
||||
python_deps_usable() {
|
||||
"$VENV_DIR/bin/python" - <<'PY' >/dev/null 2>&1
|
||||
import fastapi
|
||||
import httpx
|
||||
import pydantic
|
||||
import sqlalchemy
|
||||
import uvicorn
|
||||
import whisper
|
||||
PY
|
||||
}
|
||||
|
||||
node_deps_usable() {
|
||||
node - <<'NODE' >/dev/null 2>&1
|
||||
require('react')
|
||||
require('vite')
|
||||
require('wait-on')
|
||||
NODE
|
||||
if [ "$?" -ne 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
[ -x node_modules/.bin/tauri ] || [ -x node_modules/.bin/tauri.cmd ]
|
||||
}
|
||||
|
||||
is_linux_x86_64() {
|
||||
[ "$(uname -s)" = "Linux" ] && [ "$(uname -m)" = "x86_64" ]
|
||||
}
|
||||
|
||||
has_nvidia_gpu() {
|
||||
if command -v nvidia-smi >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
for vendor_file in /sys/class/drm/card*/device/vendor; do
|
||||
[ -r "$vendor_file" ] || continue
|
||||
if grep -qi "0x10de" "$vendor_file"; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
is_steam_deck() {
|
||||
if [ -r /etc/os-release ] && grep -Eiq '(^ID=steamos$|^NAME=.*SteamOS|^PRETTY_NAME=.*SteamOS)' /etc/os-release; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
for dmi_file in \
|
||||
/sys/devices/virtual/dmi/id/product_name \
|
||||
/sys/devices/virtual/dmi/id/product_version \
|
||||
/sys/devices/virtual/dmi/id/board_name
|
||||
do
|
||||
[ -r "$dmi_file" ] || continue
|
||||
if grep -Eiq 'steam deck|jupiter|galileo' "$dmi_file"; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
resolve_torch_flavor() {
|
||||
case "$HEIMGEIST_TORCH_FLAVOR" in
|
||||
auto)
|
||||
if is_linux_x86_64; then
|
||||
if is_steam_deck; then
|
||||
printf '%s\n' "cpu"
|
||||
return
|
||||
fi
|
||||
if has_nvidia_gpu; then
|
||||
printf '%s\n' "default"
|
||||
return
|
||||
fi
|
||||
printf '%s\n' "cpu"
|
||||
return
|
||||
fi
|
||||
printf '%s\n' "default"
|
||||
;;
|
||||
default|cpu|cuda|rocm|rocm6.4)
|
||||
printf '%s\n' "$HEIMGEIST_TORCH_FLAVOR"
|
||||
;;
|
||||
*)
|
||||
echo "Unsupported HEIMGEIST_TORCH_FLAVOR '$HEIMGEIST_TORCH_FLAVOR'. Use auto, default, cpu, cuda, rocm, or rocm6.4." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
install_selected_torch() {
|
||||
torch_flavor="$1"
|
||||
|
||||
if [ -n "$HEIMGEIST_TORCH_INDEX_URL" ]; then
|
||||
echo "Installing PyTorch from custom index: $HEIMGEIST_TORCH_INDEX_URL"
|
||||
"$VENV_DIR/bin/python" -m pip install --upgrade --index-url "$HEIMGEIST_TORCH_INDEX_URL" torch
|
||||
return
|
||||
fi
|
||||
|
||||
case "$torch_flavor" in
|
||||
default|cuda)
|
||||
return
|
||||
;;
|
||||
cpu)
|
||||
echo "Installing CPU-only PyTorch for Whisper"
|
||||
"$VENV_DIR/bin/python" -m pip install --upgrade --index-url https://download.pytorch.org/whl/cpu torch
|
||||
;;
|
||||
rocm|rocm6.4)
|
||||
echo "Installing ROCm PyTorch for Whisper"
|
||||
"$VENV_DIR/bin/python" -m pip install --upgrade --index-url https://download.pytorch.org/whl/rocm6.4 torch
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
ensure_native_build_dependencies
|
||||
ensure_node_runtime
|
||||
ensure_python_runtime
|
||||
ensure_rust_runtime
|
||||
|
||||
TORCH_FLAVOR="$(resolve_torch_flavor)"
|
||||
RECREATE_VENV=0
|
||||
|
||||
if [ ! -x "$VENV_DIR/bin/python" ] || ! "$VENV_DIR/bin/python" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 13) else 1)'; then
|
||||
RECREATE_VENV=1
|
||||
fi
|
||||
|
||||
if [ "$RECREATE_VENV" -eq 0 ]; then
|
||||
PREVIOUS_TORCH_FLAVOR=""
|
||||
if [ -r "$TORCH_FLAVOR_FILE" ]; then
|
||||
PREVIOUS_TORCH_FLAVOR="$(cat "$TORCH_FLAVOR_FILE")"
|
||||
fi
|
||||
if [ -n "$PREVIOUS_TORCH_FLAVOR" ] && [ "$PREVIOUS_TORCH_FLAVOR" != "$TORCH_FLAVOR" ]; then
|
||||
RECREATE_VENV=1
|
||||
elif [ -z "$PREVIOUS_TORCH_FLAVOR" ] && [ "$TORCH_FLAVOR" != "default" ]; then
|
||||
RECREATE_VENV=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$RECREATE_VENV" -eq 1 ]; then
|
||||
rm -rf "$VENV_DIR"
|
||||
"$PYTHON_BIN" -m venv "$VENV_DIR"
|
||||
fi
|
||||
|
||||
printf '%s\n' "$TORCH_FLAVOR" > "$TORCH_FLAVOR_FILE"
|
||||
echo "Using PyTorch flavor: $TORCH_FLAVOR"
|
||||
|
||||
NEEDS_LEGACY_PYTHON_STATE=0
|
||||
if [ ! -r "$PYTHON_DEPS_STATE_FILE" ]; then
|
||||
NEEDS_LEGACY_PYTHON_STATE=1
|
||||
fi
|
||||
if [ -z "$HEIMGEIST_TORCH_INDEX_URL" ] && [ ! -r "$TORCH_STATE_FILE" ]; then
|
||||
NEEDS_LEGACY_PYTHON_STATE=1
|
||||
fi
|
||||
|
||||
if [ "$RECREATE_VENV" -eq 0 ] && [ "$NEEDS_LEGACY_PYTHON_STATE" -eq 1 ] && python_deps_usable; then
|
||||
if [ ! -r "$PYTHON_DEPS_STATE_FILE" ]; then
|
||||
write_state "$PYTHON_DEPS_STATE_FILE" backend/requirements.txt
|
||||
fi
|
||||
if [ -z "$HEIMGEIST_TORCH_INDEX_URL" ] && [ ! -r "$TORCH_STATE_FILE" ]; then
|
||||
write_torch_state
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -d node_modules ] && [ ! -r "$NODE_DEPS_STATE_FILE" ] && node_deps_usable; then
|
||||
write_state "$NODE_DEPS_STATE_FILE" package.json package-lock.json
|
||||
fi
|
||||
|
||||
NEED_PYTHON_DEPS_INSTALL="$RECREATE_VENV"
|
||||
NEED_TORCH_INSTALL="$RECREATE_VENV"
|
||||
NEED_NODE_DEPS_INSTALL=0
|
||||
|
||||
if [ "$HEIMGEIST_FORCE_BOOTSTRAP" = "1" ]; then
|
||||
NEED_PYTHON_DEPS_INSTALL=1
|
||||
NEED_TORCH_INSTALL=1
|
||||
NEED_NODE_DEPS_INSTALL=1
|
||||
fi
|
||||
|
||||
if [ "$NEED_PYTHON_DEPS_INSTALL" -eq 0 ] && ! state_matches "$PYTHON_DEPS_STATE_FILE" backend/requirements.txt; then
|
||||
NEED_PYTHON_DEPS_INSTALL=1
|
||||
fi
|
||||
|
||||
if [ "$NEED_TORCH_INSTALL" -eq 0 ] && ! torch_state_matches; then
|
||||
NEED_TORCH_INSTALL=1
|
||||
fi
|
||||
|
||||
if [ "$NEED_PYTHON_DEPS_INSTALL" -eq 1 ]; then
|
||||
echo "Installing Python dependencies"
|
||||
"$VENV_DIR/bin/python" -m pip install --upgrade pip
|
||||
if [ "$NEED_TORCH_INSTALL" -eq 1 ]; then
|
||||
install_selected_torch "$TORCH_FLAVOR"
|
||||
write_torch_state
|
||||
fi
|
||||
"$VENV_DIR/bin/python" -m pip install -r backend/requirements.txt
|
||||
write_state "$PYTHON_DEPS_STATE_FILE" backend/requirements.txt
|
||||
elif [ "$NEED_TORCH_INSTALL" -eq 1 ]; then
|
||||
install_selected_torch "$TORCH_FLAVOR"
|
||||
write_torch_state
|
||||
fi
|
||||
|
||||
if [ ! -d node_modules ]; then
|
||||
NEED_NODE_DEPS_INSTALL=1
|
||||
elif ! state_matches "$NODE_DEPS_STATE_FILE" package.json package-lock.json; then
|
||||
NEED_NODE_DEPS_INSTALL=1
|
||||
fi
|
||||
|
||||
if [ "$NEED_NODE_DEPS_INSTALL" -eq 1 ]; then
|
||||
echo "Installing Node dependencies"
|
||||
npm install --no-fund --no-audit
|
||||
mkdir -p node_modules
|
||||
write_state "$NODE_DEPS_STATE_FILE" package.json package-lock.json
|
||||
fi
|
||||
|
||||
if [ "$HEIMGEIST_BOOTSTRAP_ONLY" = "1" ]; then
|
||||
echo "Heimgeist development dependencies are ready."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
npm run dev
|
||||
|
||||
178
scripts/build-backend-sidecar.cjs
Normal file
178
scripts/build-backend-sidecar.cjs
Normal file
@@ -0,0 +1,178 @@
|
||||
const { execFileSync, spawnSync } = require('child_process')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..')
|
||||
const pythonBin = path.join(projectRoot, 'backend', '.venv', 'bin', 'python')
|
||||
const binariesDir = path.join(projectRoot, 'src-tauri', 'binaries')
|
||||
const targetTriple = resolveTargetTriple()
|
||||
const executableExtension = process.platform === 'win32' ? '.exe' : ''
|
||||
const backendOutputName = `heimgeist-backend-${targetTriple}${executableExtension}`
|
||||
const backendOutputPath = path.join(binariesDir, backendOutputName)
|
||||
const ffmpegOutputPath = outputPathForBaseName('heimgeist-ffmpeg')
|
||||
const ffprobeOutputPath = outputPathForBaseName('heimgeist-ffprobe')
|
||||
|
||||
function resolveTargetTriple() {
|
||||
const output = execFileSync('rustc', ['-vV'], { encoding: 'utf8' })
|
||||
const match = output.match(/^host:\s+(\S+)/m)
|
||||
if (!match) {
|
||||
throw new Error('Could not determine Rust target triple from rustc -vV output.')
|
||||
}
|
||||
return match[1]
|
||||
}
|
||||
|
||||
function run(command, args, options = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: projectRoot,
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
...options,
|
||||
})
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${command} ${args.join(' ')} failed with exit code ${result.status}`)
|
||||
}
|
||||
}
|
||||
|
||||
function outputPathForBaseName(outputBaseName) {
|
||||
return path.join(binariesDir, `${outputBaseName}-${targetTriple}${executableExtension}`)
|
||||
}
|
||||
|
||||
function ensurePython() {
|
||||
if (!fs.existsSync(pythonBin)) {
|
||||
throw new Error(`Missing backend Python virtualenv at ${pythonBin}. Run ./run.sh or create backend/.venv first.`)
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePyInstaller() {
|
||||
const result = spawnSync(pythonBin, ['-c', 'import PyInstaller'], {
|
||||
cwd: projectRoot,
|
||||
stdio: 'ignore',
|
||||
})
|
||||
if (result.status === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
console.log('Installing PyInstaller into backend/.venv for sidecar packaging.')
|
||||
run(pythonBin, ['-m', 'pip', 'install', '--upgrade', 'pyinstaller'])
|
||||
}
|
||||
|
||||
function copyExecutable(sourcePath, outputBaseName) {
|
||||
if (!sourcePath || !fs.existsSync(sourcePath)) {
|
||||
return null
|
||||
}
|
||||
fs.mkdirSync(binariesDir, { recursive: true })
|
||||
const outputPath = outputPathForBaseName(outputBaseName)
|
||||
fs.copyFileSync(sourcePath, outputPath)
|
||||
fs.chmodSync(outputPath, 0o755)
|
||||
return outputPath
|
||||
}
|
||||
|
||||
function copyRequiredFfmpeg() {
|
||||
const ffmpegPath = require('ffmpeg-static')
|
||||
const outputPath = copyExecutable(ffmpegPath, 'heimgeist-ffmpeg')
|
||||
if (!outputPath) {
|
||||
throw new Error('Could not bundle ffmpeg-static: package did not provide a binary path.')
|
||||
}
|
||||
console.log(`Bundled ffmpeg helper: ${outputPath}`)
|
||||
}
|
||||
|
||||
function copyRequiredFfprobe() {
|
||||
const ffprobeStatic = require('ffprobe-static')
|
||||
const ffprobePath = ffprobeStatic && ffprobeStatic.path
|
||||
if (!ffprobePath || !fs.existsSync(ffprobePath)) {
|
||||
throw new Error('Could not bundle ffprobe-static: package did not provide a binary path.')
|
||||
}
|
||||
|
||||
const probe = spawnSync(ffprobePath, ['-version'], {
|
||||
encoding: 'utf8',
|
||||
timeout: 20000,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
if (probe.status !== 0) {
|
||||
throw new Error(
|
||||
`Could not bundle ffprobe-static: ${ffprobePath} did not run successfully on this machine.`,
|
||||
)
|
||||
}
|
||||
|
||||
const outputPath = copyExecutable(ffprobePath, 'heimgeist-ffprobe')
|
||||
console.log(`Bundled ffprobe helper: ${outputPath}`)
|
||||
}
|
||||
|
||||
function writeBinariesIgnore() {
|
||||
fs.mkdirSync(binariesDir, { recursive: true })
|
||||
const ignorePath = path.join(binariesDir, '.gitignore')
|
||||
if (!fs.existsSync(ignorePath)) {
|
||||
fs.writeFileSync(ignorePath, '*\n!.gitignore\n', 'utf8')
|
||||
}
|
||||
}
|
||||
|
||||
function buildBackendSidecar() {
|
||||
const pyinstallerRoot = path.join('/tmp', `heimgeist-pyinstaller-${targetTriple}`)
|
||||
const distPath = path.join(pyinstallerRoot, 'dist')
|
||||
const workPath = path.join(pyinstallerRoot, 'build')
|
||||
const specPath = path.join(pyinstallerRoot, 'spec')
|
||||
|
||||
fs.rmSync(pyinstallerRoot, { recursive: true, force: true })
|
||||
fs.rmSync(backendOutputPath, { force: true })
|
||||
fs.rmSync(ffmpegOutputPath, { force: true })
|
||||
fs.rmSync(ffprobeOutputPath, { force: true })
|
||||
fs.mkdirSync(distPath, { recursive: true })
|
||||
fs.mkdirSync(workPath, { recursive: true })
|
||||
fs.mkdirSync(specPath, { recursive: true })
|
||||
|
||||
run(pythonBin, [
|
||||
'-m',
|
||||
'PyInstaller',
|
||||
'--noconfirm',
|
||||
'--clean',
|
||||
'--onefile',
|
||||
'--name',
|
||||
'heimgeist-backend',
|
||||
'--distpath',
|
||||
distPath,
|
||||
'--workpath',
|
||||
workPath,
|
||||
'--specpath',
|
||||
specPath,
|
||||
'--paths',
|
||||
projectRoot,
|
||||
'--collect-submodules',
|
||||
'backend.rag',
|
||||
'--collect-submodules',
|
||||
'whisper',
|
||||
'--collect-data',
|
||||
'whisper',
|
||||
'--hidden-import',
|
||||
'backend.main',
|
||||
'--hidden-import',
|
||||
'backend.sidecar_main',
|
||||
'--hidden-import',
|
||||
'uvicorn.logging',
|
||||
'--hidden-import',
|
||||
'uvicorn.loops.auto',
|
||||
'--hidden-import',
|
||||
'uvicorn.protocols.http.auto',
|
||||
'--hidden-import',
|
||||
'uvicorn.protocols.websockets.auto',
|
||||
'--hidden-import',
|
||||
'uvicorn.lifespan.on',
|
||||
path.join(projectRoot, 'backend', 'sidecar_main.py'),
|
||||
])
|
||||
|
||||
const builtBinary = path.join(distPath, `heimgeist-backend${executableExtension}`)
|
||||
if (!fs.existsSync(builtBinary)) {
|
||||
throw new Error(`PyInstaller did not produce expected binary at ${builtBinary}`)
|
||||
}
|
||||
|
||||
fs.mkdirSync(binariesDir, { recursive: true })
|
||||
fs.copyFileSync(builtBinary, backendOutputPath)
|
||||
fs.chmodSync(backendOutputPath, 0o755)
|
||||
console.log(`Built backend sidecar: ${backendOutputPath}`)
|
||||
}
|
||||
|
||||
ensurePython()
|
||||
ensurePyInstaller()
|
||||
writeBinariesIgnore()
|
||||
buildBackendSidecar()
|
||||
copyRequiredFfmpeg()
|
||||
copyRequiredFfprobe()
|
||||
44
scripts/run-backend.cjs
Normal file
44
scripts/run-backend.cjs
Normal file
@@ -0,0 +1,44 @@
|
||||
const { spawn } = require('child_process')
|
||||
const path = require('path')
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..')
|
||||
const pythonBin = path.join(projectRoot, 'backend', '.venv', 'bin', 'python')
|
||||
|
||||
const env = { ...process.env }
|
||||
|
||||
try {
|
||||
const ffmpegPath = require('ffmpeg-static')
|
||||
if (ffmpegPath) {
|
||||
env.HEIMGEIST_FFMPEG_PATH = ffmpegPath
|
||||
}
|
||||
} catch (_error) {
|
||||
// Fall back to system PATH if the static binary package is unavailable.
|
||||
}
|
||||
|
||||
try {
|
||||
const ffprobeStatic = require('ffprobe-static')
|
||||
const ffprobePath = ffprobeStatic && ffprobeStatic.path
|
||||
if (ffprobePath) {
|
||||
env.HEIMGEIST_FFPROBE_PATH = ffprobePath
|
||||
}
|
||||
} catch (_error) {
|
||||
// Fall back to system PATH if the static binary package is unavailable.
|
||||
}
|
||||
|
||||
const child = spawn(
|
||||
pythonBin,
|
||||
['-m', 'uvicorn', 'backend.main:app', '--host', '127.0.0.1', '--port', '8000', '--reload'],
|
||||
{
|
||||
cwd: projectRoot,
|
||||
env,
|
||||
stdio: 'inherit',
|
||||
}
|
||||
)
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal)
|
||||
return
|
||||
}
|
||||
process.exit(code ?? 0)
|
||||
})
|
||||
184
scripts/run-tauri-dev.cjs
Normal file
184
scripts/run-tauri-dev.cjs
Normal file
@@ -0,0 +1,184 @@
|
||||
const { spawn, spawnSync } = require('child_process')
|
||||
const fs = require('fs')
|
||||
const http = require('http')
|
||||
const path = require('path')
|
||||
const waitOn = require('wait-on')
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..')
|
||||
const backendHealthUrl = 'http://127.0.0.1:8000/health'
|
||||
const backendHealthResource = `http-get://${backendHealthUrl.replace(/^https?:\/\//, '')}`
|
||||
const tauriCliPackage = '@tauri-apps/cli@2.11.0'
|
||||
const localTauriBin = path.join(
|
||||
projectRoot,
|
||||
'node_modules',
|
||||
'.bin',
|
||||
process.platform === 'win32' ? 'tauri.cmd' : 'tauri',
|
||||
)
|
||||
|
||||
let backendProcess = null
|
||||
let tauriProcess = null
|
||||
let shuttingDown = false
|
||||
|
||||
function isBackendHealthy(timeoutMs = 1500) {
|
||||
return new Promise((resolve) => {
|
||||
const request = http.get(backendHealthUrl, { timeout: timeoutMs }, (response) => {
|
||||
response.resume()
|
||||
resolve(response.statusCode >= 200 && response.statusCode < 300)
|
||||
})
|
||||
|
||||
request.on('timeout', () => {
|
||||
request.destroy()
|
||||
resolve(false)
|
||||
})
|
||||
request.on('error', () => resolve(false))
|
||||
})
|
||||
}
|
||||
|
||||
function spawnBackend() {
|
||||
backendProcess = spawn(process.execPath, [path.join('scripts', 'run-backend.cjs')], {
|
||||
cwd: projectRoot,
|
||||
env: process.env,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
|
||||
backendProcess.on('exit', (code, signal) => {
|
||||
if (!shuttingDown && code !== 0) {
|
||||
console.error(`Tauri dev wrapper: backend exited before shutdown (${signal || code}).`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function resolveTauriCommand() {
|
||||
if (fs.existsSync(localTauriBin)) {
|
||||
return { command: localTauriBin, args: ['dev'] }
|
||||
}
|
||||
|
||||
return {
|
||||
command: process.platform === 'win32' ? 'npm.cmd' : 'npm',
|
||||
args: ['exec', '--yes', '--package', tauriCliPackage, '--', 'tauri', 'dev'],
|
||||
}
|
||||
}
|
||||
|
||||
function getChildPids(pid) {
|
||||
if (process.platform === 'win32') {
|
||||
return []
|
||||
}
|
||||
|
||||
const result = spawnSync('pgrep', ['-P', String(pid)], {
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
if (result.status !== 0 || !result.stdout.trim()) {
|
||||
return []
|
||||
}
|
||||
|
||||
return result.stdout.trim().split(/\s+/).map(Number).filter(Number.isFinite)
|
||||
}
|
||||
|
||||
function stopPidTree(pid, signal = 'SIGTERM') {
|
||||
for (const childPid of getChildPids(pid)) {
|
||||
stopPidTree(childPid, signal)
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(pid, signal)
|
||||
} catch (_error) {
|
||||
// The process may already have exited while walking the tree.
|
||||
}
|
||||
}
|
||||
|
||||
function stopChild(child, signal = 'SIGTERM') {
|
||||
if (!child || child.killed || !child.pid) {
|
||||
return
|
||||
}
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
|
||||
stdio: 'ignore',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
stopPidTree(child.pid, signal)
|
||||
}
|
||||
|
||||
function stopSpawnedBackend(signal = 'SIGTERM') {
|
||||
if (backendProcess) {
|
||||
stopChild(backendProcess, signal)
|
||||
}
|
||||
}
|
||||
|
||||
function handleShutdown(signal) {
|
||||
if (shuttingDown) {
|
||||
return
|
||||
}
|
||||
|
||||
shuttingDown = true
|
||||
stopChild(tauriProcess, signal)
|
||||
stopSpawnedBackend(signal)
|
||||
setTimeout(() => process.exit(0), 750).unref()
|
||||
}
|
||||
|
||||
async function waitForBackend() {
|
||||
await waitOn({
|
||||
resources: [backendHealthResource],
|
||||
proxy: false,
|
||||
timeout: 120000,
|
||||
})
|
||||
}
|
||||
|
||||
async function launchTauri() {
|
||||
const { command, args } = resolveTauriCommand()
|
||||
const env = {
|
||||
...process.env,
|
||||
HEIMGEIST_DEV_WRAPPER: '1',
|
||||
}
|
||||
|
||||
tauriProcess = spawn(command, args, {
|
||||
cwd: projectRoot,
|
||||
env,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
|
||||
tauriProcess.on('exit', (code, signal) => {
|
||||
const wasShuttingDown = shuttingDown
|
||||
shuttingDown = true
|
||||
stopSpawnedBackend()
|
||||
|
||||
if (wasShuttingDown) {
|
||||
process.exit(0)
|
||||
return
|
||||
}
|
||||
|
||||
if (signal) {
|
||||
process.exit(signal === 'SIGINT' || signal === 'SIGTERM' ? 0 : 1)
|
||||
return
|
||||
}
|
||||
|
||||
process.exit(code ?? 0)
|
||||
})
|
||||
}
|
||||
|
||||
async function main() {
|
||||
process.on('SIGINT', () => handleShutdown('SIGINT'))
|
||||
process.on('SIGTERM', () => handleShutdown('SIGTERM'))
|
||||
|
||||
if (await isBackendHealthy()) {
|
||||
console.log('Tauri dev wrapper: FastAPI backend already healthy on 127.0.0.1:8000; reusing it.')
|
||||
} else {
|
||||
console.log('Tauri dev wrapper: starting FastAPI backend from scripts/run-backend.cjs.')
|
||||
spawnBackend()
|
||||
await waitForBackend()
|
||||
}
|
||||
|
||||
console.log('Tauri dev wrapper: backend ready, launching Tauri on the Tauri renderer port.')
|
||||
await launchTauri()
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
shuttingDown = true
|
||||
stopChild(tauriProcess)
|
||||
stopSpawnedBackend()
|
||||
console.error('Failed to launch Tauri dev wrapper:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
18
src-tauri/Cargo.toml
Normal file
18
src-tauri/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "heimgeist-tauri"
|
||||
version = "0.1.0"
|
||||
description = "Tauri migration spike for Heimgeist"
|
||||
authors = ["Heimgeist"]
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-shell = "2"
|
||||
2
src-tauri/binaries/.gitignore
vendored
Normal file
2
src-tauri/binaries/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
3
src-tauri/build.rs
Normal file
3
src-tauri/build.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build();
|
||||
}
|
||||
12
src-tauri/capabilities/default.json
Normal file
12
src-tauri/capabilities/default.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"identifier": "default",
|
||||
"description": "Default capability for the Heimgeist Tauri migration spike.",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"dialog:allow-open",
|
||||
"opener:allow-default-urls",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-open-url"
|
||||
]
|
||||
}
|
||||
BIN
src-tauri/icons/icon.png
Normal file
BIN
src-tauri/icons/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 757 B |
866
src-tauri/src/main.rs
Normal file
866
src-tauri/src/main.rs
Normal file
@@ -0,0 +1,866 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
net::{SocketAddr, TcpStream},
|
||||
path::{Path, PathBuf},
|
||||
process::Command as StdCommand,
|
||||
sync::Mutex,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
use tauri::{AppHandle, Emitter, Manager, State, WindowEvent};
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
use tauri_plugin_shell::{
|
||||
process::{CommandChild, CommandEvent},
|
||||
ShellExt,
|
||||
};
|
||||
|
||||
const DEFAULT_BACKEND_API_URL: &str = "http://127.0.0.1:8000";
|
||||
const BACKEND_HOST: &str = "127.0.0.1";
|
||||
const BACKEND_PORT: u16 = 8000;
|
||||
const BACKEND_SIDECAR_NAME: &str = "heimgeist-backend";
|
||||
const BACKEND_STARTUP_TIMEOUT: Duration = Duration::from_secs(45);
|
||||
const DEFAULT_OLLAMA_API_URL: &str = "http://127.0.0.1:11434";
|
||||
const DEFAULT_EMBED_MODEL: &str = "nomic-embed-text:latest";
|
||||
const DEFAULT_ENRICHMENT_MODEL: &str = "qwen3:4b";
|
||||
const DEFAULT_TRANSCRIPTION_MODEL: &str = "base";
|
||||
const BGE_EMBED_MODEL: &str = "bge-m3:latest";
|
||||
const DEFAULT_UI_SCALE: f64 = 1.0;
|
||||
const MIN_UI_SCALE: f64 = 0.7;
|
||||
const MAX_UI_SCALE: f64 = 1.3;
|
||||
const SETTINGS_FILE_NAME: &str = "settings.json";
|
||||
const CHANGELOG_PAGE_SIZE: u64 = 50;
|
||||
|
||||
type SettingsMap = Map<String, Value>;
|
||||
|
||||
struct SettingsStore {
|
||||
path: PathBuf,
|
||||
settings: Mutex<SettingsMap>,
|
||||
}
|
||||
|
||||
struct BackendSidecar {
|
||||
child: Mutex<Option<CommandChild>>,
|
||||
}
|
||||
|
||||
impl BackendSidecar {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
child: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn running(child: CommandChild) -> Self {
|
||||
Self {
|
||||
child: Mutex::new(Some(child)),
|
||||
}
|
||||
}
|
||||
|
||||
fn shutdown(&self) {
|
||||
let child = match self.child.lock() {
|
||||
Ok(mut child) => child.take(),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
if let Some(child) = child {
|
||||
let pid = child.pid();
|
||||
terminate_process_tree(pid);
|
||||
if let Err(error) = child.kill() {
|
||||
eprintln!("Failed to stop Heimgeist backend sidecar pid {pid}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BackendSidecar {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn terminate_process_tree(pid: u32) {
|
||||
let pid = pid.to_string();
|
||||
let _ = StdCommand::new("pkill")
|
||||
.args(["-TERM", "-P", &pid])
|
||||
.status();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn terminate_process_tree(pid: u32) {
|
||||
let _ = StdCommand::new("taskkill")
|
||||
.args(["/PID", &pid.to_string(), "/T", "/F"])
|
||||
.status();
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn terminate_process_tree(_pid: u32) {}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PickPathsOptions {
|
||||
title: Option<String>,
|
||||
filters: Option<Vec<DialogFilter>>,
|
||||
multiple: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct DialogFilter {
|
||||
name: Option<String>,
|
||||
extensions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
fn default_settings() -> SettingsMap {
|
||||
let mut settings = SettingsMap::new();
|
||||
settings.insert("backendApiUrl".into(), json!(DEFAULT_BACKEND_API_URL));
|
||||
settings.insert("ollamaApiUrl".into(), json!(DEFAULT_OLLAMA_API_URL));
|
||||
settings.insert("chatModel".into(), json!("llama3"));
|
||||
settings.insert("visionModel".into(), json!(""));
|
||||
settings.insert("embedModel".into(), json!(DEFAULT_EMBED_MODEL));
|
||||
settings.insert("rerankModel".into(), json!(DEFAULT_EMBED_MODEL));
|
||||
settings.insert("enrichmentModel".into(), json!(DEFAULT_ENRICHMENT_MODEL));
|
||||
settings.insert(
|
||||
"transcriptionModel".into(),
|
||||
json!(DEFAULT_TRANSCRIPTION_MODEL),
|
||||
);
|
||||
settings.insert("workflowSelectionMode".into(), json!("auto"));
|
||||
settings.insert("autoDeepEnrichment".into(), json!(true));
|
||||
settings.insert("colorScheme".into(), json!("Default"));
|
||||
settings.insert("uiScale".into(), json!(DEFAULT_UI_SCALE));
|
||||
settings.insert("openDevToolsOnStartup".into(), json!(false));
|
||||
settings.insert("audioInputEnabled".into(), json!(true));
|
||||
settings.insert("audioInputDeviceId".into(), json!(""));
|
||||
settings.insert("audioInputLanguage".into(), json!(""));
|
||||
settings
|
||||
}
|
||||
|
||||
fn value_to_trimmed_string(value: Option<&Value>) -> String {
|
||||
match value {
|
||||
Some(Value::String(text)) => text.trim().to_string(),
|
||||
Some(Value::Number(number)) => number.to_string(),
|
||||
Some(Value::Bool(value)) => value.to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn value_to_number(value: Option<&Value>) -> Option<f64> {
|
||||
match value {
|
||||
Some(Value::Number(number)) => number.as_f64(),
|
||||
Some(Value::String(text)) => text.trim().parse::<f64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_ui_scale(value: Option<&Value>) -> f64 {
|
||||
let scale = value_to_number(value).unwrap_or(DEFAULT_UI_SCALE);
|
||||
let clamped = scale.clamp(MIN_UI_SCALE, MAX_UI_SCALE);
|
||||
(clamped * 100.0).round() / 100.0
|
||||
}
|
||||
|
||||
fn normalize_boolean_setting(value: Option<&Value>) -> bool {
|
||||
match value {
|
||||
Some(Value::String(text)) => match text.trim().to_lowercase().as_str() {
|
||||
"true" | "1" | "yes" | "on" => true,
|
||||
"false" | "0" | "no" | "off" | "" => false,
|
||||
_ => false,
|
||||
},
|
||||
Some(Value::Bool(value)) => *value,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_model_name(value: Option<&Value>, fallback: &str) -> String {
|
||||
let trimmed = value_to_trimmed_string(value);
|
||||
if trimmed.is_empty() {
|
||||
fallback.to_string()
|
||||
} else {
|
||||
trimmed
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_embed_model(value: Option<&Value>) -> String {
|
||||
let trimmed = value_to_trimmed_string(value);
|
||||
if trimmed.is_empty() {
|
||||
return DEFAULT_EMBED_MODEL.to_string();
|
||||
}
|
||||
|
||||
match trimmed.to_lowercase().as_str() {
|
||||
"bge" | "bge-m3" | BGE_EMBED_MODEL => BGE_EMBED_MODEL.to_string(),
|
||||
"nomic" | "nomic-embed-text" | DEFAULT_EMBED_MODEL => DEFAULT_EMBED_MODEL.to_string(),
|
||||
_ => trimmed,
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_like_ollama_url(value: &str) -> bool {
|
||||
tauri::Url::parse(value)
|
||||
.map(|parsed| {
|
||||
parsed.port() == Some(11434)
|
||||
|| parsed
|
||||
.path()
|
||||
.trim_end_matches('/')
|
||||
.eq_ignore_ascii_case("/api")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn migrate_settings(source: Option<SettingsMap>) -> (SettingsMap, bool) {
|
||||
let source = source.unwrap_or_default();
|
||||
let mut next = default_settings();
|
||||
let mut migrated = false;
|
||||
|
||||
for (key, value) in source.iter() {
|
||||
next.insert(key.clone(), value.clone());
|
||||
}
|
||||
|
||||
if !source.contains_key("backendApiUrl") {
|
||||
if let Some(Value::String(ollama_api_url)) = source.get("ollamaApiUrl") {
|
||||
if looks_like_ollama_url(ollama_api_url) {
|
||||
next.insert("backendApiUrl".into(), json!(DEFAULT_BACKEND_API_URL));
|
||||
next.insert("ollamaApiUrl".into(), json!(ollama_api_url.trim()));
|
||||
} else {
|
||||
next.insert("backendApiUrl".into(), json!(ollama_api_url.trim()));
|
||||
next.insert("ollamaApiUrl".into(), json!(DEFAULT_OLLAMA_API_URL));
|
||||
}
|
||||
migrated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !source.contains_key("openDevToolsOnStartup") {
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
if !source.contains_key("rerankModel") {
|
||||
let embed_model = next
|
||||
.get("embedModel")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!(DEFAULT_EMBED_MODEL));
|
||||
next.insert("rerankModel".into(), embed_model);
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
if !source.contains_key("visionModel") {
|
||||
let chat_model = value_to_trimmed_string(next.get("chatModel"));
|
||||
next.insert("visionModel".into(), json!(chat_model));
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
if !source.contains_key("enrichmentModel") {
|
||||
next.insert("enrichmentModel".into(), json!(DEFAULT_ENRICHMENT_MODEL));
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
if !source.contains_key("transcriptionModel") {
|
||||
next.insert(
|
||||
"transcriptionModel".into(),
|
||||
json!(DEFAULT_TRANSCRIPTION_MODEL),
|
||||
);
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
if !source.contains_key("autoDeepEnrichment") {
|
||||
next.insert("autoDeepEnrichment".into(), json!(true));
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
if !source.contains_key("workflowSelectionMode") {
|
||||
next.insert("workflowSelectionMode".into(), json!("auto"));
|
||||
migrated = true;
|
||||
}
|
||||
|
||||
normalize_settings(&mut next);
|
||||
(next, migrated)
|
||||
}
|
||||
|
||||
fn normalize_settings(settings: &mut SettingsMap) {
|
||||
let backend_api_url = value_to_trimmed_string(settings.get("backendApiUrl"));
|
||||
let ollama_api_url = value_to_trimmed_string(settings.get("ollamaApiUrl"));
|
||||
let chat_model = normalize_model_name(settings.get("chatModel"), "");
|
||||
let vision_model = normalize_model_name(settings.get("visionModel"), "");
|
||||
let embed_model = normalize_embed_model(settings.get("embedModel"));
|
||||
let rerank_model = normalize_embed_model(settings.get("rerankModel"));
|
||||
let enrichment_model =
|
||||
normalize_model_name(settings.get("enrichmentModel"), DEFAULT_ENRICHMENT_MODEL);
|
||||
let transcription_model = normalize_model_name(
|
||||
settings.get("transcriptionModel"),
|
||||
DEFAULT_TRANSCRIPTION_MODEL,
|
||||
);
|
||||
let workflow_selection_mode =
|
||||
if value_to_trimmed_string(settings.get("workflowSelectionMode")).eq_ignore_ascii_case("manual") {
|
||||
"manual"
|
||||
} else {
|
||||
"auto"
|
||||
};
|
||||
let auto_deep_enrichment = normalize_boolean_setting(settings.get("autoDeepEnrichment"));
|
||||
let ui_scale = normalize_ui_scale(settings.get("uiScale"));
|
||||
let open_devtools_on_startup = normalize_boolean_setting(settings.get("openDevToolsOnStartup"));
|
||||
let audio_input_enabled = normalize_boolean_setting(settings.get("audioInputEnabled"));
|
||||
let audio_input_device_id = value_to_trimmed_string(settings.get("audioInputDeviceId"));
|
||||
let audio_input_language =
|
||||
value_to_trimmed_string(settings.get("audioInputLanguage")).to_lowercase();
|
||||
|
||||
settings.insert("backendApiUrl".into(), json!(backend_api_url));
|
||||
settings.insert("ollamaApiUrl".into(), json!(ollama_api_url));
|
||||
settings.insert("chatModel".into(), json!(chat_model));
|
||||
settings.insert("visionModel".into(), json!(vision_model));
|
||||
settings.insert("embedModel".into(), json!(embed_model));
|
||||
settings.insert("rerankModel".into(), json!(rerank_model));
|
||||
settings.insert("enrichmentModel".into(), json!(enrichment_model));
|
||||
settings.insert("transcriptionModel".into(), json!(transcription_model));
|
||||
settings.insert("workflowSelectionMode".into(), json!(workflow_selection_mode));
|
||||
settings.insert("autoDeepEnrichment".into(), json!(auto_deep_enrichment));
|
||||
settings.insert("uiScale".into(), json!(ui_scale));
|
||||
settings.insert(
|
||||
"openDevToolsOnStartup".into(),
|
||||
json!(open_devtools_on_startup),
|
||||
);
|
||||
settings.insert("audioInputEnabled".into(), json!(audio_input_enabled));
|
||||
settings.insert("audioInputDeviceId".into(), json!(audio_input_device_id));
|
||||
settings.insert("audioInputLanguage".into(), json!(audio_input_language));
|
||||
}
|
||||
|
||||
fn explicit_settings_file_path() -> Option<PathBuf> {
|
||||
if let Ok(path) = std::env::var("HEIMGEIST_SETTINGS_FILE") {
|
||||
let trimmed = path.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(PathBuf::from(trimmed));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn tauri_settings_file_path(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
app.path()
|
||||
.app_config_dir()
|
||||
.map(|dir| dir.join(SETTINGS_FILE_NAME))
|
||||
.map_err(|error| format!("Could not resolve Tauri settings path: {error}"))
|
||||
}
|
||||
|
||||
fn settings_file_path(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
explicit_settings_file_path()
|
||||
.map(Ok)
|
||||
.unwrap_or_else(|| tauri_settings_file_path(app))
|
||||
}
|
||||
|
||||
fn paths_equal(first: &Path, second: &Path) -> bool {
|
||||
match (first.canonicalize(), second.canonicalize()) {
|
||||
(Ok(first), Ok(second)) => first == second,
|
||||
_ => first == second,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_unique_candidate(candidates: &mut Vec<PathBuf>, candidate: PathBuf, tauri_path: &Path) {
|
||||
if paths_equal(&candidate, tauri_path)
|
||||
|| candidates
|
||||
.iter()
|
||||
.any(|existing| paths_equal(existing, &candidate))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
candidates.push(candidate);
|
||||
}
|
||||
|
||||
fn legacy_settings_candidates(app: &AppHandle, tauri_path: &Path) -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
|
||||
if let Ok(config_dir) = app.path().config_dir() {
|
||||
let product_name = app.config().product_name.as_deref().unwrap_or("Heimgeist");
|
||||
|
||||
for app_dir in [product_name, "Heimgeist", "heimgeist"] {
|
||||
push_unique_candidate(
|
||||
&mut candidates,
|
||||
config_dir.join(app_dir).join(SETTINGS_FILE_NAME),
|
||||
tauri_path,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
candidates
|
||||
}
|
||||
|
||||
fn import_legacy_settings_if_available(app: &AppHandle, tauri_path: &Path) -> Option<SettingsMap> {
|
||||
for candidate in legacy_settings_candidates(app, tauri_path) {
|
||||
match read_settings_file(&candidate) {
|
||||
Ok(Some(settings)) => {
|
||||
println!(
|
||||
"Imported legacy Heimgeist settings for first Tauri run from {}",
|
||||
candidate.display()
|
||||
);
|
||||
return Some(settings);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"Skipping legacy settings import from {}: {error}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn read_settings_file(path: &PathBuf) -> Result<Option<SettingsMap>, String> {
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let data = fs::read_to_string(path)
|
||||
.map_err(|error| format!("Could not read settings from {}: {error}", path.display()))?;
|
||||
let value: Value = serde_json::from_str(&data)
|
||||
.map_err(|error| format!("Could not parse settings from {}: {error}", path.display()))?;
|
||||
|
||||
match value {
|
||||
Value::Object(settings) => Ok(Some(settings)),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_settings_file(path: &PathBuf, settings: &SettingsMap) -> Result<(), String> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|error| {
|
||||
format!(
|
||||
"Could not create settings directory {}: {error}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
|
||||
let data = serde_json::to_string_pretty(settings)
|
||||
.map_err(|error| format!("Could not serialize settings: {error}"))?;
|
||||
fs::write(path, format!("{data}\n"))
|
||||
.map_err(|error| format!("Could not write settings to {}: {error}", path.display()))
|
||||
}
|
||||
|
||||
enum BackendHealth {
|
||||
Healthy,
|
||||
Unavailable,
|
||||
Incompatible(String),
|
||||
}
|
||||
|
||||
fn check_backend_health() -> BackendHealth {
|
||||
let address = SocketAddr::from(([127, 0, 0, 1], BACKEND_PORT));
|
||||
let mut stream = match TcpStream::connect_timeout(&address, Duration::from_millis(500)) {
|
||||
Ok(stream) => stream,
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
return BackendHealth::Unavailable;
|
||||
}
|
||||
Err(error) => {
|
||||
return BackendHealth::Incompatible(format!(
|
||||
"Could not connect to backend health port {BACKEND_PORT}: {error}"
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
|
||||
if let Err(error) = stream.write_all(
|
||||
format!("GET /health HTTP/1.1\r\nHost: {BACKEND_HOST}\r\nConnection: close\r\n\r\n")
|
||||
.as_bytes(),
|
||||
) {
|
||||
return BackendHealth::Incompatible(format!(
|
||||
"Port {BACKEND_PORT} is occupied but did not accept a health request: {error}"
|
||||
));
|
||||
}
|
||||
|
||||
let mut response = String::new();
|
||||
if let Err(error) = stream.read_to_string(&mut response) {
|
||||
return BackendHealth::Incompatible(format!(
|
||||
"Port {BACKEND_PORT} is occupied but did not return a readable health response: {error}"
|
||||
));
|
||||
}
|
||||
|
||||
if response.contains("200 OK") && response.contains("\"ok\"") {
|
||||
BackendHealth::Healthy
|
||||
} else {
|
||||
let preview = response.lines().next().unwrap_or("empty response");
|
||||
BackendHealth::Incompatible(format!(
|
||||
"Port {BACKEND_PORT} is occupied but /health did not return Heimgeist health OK ({preview})."
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_backend_health(timeout: Duration) -> Result<(), String> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
match check_backend_health() {
|
||||
BackendHealth::Healthy => return Ok(()),
|
||||
BackendHealth::Unavailable => {
|
||||
if Instant::now() >= deadline {
|
||||
return Err(format!(
|
||||
"Timed out waiting for Heimgeist backend /health on {BACKEND_HOST}:{BACKEND_PORT}."
|
||||
));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
BackendHealth::Incompatible(detail) => return Err(detail),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn should_start_backend_sidecar() -> bool {
|
||||
!cfg!(debug_assertions)
|
||||
|| std::env::var("HEIMGEIST_USE_BACKEND_SIDECAR")
|
||||
.map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn bundled_executable_path(name: &str) -> Option<PathBuf> {
|
||||
let exe_path = std::env::current_exe().ok()?;
|
||||
let exe_dir = exe_path.parent()?;
|
||||
#[cfg(not(windows))]
|
||||
let path = exe_dir.join(name);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut path = exe_dir.join(name);
|
||||
path.set_extension("exe");
|
||||
path.exists().then_some(path)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
path.exists().then_some(path)
|
||||
}
|
||||
}
|
||||
|
||||
fn app_managed_data_dir(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
let data_dir = app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.map_err(|error| format!("Could not resolve app data directory: {error}"))?;
|
||||
fs::create_dir_all(&data_dir).map_err(|error| {
|
||||
format!(
|
||||
"Could not create app data directory {}: {error}",
|
||||
data_dir.display()
|
||||
)
|
||||
})?;
|
||||
Ok(data_dir)
|
||||
}
|
||||
|
||||
fn start_backend_sidecar(app: &AppHandle, settings_path: &Path) -> Result<BackendSidecar, String> {
|
||||
match check_backend_health() {
|
||||
BackendHealth::Healthy => {
|
||||
println!("Reusing healthy Heimgeist backend on {BACKEND_HOST}:{BACKEND_PORT}.");
|
||||
return Ok(BackendSidecar::empty());
|
||||
}
|
||||
BackendHealth::Unavailable => {}
|
||||
BackendHealth::Incompatible(detail) => return Err(detail),
|
||||
}
|
||||
|
||||
if !should_start_backend_sidecar() {
|
||||
println!(
|
||||
"Heimgeist backend is not running; dev shell expects an external backend wrapper."
|
||||
);
|
||||
return Ok(BackendSidecar::empty());
|
||||
}
|
||||
|
||||
let data_dir = app_managed_data_dir(app)?;
|
||||
let mut command = app
|
||||
.shell()
|
||||
.sidecar(BACKEND_SIDECAR_NAME)
|
||||
.map_err(|error| format!("Could not resolve bundled backend sidecar: {error}"))?
|
||||
.env("HEIMGEIST_DATA_DIR", data_dir.as_os_str())
|
||||
.env("HEIMGEIST_SETTINGS_FILE", settings_path.as_os_str())
|
||||
.env("HEIMGEIST_BACKEND_HOST", BACKEND_HOST)
|
||||
.env("HEIMGEIST_BACKEND_PORT", BACKEND_PORT.to_string());
|
||||
|
||||
if let Some(ffmpeg_path) = bundled_executable_path("heimgeist-ffmpeg") {
|
||||
command = command.env("HEIMGEIST_FFMPEG_PATH", ffmpeg_path.as_os_str());
|
||||
}
|
||||
if let Some(ffprobe_path) = bundled_executable_path("heimgeist-ffprobe") {
|
||||
command = command.env("HEIMGEIST_FFPROBE_PATH", ffprobe_path.as_os_str());
|
||||
}
|
||||
|
||||
let (mut events, child) = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("Failed to start bundled backend sidecar: {error}"))?;
|
||||
let pid = child.pid();
|
||||
println!("Started bundled Heimgeist backend sidecar with pid {pid}.");
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = events.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(bytes) => {
|
||||
let line = String::from_utf8_lossy(&bytes);
|
||||
println!("[backend] {}", line.trim_end());
|
||||
}
|
||||
CommandEvent::Stderr(bytes) => {
|
||||
let line = String::from_utf8_lossy(&bytes);
|
||||
eprintln!("[backend] {}", line.trim_end());
|
||||
}
|
||||
CommandEvent::Error(error) => {
|
||||
eprintln!("[backend] {error}");
|
||||
}
|
||||
CommandEvent::Terminated(status) => {
|
||||
eprintln!(
|
||||
"[backend] sidecar terminated code={:?} signal={:?}",
|
||||
status.code, status.signal
|
||||
);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let sidecar = BackendSidecar::running(child);
|
||||
wait_for_backend_health(BACKEND_STARTUP_TIMEOUT)?;
|
||||
Ok(sidecar)
|
||||
}
|
||||
|
||||
fn load_settings_store(app: &AppHandle) -> Result<SettingsStore, String> {
|
||||
let path = settings_file_path(app)?;
|
||||
let raw_settings = read_settings_file(&path)?;
|
||||
let (settings, should_write) = match raw_settings {
|
||||
Some(raw_settings) => {
|
||||
let (settings, migrated) = migrate_settings(Some(raw_settings));
|
||||
(settings, migrated)
|
||||
}
|
||||
None => {
|
||||
let imported_settings = if explicit_settings_file_path().is_none() {
|
||||
import_legacy_settings_if_available(app, &path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (settings, _migrated) = migrate_settings(imported_settings);
|
||||
(settings, true)
|
||||
}
|
||||
};
|
||||
|
||||
if should_write {
|
||||
write_settings_file(&path, &settings)?;
|
||||
}
|
||||
|
||||
Ok(SettingsStore {
|
||||
path,
|
||||
settings: Mutex::new(settings),
|
||||
})
|
||||
}
|
||||
|
||||
fn unavailable_update_status(message: &str) -> Value {
|
||||
json!({
|
||||
"state": "unavailable",
|
||||
"message": message,
|
||||
"checkedAt": null,
|
||||
"localCommit": null,
|
||||
"remoteCommit": null,
|
||||
"branch": null,
|
||||
"restartScheduled": false
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_changelog_page(page: Option<u64>) -> u64 {
|
||||
page.filter(|value| *value > 0).unwrap_or(1)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_settings(store: State<'_, SettingsStore>) -> Result<Value, String> {
|
||||
let settings = store
|
||||
.settings
|
||||
.lock()
|
||||
.map_err(|_| "Settings store is unavailable.".to_string())?;
|
||||
Ok(Value::Object(settings.clone()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn set_setting(key: String, value: Value, store: State<'_, SettingsStore>) -> Result<bool, String> {
|
||||
let mut settings = store
|
||||
.settings
|
||||
.lock()
|
||||
.map_err(|_| "Settings store is unavailable.".to_string())?;
|
||||
settings.insert(key, value);
|
||||
normalize_settings(&mut settings);
|
||||
write_settings_file(&store.path, &settings)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn update_settings(settings: SettingsMap, store: State<'_, SettingsStore>) -> Result<bool, String> {
|
||||
let mut current_settings = store
|
||||
.settings
|
||||
.lock()
|
||||
.map_err(|_| "Settings store is unavailable.".to_string())?;
|
||||
current_settings.extend(settings);
|
||||
normalize_settings(&mut current_settings);
|
||||
write_settings_file(&store.path, ¤t_settings)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_update_status() -> Value {
|
||||
unavailable_update_status(
|
||||
"Tauri update checks are not implemented in this production release phase.",
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn check_for_updates() -> Value {
|
||||
unavailable_update_status(
|
||||
"Tauri update checks are not implemented in this production release phase.",
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_changelog_page(page: Option<u64>) -> Value {
|
||||
json!({
|
||||
"page": normalize_changelog_page(page),
|
||||
"pageSize": CHANGELOG_PAGE_SIZE,
|
||||
"hasMore": false,
|
||||
"entries": []
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pick_paths(
|
||||
app: AppHandle,
|
||||
options: Option<PickPathsOptions>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let options = options.unwrap_or(PickPathsOptions {
|
||||
title: None,
|
||||
filters: None,
|
||||
multiple: None,
|
||||
});
|
||||
let mut dialog = app.dialog().file();
|
||||
|
||||
if let Some(title) = options
|
||||
.title
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|title| !title.is_empty())
|
||||
{
|
||||
dialog = dialog.set_title(title);
|
||||
}
|
||||
|
||||
for filter in options.filters.unwrap_or_default() {
|
||||
let name = filter
|
||||
.name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or("Files")
|
||||
.to_string();
|
||||
let extensions: Vec<String> = filter
|
||||
.extensions
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|extension| extension.trim().trim_start_matches('.').to_string())
|
||||
.filter(|extension| !extension.is_empty())
|
||||
.collect();
|
||||
|
||||
if !extensions.is_empty() {
|
||||
let extension_refs: Vec<&str> = extensions.iter().map(String::as_str).collect();
|
||||
dialog = dialog.add_filter(name, &extension_refs);
|
||||
}
|
||||
}
|
||||
|
||||
let paths = if options.multiple.unwrap_or(true) {
|
||||
dialog.blocking_pick_files().unwrap_or_default()
|
||||
} else {
|
||||
dialog.blocking_pick_file().into_iter().collect()
|
||||
};
|
||||
|
||||
paths
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
path.into_path()
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.map_err(|error| format!("Could not resolve selected file path: {error}"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_path(app: AppHandle, file_path: String) -> Result<bool, String> {
|
||||
let file_path = file_path.trim();
|
||||
if file_path.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
match app.opener().open_path(file_path, None::<&str>) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(error) => {
|
||||
eprintln!("Failed to open path {file_path}: {error}");
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_allowed_external_url(url: &str) -> bool {
|
||||
tauri::Url::parse(url)
|
||||
.map(|parsed| matches!(parsed.scheme(), "http" | "https" | "mailto" | "tel"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_external_link(app: AppHandle, url: String) -> Result<bool, String> {
|
||||
let url = url.trim();
|
||||
if url.is_empty() || !is_allowed_external_url(url) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
match app.opener().open_url(url, None::<&str>) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(error) => {
|
||||
eprintln!("Failed to open URL {url}: {error}");
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shutdown_backend_sidecar(app: &AppHandle) {
|
||||
if let Some(sidecar) = app.try_state::<BackendSidecar>() {
|
||||
sidecar.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let app = tauri::Builder::default()
|
||||
.menu(|handle| tauri::menu::Menu::default(handle))
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.setup(|app| {
|
||||
let store = load_settings_store(app.handle()).map_err(std::io::Error::other)?;
|
||||
let backend_sidecar =
|
||||
start_backend_sidecar(app.handle(), &store.path).map_err(std::io::Error::other)?;
|
||||
app.manage(store);
|
||||
app.manage(backend_sidecar);
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
if matches!(event, WindowEvent::Focused(true)) {
|
||||
let _ = window.emit("window-focused", ());
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
get_settings,
|
||||
set_setting,
|
||||
update_settings,
|
||||
get_update_status,
|
||||
check_for_updates,
|
||||
get_changelog_page,
|
||||
pick_paths,
|
||||
open_path,
|
||||
open_external_link
|
||||
])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("failed to build Heimgeist Tauri desktop shell");
|
||||
|
||||
app.run(|app_handle, event| {
|
||||
if matches!(
|
||||
event,
|
||||
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit
|
||||
) {
|
||||
shutdown_backend_sidecar(app_handle);
|
||||
}
|
||||
});
|
||||
}
|
||||
38
src-tauri/tauri.conf.json
Normal file
38
src-tauri/tauri.conf.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Heimgeist",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.giers.heimgeist",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev:renderer",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"devUrl": "http://127.0.0.1:5174",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"withGlobalTauri": true,
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Heimgeist",
|
||||
"width": 1000,
|
||||
"height": 720,
|
||||
"minWidth": 680,
|
||||
"minHeight": 300
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["app"],
|
||||
"icon": ["icons/icon.png"],
|
||||
"externalBin": [
|
||||
"binaries/heimgeist-backend",
|
||||
"binaries/heimgeist-ffmpeg",
|
||||
"binaries/heimgeist-ffprobe"
|
||||
]
|
||||
}
|
||||
}
|
||||
2348
src/App.jsx
2348
src/App.jsx
File diff suppressed because it is too large
Load Diff
82
src/AssistantMessageContent.jsx
Normal file
82
src/AssistantMessageContent.jsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import React from 'react'
|
||||
import { markdownToHTML } from './markdown'
|
||||
import { enrichOllamaErrorText, splitThinkBlocks } from './chatText'
|
||||
import desktopApi from './desktop/desktopApi'
|
||||
|
||||
export default function AssistantMessageContent({ content, streamOutput, sources }) {
|
||||
const displayContent = enrichOllamaErrorText(content || '')
|
||||
const { think, answer } = splitThinkBlocks(displayContent)
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const showThinkButton = !!think
|
||||
|
||||
return (
|
||||
<div className="assistant-message">
|
||||
{showThinkButton && (
|
||||
<div className="assistant-thoughts">
|
||||
<button
|
||||
className="think-toggle"
|
||||
onClick={() => setOpen(o => !o)}
|
||||
aria-expanded={open ? 'true' : 'false'}
|
||||
aria-controls="think-content"
|
||||
>
|
||||
<span className="think-toggle-icon" aria-hidden="true">
|
||||
{open ? '▾' : '▸'}
|
||||
</span>
|
||||
Thoughts
|
||||
</button>
|
||||
{open && (
|
||||
<div
|
||||
id="think-content"
|
||||
className="think-content"
|
||||
dangerouslySetInnerHTML={{ __html: markdownToHTML(think) }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="msg-content"
|
||||
dangerouslySetInnerHTML={{ __html: markdownToHTML(answer || displayContent || '') }}
|
||||
/>
|
||||
{Array.isArray(sources) && sources.length > 0 && (
|
||||
<div className="msg-sources chips">
|
||||
{sources.map((source, i) => {
|
||||
const u = typeof source === 'string' ? source : (source?.url || source?.canonical_url || '')
|
||||
let label = typeof source === 'object' && source?.title ? source.title : u
|
||||
let isFile = false
|
||||
try {
|
||||
const parsed = new URL(u)
|
||||
if (parsed.protocol === 'file:') {
|
||||
isFile = true
|
||||
const parts = parsed.pathname.split('/').filter(Boolean)
|
||||
label = decodeURIComponent(parts[parts.length - 1] || u)
|
||||
} else {
|
||||
const host = parsed.hostname || u
|
||||
label = host.replace(/^www\./i, '')
|
||||
}
|
||||
} catch {}
|
||||
return (
|
||||
<a
|
||||
key={(u || JSON.stringify(source)) + i}
|
||||
className="chip"
|
||||
href={u || undefined}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title={typeof source === 'object' ? (source.snippet || u) : u}
|
||||
onClick={(event) => {
|
||||
if (!isFile || !u) return
|
||||
event.preventDefault()
|
||||
try {
|
||||
const parsed = new URL(u)
|
||||
desktopApi.openPath(decodeURIComponent(parsed.pathname))
|
||||
} catch {}
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</a>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,27 +1,83 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { colorSchemes, applyColorScheme } from './colorSchemes';
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { colorSchemes, applyColorScheme } from './colorSchemes'
|
||||
import desktopApi from './desktop/desktopApi'
|
||||
|
||||
const COLOR_SCHEME_KEY = 'colorScheme';
|
||||
const COLOR_SCHEME_KEY = 'colorScheme'
|
||||
const STREAM_KEY = 'streamOutput'
|
||||
const UI_SCALE_KEY = 'uiScale'
|
||||
const OPEN_DEVTOOLS_ON_STARTUP_KEY = 'openDevToolsOnStartup'
|
||||
const DEFAULT_UI_SCALE = 1
|
||||
const MIN_UI_SCALE = 0.7
|
||||
const MAX_UI_SCALE = 1.3
|
||||
const UI_SCALE_STEP = 0.05
|
||||
|
||||
export default function InterfaceSettings() {
|
||||
const [selectedColorScheme, setSelectedColorScheme] = useState('Default');
|
||||
function normalizeUiScale(value) {
|
||||
const numericValue = Number(value)
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
return DEFAULT_UI_SCALE
|
||||
}
|
||||
|
||||
return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, Math.round(numericValue * 100) / 100))
|
||||
}
|
||||
|
||||
export default function InterfaceSettings({
|
||||
streamOutput = false,
|
||||
onStreamOutputChange,
|
||||
}) {
|
||||
const [selectedColorScheme, setSelectedColorScheme] = useState('Default')
|
||||
const [uiScale, setUiScale] = useState(DEFAULT_UI_SCALE)
|
||||
const [openDevToolsOnStartup, setOpenDevToolsOnStartup] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
window.electronAPI.getSettings().then(settings => {
|
||||
setSelectedColorScheme(settings.colorScheme);
|
||||
applyColorScheme(settings.colorScheme);
|
||||
});
|
||||
}, []);
|
||||
desktopApi.getSettings().then(settings => {
|
||||
const schemeName = settings.colorScheme || 'Default'
|
||||
const nextUiScale = normalizeUiScale(settings.uiScale)
|
||||
setSelectedColorScheme(schemeName)
|
||||
setUiScale(nextUiScale)
|
||||
setOpenDevToolsOnStartup(settings.openDevToolsOnStartup === true)
|
||||
applyColorScheme(schemeName)
|
||||
desktopApi.applyUiScale(nextUiScale)
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
applyColorScheme(selectedColorScheme);
|
||||
}, [selectedColorScheme]);
|
||||
applyColorScheme(selectedColorScheme)
|
||||
}, [selectedColorScheme])
|
||||
|
||||
const handleColorSchemeChange = (e) => {
|
||||
const newScheme = e.target.value;
|
||||
setSelectedColorScheme(newScheme);
|
||||
window.electronAPI.setSetting(COLOR_SCHEME_KEY, newScheme);
|
||||
};
|
||||
const handleColorSchemeChange = (event) => {
|
||||
const newScheme = event.target.value
|
||||
setSelectedColorScheme(newScheme)
|
||||
desktopApi.setSetting(COLOR_SCHEME_KEY, newScheme)
|
||||
}
|
||||
|
||||
const persistUiScale = (value) => {
|
||||
const nextScale = normalizeUiScale(value)
|
||||
setUiScale(nextScale)
|
||||
desktopApi.applyUiScale(nextScale)
|
||||
desktopApi.setSetting(UI_SCALE_KEY, nextScale)
|
||||
}
|
||||
|
||||
const handleUiScaleChange = (event) => {
|
||||
persistUiScale(event.target.value)
|
||||
}
|
||||
|
||||
const handleUiScaleReset = () => {
|
||||
persistUiScale(DEFAULT_UI_SCALE)
|
||||
}
|
||||
|
||||
const handleOpenDevToolsOnStartupToggle = () => {
|
||||
const nextValue = !openDevToolsOnStartup
|
||||
setOpenDevToolsOnStartup(nextValue)
|
||||
desktopApi.setSetting(OPEN_DEVTOOLS_ON_STARTUP_KEY, nextValue)
|
||||
}
|
||||
|
||||
const handleStreamOutputToggle = () => {
|
||||
const nextValue = !streamOutput
|
||||
desktopApi.setSetting(STREAM_KEY, nextValue)
|
||||
if (onStreamOutputChange) {
|
||||
onStreamOutputChange(nextValue)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-content-panel">
|
||||
@@ -39,6 +95,60 @@ export default function InterfaceSettings() {
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="setting-section">
|
||||
<h3>UI Scale</h3>
|
||||
<div className="setting-control-row">
|
||||
<input
|
||||
type="range"
|
||||
className="range-input"
|
||||
min={MIN_UI_SCALE}
|
||||
max={MAX_UI_SCALE}
|
||||
step={UI_SCALE_STEP}
|
||||
value={uiScale}
|
||||
onChange={handleUiScaleChange}
|
||||
/>
|
||||
<span className="setting-value">{Math.round(uiScale * 100)}%</span>
|
||||
<button
|
||||
type="button"
|
||||
className="button"
|
||||
onClick={handleUiScaleReset}
|
||||
disabled={uiScale === DEFAULT_UI_SCALE}
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
</div>
|
||||
<p className="setting-description">
|
||||
Scales the whole interface, including fonts, spacing, and controls. 100% is the default size.
|
||||
</p>
|
||||
</div>
|
||||
<div className="setting-section">
|
||||
<h3>Open DevTools on Startup</h3>
|
||||
<label className="toggle-switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={openDevToolsOnStartup}
|
||||
onChange={handleOpenDevToolsOnStartupToggle}
|
||||
/>
|
||||
<span className="slider"></span>
|
||||
</label>
|
||||
<p className="setting-description">
|
||||
Stored for future desktop diagnostics. Tauri does not currently apply this preference automatically.
|
||||
</p>
|
||||
</div>
|
||||
<div className="setting-section">
|
||||
<h3>Stream Output</h3>
|
||||
<label className="toggle-switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={streamOutput}
|
||||
onChange={handleStreamOutputToggle}
|
||||
/>
|
||||
<span className="slider"></span>
|
||||
</label>
|
||||
<p className="setting-description">
|
||||
Shows assistant replies token by token while they are generating instead of waiting for the full message to finish first.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
644
src/LibraryManager.jsx
Normal file
644
src/LibraryManager.jsx
Normal file
@@ -0,0 +1,644 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import desktopApi from './desktop/desktopApi'
|
||||
|
||||
const TOAST_DURATION_MS = {
|
||||
info: 3600,
|
||||
success: 4800,
|
||||
warning: 5600
|
||||
}
|
||||
|
||||
function itemSyncMeta(item) {
|
||||
const sync = item?.sync || {}
|
||||
const status = String(sync.status || 'pending')
|
||||
const progress = Math.max(0, Math.min(100, Number(sync.progress) || 0))
|
||||
const detail = String(sync.detail || '').trim()
|
||||
const enrichEnabled = !!item?.enrich_enabled
|
||||
const metadataReady = ['ready', 'fallback'].includes(item?.metadata?.status)
|
||||
|
||||
if (status === 'ready') {
|
||||
return {
|
||||
status,
|
||||
progress: 100,
|
||||
label: 'Available',
|
||||
detail: detail || (
|
||||
metadataReady
|
||||
? (enrichEnabled ? 'Ready with standard metadata and deep enrichment.' : 'Ready with standard metadata.')
|
||||
: 'Ready for chat. Automatic metadata has not been generated yet.'
|
||||
)
|
||||
}
|
||||
}
|
||||
if (status === 'failed') {
|
||||
return {
|
||||
status,
|
||||
progress: 100,
|
||||
label: 'Sync failed',
|
||||
detail: String(sync.error || '').trim() || detail || 'Heimgeist could not finish syncing this content.'
|
||||
}
|
||||
}
|
||||
if (status === 'syncing') {
|
||||
return {
|
||||
status,
|
||||
progress,
|
||||
label: progress > 0 ? `Syncing ${Math.round(progress)}%` : 'Syncing',
|
||||
detail: detail || 'Rebuilding Knowledge search indexes.'
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'pending',
|
||||
progress: 6,
|
||||
label: 'Queued',
|
||||
detail: 'Waiting to rebuild the retrieval pipeline.'
|
||||
}
|
||||
}
|
||||
|
||||
function kindLabel(item) {
|
||||
if (item?.kind === 'text') return 'Text'
|
||||
if (item?.kind === 'website') return 'Website'
|
||||
if (item?.kind === 'video') return 'Video'
|
||||
if (item?.kind === 'chat_message') return 'Chat Message'
|
||||
return 'File'
|
||||
}
|
||||
|
||||
async function expectJson(response) {
|
||||
const raw = await response.text()
|
||||
let data = null
|
||||
try {
|
||||
data = raw ? JSON.parse(raw) : null
|
||||
} catch {}
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.detail || raw || `HTTP ${response.status}`)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export default function LibraryManager({ apiBase, library, jobs, onOpenChatMessage, onRefresh }) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState('')
|
||||
const [toasts, setToasts] = useState([])
|
||||
const [search, setSearch] = useState('')
|
||||
const [formMode, setFormMode] = useState(null)
|
||||
const [editingItemId, setEditingItemId] = useState(null)
|
||||
const [textTitle, setTextTitle] = useState('')
|
||||
const [textContent, setTextContent] = useState('')
|
||||
const [websiteTitle, setWebsiteTitle] = useState('')
|
||||
const [websiteUrl, setWebsiteUrl] = useState('')
|
||||
const [websiteProcessing, setWebsiteProcessing] = useState(false)
|
||||
const [expandedItemId, setExpandedItemId] = useState(null)
|
||||
const [contentPreviews, setContentPreviews] = useState({})
|
||||
const toastTimeoutsRef = useRef(new Map())
|
||||
const toastIdRef = useRef(0)
|
||||
const previousLibraryStateRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
setErrorMessage('')
|
||||
setSearch('')
|
||||
setExpandedItemId(null)
|
||||
setContentPreviews({})
|
||||
closeForm()
|
||||
}, [library?.slug, library?.name])
|
||||
|
||||
function dismissToast(id) {
|
||||
const timeoutId = toastTimeoutsRef.current.get(id)
|
||||
if (timeoutId) clearTimeout(timeoutId)
|
||||
toastTimeoutsRef.current.delete(id)
|
||||
setToasts(current => current.filter(toast => toast.id !== id))
|
||||
}
|
||||
|
||||
function clearToasts() {
|
||||
toastTimeoutsRef.current.forEach(timeoutId => clearTimeout(timeoutId))
|
||||
toastTimeoutsRef.current.clear()
|
||||
setToasts([])
|
||||
}
|
||||
|
||||
function queueToast(message, tone = 'info') {
|
||||
setToasts(current => {
|
||||
if (current.some(toast => toast.message === message && toast.tone === tone)) return current
|
||||
const id = `library-toast-${toastIdRef.current++}`
|
||||
const timeoutId = window.setTimeout(() => dismissToast(id), TOAST_DURATION_MS[tone] || TOAST_DURATION_MS.info)
|
||||
toastTimeoutsRef.current.set(id, timeoutId)
|
||||
return [...current, { id, message, tone }].slice(-3)
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => () => {
|
||||
toastTimeoutsRef.current.forEach(timeoutId => clearTimeout(timeoutId))
|
||||
toastTimeoutsRef.current.clear()
|
||||
}, [])
|
||||
|
||||
function closeForm() {
|
||||
setFormMode(null)
|
||||
setEditingItemId(null)
|
||||
setTextTitle('')
|
||||
setTextContent('')
|
||||
setWebsiteTitle('')
|
||||
setWebsiteUrl('')
|
||||
}
|
||||
|
||||
async function toggleContentPreview(item) {
|
||||
const itemId = item?.item_id
|
||||
if (!library || !itemId) return
|
||||
if (expandedItemId === itemId) {
|
||||
setExpandedItemId(null)
|
||||
return
|
||||
}
|
||||
setExpandedItemId(itemId)
|
||||
if (contentPreviews[itemId]) return
|
||||
setContentPreviews(current => ({ ...current, [itemId]: { loading: true } }))
|
||||
try {
|
||||
const response = await fetch(`${apiBase}/knowledge/items/${itemId}`)
|
||||
const data = await expectJson(response)
|
||||
setContentPreviews(current => ({ ...current, [itemId]: { data } }))
|
||||
} catch (error) {
|
||||
setContentPreviews(current => ({
|
||||
...current,
|
||||
[itemId]: { error: String(error?.message || error) }
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
async function runAction(fn, successMessage) {
|
||||
setBusy(true)
|
||||
setErrorMessage('')
|
||||
try {
|
||||
const result = await fn()
|
||||
if (successMessage) queueToast(successMessage, 'success')
|
||||
return result
|
||||
} catch (error) {
|
||||
setErrorMessage(String(error?.message || error))
|
||||
throw error
|
||||
} finally {
|
||||
setBusy(false)
|
||||
await onRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
async function addPaths() {
|
||||
if (!library) return
|
||||
const paths = await desktopApi.pickPaths()
|
||||
if (!Array.isArray(paths) || paths.length === 0) return
|
||||
try {
|
||||
await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/files/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths })
|
||||
})
|
||||
return expectJson(response)
|
||||
}, 'Files added. Heimgeist is updating Knowledge.')
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function submitText(event) {
|
||||
event.preventDefault()
|
||||
if (!library) return
|
||||
try {
|
||||
await runAction(async () => {
|
||||
const editing = Boolean(editingItemId)
|
||||
const response = await fetch(
|
||||
editing
|
||||
? `${apiBase}/knowledge/texts/${editingItemId}`
|
||||
: `${apiBase}/knowledge/texts`,
|
||||
{
|
||||
method: editing ? 'PATCH' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: textTitle, content: textContent })
|
||||
}
|
||||
)
|
||||
return expectJson(response)
|
||||
}, editingItemId ? 'Text updated.' : 'Text added to Knowledge.')
|
||||
if (editingItemId) {
|
||||
setContentPreviews(current => {
|
||||
const next = { ...current }
|
||||
delete next[editingItemId]
|
||||
return next
|
||||
})
|
||||
setExpandedItemId(current => current === editingItemId ? null : current)
|
||||
}
|
||||
closeForm()
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function editText(item) {
|
||||
if (!library || !item?.item_id) return
|
||||
setBusy(true)
|
||||
setErrorMessage('')
|
||||
try {
|
||||
const response = await fetch(`${apiBase}/knowledge/items/${item.item_id}`)
|
||||
const data = await expectJson(response)
|
||||
setEditingItemId(item.item_id)
|
||||
setTextTitle(data.title || item.title || item.name || '')
|
||||
setTextContent(data.content || '')
|
||||
setFormMode('text')
|
||||
} catch (error) {
|
||||
setErrorMessage(String(error?.message || error))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function submitWebsite(event) {
|
||||
event.preventDefault()
|
||||
if (!library) return
|
||||
setWebsiteProcessing(true)
|
||||
try {
|
||||
const result = await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/websites`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: websiteUrl, title: websiteTitle || null })
|
||||
})
|
||||
return expectJson(response)
|
||||
})
|
||||
queueToast(
|
||||
result?.content_kind === 'video'
|
||||
? 'Video transcribed and summarized. Heimgeist is indexing it.'
|
||||
: 'Website saved. Heimgeist is indexing its text.',
|
||||
'success'
|
||||
)
|
||||
closeForm()
|
||||
} catch {
|
||||
} finally {
|
||||
setWebsiteProcessing(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshWebsite(item) {
|
||||
if (!library || !item?.item_id) return
|
||||
try {
|
||||
const result = await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/websites/${item.item_id}/refresh`, {
|
||||
method: 'POST'
|
||||
})
|
||||
return expectJson(response)
|
||||
})
|
||||
setContentPreviews(current => {
|
||||
const next = { ...current }
|
||||
delete next[item.item_id]
|
||||
return next
|
||||
})
|
||||
setExpandedItemId(current => current === item.item_id ? null : current)
|
||||
queueToast(result?.changed ? 'Website changed and is being reindexed.' : 'Website checked. No text changes found.', 'success')
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function refreshVideo(item) {
|
||||
if (!library || !item?.item_id) return
|
||||
setWebsiteProcessing(true)
|
||||
try {
|
||||
const result = await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/videos/${item.item_id}/refresh`, {
|
||||
method: 'POST'
|
||||
})
|
||||
return expectJson(response)
|
||||
})
|
||||
setContentPreviews(current => {
|
||||
const next = { ...current }
|
||||
delete next[item.item_id]
|
||||
return next
|
||||
})
|
||||
setExpandedItemId(current => current === item.item_id ? null : current)
|
||||
queueToast(result?.changed ? 'Video reprocessed and changed.' : 'Video reprocessed. Transcript content is unchanged.', 'success')
|
||||
} catch {
|
||||
} finally {
|
||||
setWebsiteProcessing(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeItem(item) {
|
||||
if (!library) return
|
||||
try {
|
||||
await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/files`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ rel: item.rel })
|
||||
})
|
||||
return expectJson(response)
|
||||
}, `${kindLabel(item)} removed.`)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function updateEnrichment(item, enabled) {
|
||||
if (!library) return
|
||||
try {
|
||||
await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/files/enrichment`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ rel: item.rel, enabled })
|
||||
})
|
||||
return expectJson(response)
|
||||
}, enabled ? 'Deep enrichment enabled. Metadata is being updated.' : 'Using standard metadata only.')
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function generateMetadata() {
|
||||
if (!library) return
|
||||
try {
|
||||
await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/jobs/prepare`, { method: 'POST' })
|
||||
return expectJson(response)
|
||||
}, 'Generating metadata for Knowledge.')
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function retrySync() {
|
||||
if (!library) return
|
||||
try {
|
||||
await runAction(async () => {
|
||||
const response = await fetch(`${apiBase}/knowledge/jobs/prepare`, { method: 'POST' })
|
||||
return expectJson(response)
|
||||
})
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const librarySlug = library?.slug || null
|
||||
const isSyncing = !!librarySlug && (jobs || []).some(
|
||||
job => job.slug === librarySlug && (job.status === 'queued' || job.status === 'running')
|
||||
)
|
||||
const isReadyForChat = !!library?.states?.is_indexed
|
||||
const items = library?.files || []
|
||||
const hasFailedItems = items.some(item => item?.sync?.status === 'failed')
|
||||
const filteredItems = useMemo(() => {
|
||||
const term = search.trim().toLowerCase()
|
||||
if (!term) return items
|
||||
return items.filter(item => [
|
||||
item.title,
|
||||
item.name,
|
||||
item.path,
|
||||
item.url,
|
||||
item.kind,
|
||||
item.source_session_title,
|
||||
item.source_role,
|
||||
item.channel,
|
||||
item.video_summary,
|
||||
item.metadata?.headline,
|
||||
item.metadata?.summary,
|
||||
...(item.metadata?.keywords || []),
|
||||
...(item.metadata?.entities || []).map(entity => entity?.name)
|
||||
]
|
||||
.some(value => String(value || '').toLowerCase().includes(term)))
|
||||
}, [items, search])
|
||||
const hasMissingMetadata = items.some(item => !['ready', 'fallback'].includes(item?.metadata?.status))
|
||||
|
||||
useEffect(() => {
|
||||
if (!library?.slug) {
|
||||
previousLibraryStateRef.current = null
|
||||
clearToasts()
|
||||
return
|
||||
}
|
||||
const nextState = {
|
||||
slug: library.slug,
|
||||
hasItems: items.length > 0,
|
||||
isSyncing,
|
||||
isReadyForChat,
|
||||
hasFailedItems
|
||||
}
|
||||
const previousState = previousLibraryStateRef.current
|
||||
if (!previousState || previousState.slug !== nextState.slug) {
|
||||
previousLibraryStateRef.current = nextState
|
||||
return
|
||||
}
|
||||
if (!previousState.isSyncing && nextState.isSyncing) {
|
||||
queueToast('Syncing Knowledge. Heimgeist is rebuilding its search indexes.')
|
||||
} else if (previousState.isSyncing && !nextState.isSyncing) {
|
||||
if (nextState.hasFailedItems) queueToast('Some content did not finish syncing.', 'warning')
|
||||
else if (nextState.isReadyForChat) queueToast('Sync complete. Knowledge is ready in chat.', 'success')
|
||||
}
|
||||
previousLibraryStateRef.current = nextState
|
||||
}, [library?.slug, items.length, hasFailedItems, isReadyForChat, isSyncing])
|
||||
|
||||
if (!library) {
|
||||
return <div className="placeholder-view"><p>Add files, your own texts, or websites to Knowledge.</p></div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="library-panel">
|
||||
<div className="library-panel-scroll">
|
||||
{errorMessage && <div className="form-error">{errorMessage}</div>}
|
||||
|
||||
{formMode === 'text' && (
|
||||
<form className="library-inline-form library-content-form" onSubmit={submitText}>
|
||||
<div className="library-form-header">
|
||||
<strong>{editingItemId ? 'Edit text' : 'Add text'}</strong>
|
||||
<button type="button" className="button ghost" onClick={closeForm}>Cancel</button>
|
||||
</div>
|
||||
<label>
|
||||
Title
|
||||
<input value={textTitle} onChange={event => setTextTitle(event.target.value)} autoFocus required />
|
||||
</label>
|
||||
<label>
|
||||
Text
|
||||
<textarea value={textContent} onChange={event => setTextContent(event.target.value)} rows={12} required />
|
||||
</label>
|
||||
<div className="library-form-actions">
|
||||
<button className="button" type="submit" disabled={busy}>{editingItemId ? 'Save Changes' : 'Add Text'}</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{formMode === 'website' && (
|
||||
<form className="library-inline-form library-content-form" onSubmit={submitWebsite}>
|
||||
<div className="library-form-header">
|
||||
<strong>Add website or video</strong>
|
||||
<button type="button" className="button ghost" onClick={closeForm}>Cancel</button>
|
||||
</div>
|
||||
<p className="muted-copy library-video-help">
|
||||
Supported video links are detected automatically, downloaded temporarily, transcribed with Whisper, and summarized locally. Video and audio files are discarded afterwards.
|
||||
</p>
|
||||
<label>
|
||||
Website or video URL
|
||||
<input type="url" value={websiteUrl} onChange={event => setWebsiteUrl(event.target.value)} placeholder="https://example.com/article-or-video" autoFocus required />
|
||||
</label>
|
||||
<label>
|
||||
Custom title <span className="muted-copy">(optional)</span>
|
||||
<input value={websiteTitle} onChange={event => setWebsiteTitle(event.target.value)} />
|
||||
</label>
|
||||
<p className="muted-copy">Normal webpages are saved as one local text snapshot. Heimgeist will not crawl linked pages.</p>
|
||||
<div className="library-form-actions">
|
||||
<button className="button" type="submit" disabled={busy}>{websiteProcessing ? 'Processing content...' : 'Add Content'}</button>
|
||||
</div>
|
||||
{websiteProcessing && <div className="library-video-processing">Video processing can take several minutes. Heimgeist is downloading audio, transcribing it, and generating a local summary.</div>}
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="library-content-heading">
|
||||
<div>
|
||||
<h2>Contents</h2>
|
||||
<p className="muted-copy">Files, texts, website snapshots, videos, and saved chat messages are searched together through Knowledge workflows.</p>
|
||||
</div>
|
||||
<input
|
||||
className="library-search"
|
||||
value={search}
|
||||
onChange={event => setSearch(event.target.value)}
|
||||
placeholder="Search contents"
|
||||
aria-label="Search Knowledge contents"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredItems.length ? (
|
||||
<div className="library-content-grid">
|
||||
{filteredItems.map(item => {
|
||||
const sync = itemSyncMeta(item)
|
||||
const label = kindLabel(item)
|
||||
const source = item.kind === 'website'
|
||||
? item.url
|
||||
: item.kind === 'video'
|
||||
? `${item.channel ? `${item.channel} · ` : ''}${item.duration_text || 'Saved video'}`
|
||||
: item.kind === 'text'
|
||||
? 'Written in Heimgeist'
|
||||
: item.kind === 'chat_message'
|
||||
? `${item.source_role === 'user' ? 'User message' : 'Assistant message'} · ${item.source_session_title || 'Chat'}`
|
||||
: item.path
|
||||
const itemId = item.item_id || item.sha256 || item.rel
|
||||
const isExpanded = expandedItemId === itemId
|
||||
const preview = contentPreviews[itemId]
|
||||
const metadata = item.metadata || {}
|
||||
const keywords = Array.isArray(metadata.keywords) ? metadata.keywords : []
|
||||
const entities = Array.isArray(metadata.entities) ? metadata.entities : []
|
||||
const qaPairs = Array.isArray(metadata.qa) ? metadata.qa : []
|
||||
const qualityFlags = Array.isArray(metadata.quality_flags) ? metadata.quality_flags : []
|
||||
return (
|
||||
<article key={itemId} className={`library-content-card kind-${item.kind || 'file'} ${isExpanded ? 'expanded' : ''}`}>
|
||||
<div className="library-content-card-header">
|
||||
<span className="library-kind-badge">{label}</span>
|
||||
<span className={`library-file-sync-label ${sync.status}`}>{sync.label}</span>
|
||||
</div>
|
||||
<div className="library-file-name">{item.title || item.name || item.path}</div>
|
||||
<div className="library-file-path">{source}</div>
|
||||
<div className={`library-file-mode ${item.enrich_enabled ? 'enabled' : ''}`}>
|
||||
{item.enrich_enabled ? 'Deep enrichment' : 'Standard'}
|
||||
</div>
|
||||
{item.kind === 'video' && item.video_summary && (
|
||||
<div className="library-video-summary">
|
||||
<div className="library-metadata-label">Video summary</div>
|
||||
<p>{item.video_summary}</p>
|
||||
<div className="library-metadata-details">
|
||||
{item.extractor && <span>Provider: {item.extractor}</span>}
|
||||
{item.video_id && <span>Video ID: {item.video_id}</span>}
|
||||
{item.upload_date && <span>Uploaded: {item.upload_date}</span>}
|
||||
{item.transcription_model && <span>Whisper: {item.transcription_model}</span>}
|
||||
{item.transcription_workers && <span>Workers: {item.transcription_workers}</span>}
|
||||
{item.transcription_slices && <span>Audio slices: {item.transcription_slices}</span>}
|
||||
{item.transcript_chars && <span>Transcript: {Number(item.transcript_chars).toLocaleString()} characters</span>}
|
||||
{item.summary_model && <span>Summary: {item.summary_model}</span>}
|
||||
{item.yt_dlp_version && <span>yt-dlp: {item.yt_dlp_version}</span>}
|
||||
{item.fetched_at && <span>Processed: {new Date(item.fetched_at).toLocaleString()}</span>}
|
||||
</div>
|
||||
{item.url && <div className="library-video-source">Source: {item.url}</div>}
|
||||
{item.thumbnail_url && <button type="button" className="button ghost library-video-thumbnail" onClick={() => desktopApi.openExternalLink(item.thumbnail_url)}>Open thumbnail</button>}
|
||||
</div>
|
||||
)}
|
||||
<div className={`library-item-metadata status-${metadata.status || 'missing'}`}>
|
||||
{metadata.headline && <h3>{metadata.headline}</h3>}
|
||||
{metadata.summary ? (
|
||||
<p>{metadata.summary}</p>
|
||||
) : (
|
||||
<p className="muted-copy">
|
||||
{metadata.status === 'pending' ? 'Metadata is being generated.' : 'No automatic metadata has been generated yet.'}
|
||||
</p>
|
||||
)}
|
||||
{keywords.length > 0 && (
|
||||
<div className="library-metadata-chips" aria-label="Keywords">
|
||||
{keywords.map(keyword => <span key={keyword}>{keyword}</span>)}
|
||||
</div>
|
||||
)}
|
||||
{entities.length > 0 && (
|
||||
<div className="library-metadata-entities">
|
||||
{entities.map(entity => (
|
||||
<span key={`${entity.name}-${entity.type}`}>{entity.name}{entity.type ? ` · ${entity.type}` : ''}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{qaPairs.length > 0 && (
|
||||
<div className="library-metadata-qa">
|
||||
<div className="library-metadata-label">Generated Q&A</div>
|
||||
{qaPairs.map((qa, index) => (
|
||||
<div className="library-metadata-qa-pair" key={`${qa.q}-${index}`}>
|
||||
<strong>{qa.q}</strong>
|
||||
<span>{qa.a}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{(metadata.model || metadata.language || metadata.strategy || qualityFlags.length > 0) && (
|
||||
<div className="library-metadata-details">
|
||||
{metadata.model && <span>Model: {metadata.model}</span>}
|
||||
{metadata.language && <span>Language: {metadata.language}</span>}
|
||||
{metadata.strategy && <span>Strategy: {metadata.strategy}</span>}
|
||||
{qualityFlags.length > 0 && <span>Flags: {qualityFlags.join(', ')}</span>}
|
||||
</div>
|
||||
)}
|
||||
{metadata.status === 'fallback' && <div className="library-metadata-warning">Local model metadata was unavailable; Heimgeist used a text fallback.</div>}
|
||||
{metadata.status === 'failed' && <div className="library-metadata-warning">{metadata.error || 'Metadata generation failed.'}</div>}
|
||||
</div>
|
||||
<div className="library-file-sync">
|
||||
<div className="library-file-sync-detail">{sync.detail}</div>
|
||||
<div className={`library-file-progress ${sync.status}`} role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow={Math.round(sync.progress)}>
|
||||
<div className="library-file-progress-bar" style={{ width: `${sync.progress}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
{isExpanded && (
|
||||
<div className="library-content-preview">
|
||||
<div className="library-content-preview-label">
|
||||
{item.kind === 'website' ? 'Saved website text' : item.kind === 'video' ? 'Video summary and transcript' : item.kind === 'chat_message' ? 'Stored chat knowledge' : item.kind === 'text' ? 'Stored text' : 'Extracted text used by RAG'}
|
||||
</div>
|
||||
{preview?.loading && <div className="muted-copy">Loading content…</div>}
|
||||
{preview?.error && <div className="form-error">{preview.error}</div>}
|
||||
{preview?.data && (
|
||||
<>
|
||||
<pre>{preview.data.content || 'No readable text was extracted from this item.'}</pre>
|
||||
{preview.data.content_truncated && <div className="muted-copy">Preview shortened. The indexed source contains more text.</div>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="library-file-actions">
|
||||
<button className="button ghost" disabled={busy} onClick={() => toggleContentPreview(item)}>
|
||||
{isExpanded ? 'Hide Content' : 'View Content'}
|
||||
</button>
|
||||
{(item.kind === 'text' || item.kind === 'chat_message') && <button className="button ghost" disabled={busy} onClick={() => editText(item)}>Edit</button>}
|
||||
{item.kind === 'chat_message' && <button className="button ghost" onClick={() => onOpenChatMessage?.(item)}>Open Chat</button>}
|
||||
{item.kind === 'website' && <button className="button ghost" onClick={() => desktopApi.openExternalLink(item.url)}>Open</button>}
|
||||
{item.kind === 'website' && <button className="button ghost" disabled={busy} onClick={() => refreshWebsite(item)}>Refresh</button>}
|
||||
{item.kind === 'video' && <button className="button ghost" onClick={() => desktopApi.openExternalLink(item.url)}>Open</button>}
|
||||
{item.kind === 'video' && <button className="button ghost" disabled={busy} onClick={() => refreshVideo(item)}>Reprocess</button>}
|
||||
{(!item.kind || item.kind === 'file') && <button className="button ghost" onClick={() => desktopApi.openPath(item.path)}>Open</button>}
|
||||
<button className="button ghost" disabled={busy || isSyncing} onClick={() => updateEnrichment(item, !item.enrich_enabled)}>
|
||||
{item.enrich_enabled ? 'Use Standard' : 'Enable Deep'}
|
||||
</button>
|
||||
<button className="button ghost" disabled={busy || isSyncing} onClick={() => removeItem(item)}>Remove</button>
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="muted-copy">{items.length ? 'No matching contents.' : 'No content added yet.'}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="library-footer-actions">
|
||||
<button className="button" disabled={busy} onClick={addPaths}>Add Files</button>
|
||||
<button className="button" disabled={busy} onClick={() => { closeForm(); setFormMode('text') }}>Add Text</button>
|
||||
<button className="button" disabled={busy} onClick={() => { closeForm(); setFormMode('website') }}>Add Website / Video</button>
|
||||
{items.length > 0 && hasMissingMetadata && !isSyncing && isReadyForChat && (
|
||||
<button className="button ghost" disabled={busy} onClick={generateMetadata}>Generate Metadata</button>
|
||||
)}
|
||||
{items.length > 0 && !isSyncing && !isReadyForChat && (
|
||||
<button className="button ghost" disabled={busy} onClick={retrySync}>Retry Sync</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{toasts.length > 0 && (
|
||||
<div className="library-toast-stack" aria-live="polite">
|
||||
{toasts.map(toast => (
|
||||
<div key={toast.id} className={`library-toast ${toast.tone}`} role={toast.tone === 'warning' ? 'alert' : 'status'}>
|
||||
{toast.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
125
src/SaveMessageToKnowledgeDialog.jsx
Normal file
125
src/SaveMessageToKnowledgeDialog.jsx
Normal file
@@ -0,0 +1,125 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { splitThinkBlocks } from './chatText'
|
||||
|
||||
function cleanAssistantContent(content) {
|
||||
const raw = String(content || '')
|
||||
try {
|
||||
const { answer } = splitThinkBlocks(raw)
|
||||
return String(answer || raw).trim()
|
||||
} catch {
|
||||
return raw.trim()
|
||||
}
|
||||
}
|
||||
|
||||
function defaultTitle(message) {
|
||||
const prefix = message?.role === 'user' ? 'User note' : 'Saved answer'
|
||||
const content = message?.role === 'assistant'
|
||||
? cleanAssistantContent(message?.content)
|
||||
: String(message?.content || '').trim()
|
||||
const compact = content.replace(/\s+/g, ' ')
|
||||
if (!compact) return prefix
|
||||
const excerpt = compact.length > 90 ? `${compact.slice(0, 87).trim()}...` : compact
|
||||
return `${prefix}: ${excerpt}`
|
||||
}
|
||||
|
||||
function defaultKnowledgeContent(message, precedingUserMessage) {
|
||||
const content = message?.role === 'assistant'
|
||||
? cleanAssistantContent(message?.content)
|
||||
: String(message?.content || '').trim()
|
||||
if (message?.role !== 'assistant' || !precedingUserMessage?.content?.trim()) {
|
||||
return content
|
||||
}
|
||||
return `User question:\n${precedingUserMessage.content.trim()}\n\nAssistant response:\n${content}`
|
||||
}
|
||||
|
||||
async function expectJson(response) {
|
||||
const raw = await response.text()
|
||||
let data = null
|
||||
try {
|
||||
data = raw ? JSON.parse(raw) : null
|
||||
} catch {}
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.detail || raw || `HTTP ${response.status}`)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export default function SaveMessageToKnowledgeDialog({
|
||||
apiBase,
|
||||
message,
|
||||
onClose,
|
||||
onSaved,
|
||||
precedingUserMessage,
|
||||
}) {
|
||||
const [title, setTitle] = useState(() => defaultTitle(message))
|
||||
const [content, setContent] = useState(() => defaultKnowledgeContent(message, precedingUserMessage))
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = event => {
|
||||
if (event.key === 'Escape' && !busy) onClose()
|
||||
}
|
||||
document.addEventListener('keydown', onKeyDown)
|
||||
return () => document.removeEventListener('keydown', onKeyDown)
|
||||
}, [busy, onClose])
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault()
|
||||
if (!message?.message_id) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const response = await fetch(`${apiBase}/knowledge/chat-messages`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message_id: message.message_id,
|
||||
title,
|
||||
content,
|
||||
}),
|
||||
})
|
||||
const data = await expectJson(response)
|
||||
await onSaved(data)
|
||||
} catch (submitError) {
|
||||
setError(String(submitError?.message || submitError))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="knowledge-save-overlay" role="presentation" onMouseDown={event => {
|
||||
if (event.target === event.currentTarget && !busy) onClose()
|
||||
}}>
|
||||
<form className="knowledge-save-dialog" role="dialog" aria-modal="true" aria-labelledby="knowledge-save-title" onSubmit={submit}>
|
||||
<div className="knowledge-save-header">
|
||||
<div>
|
||||
<strong id="knowledge-save-title">Save message to knowledge</strong>
|
||||
<p>The saved snapshot becomes a normal item in Knowledge.</p>
|
||||
</div>
|
||||
<button type="button" className="icon-button" title="Close" aria-label="Close" onClick={onClose} disabled={busy}>
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12" /></svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label>
|
||||
Title
|
||||
<input value={title} onChange={event => setTitle(event.target.value)} required autoFocus disabled={busy} />
|
||||
</label>
|
||||
<label>
|
||||
Knowledge content
|
||||
<textarea value={content} onChange={event => setContent(event.target.value)} rows={12} required disabled={busy} />
|
||||
</label>
|
||||
|
||||
{error && <div className="form-error">{error}</div>}
|
||||
<div className="knowledge-save-actions">
|
||||
<button type="button" className="button ghost" onClick={onClose} disabled={busy}>Cancel</button>
|
||||
<button type="submit" className="button" disabled={busy || !title.trim() || !content.trim()}>
|
||||
{busy ? 'Saving...' : 'Save to Knowledge'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
88
src/SettingsPanels.jsx
Normal file
88
src/SettingsPanels.jsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import GeneralSettings from './GeneralSettings'
|
||||
import InterfaceSettings from './InterfaceSettings'
|
||||
import WebsearchSettings from './WebsearchSettings'
|
||||
import { normalizeWebsearchEngines } from './websearchEngines'
|
||||
|
||||
const SETTINGS_SECTIONS = ['General', 'AI Models', 'Interface', 'Backend', 'Updates', 'Advanced']
|
||||
|
||||
export function SettingsSidebar({ activeSection, onSelect }) {
|
||||
return (
|
||||
<div className="settings-list">
|
||||
{SETTINGS_SECTIONS.map(section => (
|
||||
<div
|
||||
key={section}
|
||||
className={`settings-item ${activeSection === section ? 'active' : ''}`}
|
||||
onClick={() => onSelect(section)}
|
||||
>
|
||||
{section}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function SettingsPanel({
|
||||
activeSection,
|
||||
onAudioInputDeviceChange,
|
||||
onAudioInputLanguageChange,
|
||||
onBackendApiUrlChange,
|
||||
onLibrariesPurged,
|
||||
onModelChange,
|
||||
onStreamOutputChange,
|
||||
onTranscriptionModelChange,
|
||||
onVisionModelChange,
|
||||
onWorkflowRouterModelChange,
|
||||
onWorkflowSelectionModeChange,
|
||||
searxEngines,
|
||||
searxUrl,
|
||||
setSearxEngines,
|
||||
setSearxUrl,
|
||||
streamOutput,
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className="header">
|
||||
<strong>{activeSection} Settings</strong>
|
||||
</div>
|
||||
{activeSection === 'General' && (
|
||||
<GeneralSettings
|
||||
panel="General"
|
||||
onAudioInputDeviceChange={onAudioInputDeviceChange}
|
||||
onAudioInputLanguageChange={onAudioInputLanguageChange}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'AI Models' && (
|
||||
<GeneralSettings
|
||||
panel="AI Models"
|
||||
onModelChange={onModelChange}
|
||||
onVisionModelChange={onVisionModelChange}
|
||||
onWorkflowRouterModelChange={onWorkflowRouterModelChange}
|
||||
onWorkflowSelectionModeChange={onWorkflowSelectionModeChange}
|
||||
onTranscriptionModelChange={onTranscriptionModelChange}
|
||||
onLibrariesPurged={onLibrariesPurged}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'Interface' && (
|
||||
<InterfaceSettings
|
||||
streamOutput={streamOutput}
|
||||
onStreamOutputChange={onStreamOutputChange}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'Backend' && (
|
||||
<WebsearchSettings
|
||||
onBackendApiUrlChange={onBackendApiUrlChange}
|
||||
searxUrl={searxUrl}
|
||||
setSearxUrl={setSearxUrl}
|
||||
engines={searxEngines}
|
||||
setEngines={(next) => setSearxEngines(normalizeWebsearchEngines(next))}
|
||||
/>
|
||||
)}
|
||||
{activeSection === 'Updates' && (
|
||||
<GeneralSettings panel="Updates" />
|
||||
)}
|
||||
{activeSection === 'Advanced' && (
|
||||
<GeneralSettings panel="Advanced" onLibrariesPurged={onLibrariesPurged} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
116
src/WebsearchSettings.jsx
Normal file
116
src/WebsearchSettings.jsx
Normal file
@@ -0,0 +1,116 @@
|
||||
// src/WebsearchSettings.jsx
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { WEBSEARCH_ENGINE_OPTIONS, normalizeWebsearchEngines } from './websearchEngines'
|
||||
import desktopApi from './desktop/desktopApi'
|
||||
|
||||
const BACKEND_API_URL_KEY = 'backendApiUrl'
|
||||
const OLLAMA_API_URL_KEY = 'ollamaApiUrl'
|
||||
const DEFAULT_BACKEND_API_URL = 'http://127.0.0.1:8000'
|
||||
const DEFAULT_OLLAMA_API_URL = 'http://127.0.0.1:11434'
|
||||
|
||||
function resolveBackendApiUrl(settings) {
|
||||
return settings.backendApiUrl || settings.ollamaApiUrl || DEFAULT_BACKEND_API_URL
|
||||
}
|
||||
|
||||
export default function WebsearchSettings({
|
||||
onBackendApiUrlChange,
|
||||
searxUrl,
|
||||
setSearxUrl,
|
||||
engines,
|
||||
setEngines,
|
||||
}) {
|
||||
const [backendApiUrl, setBackendApiUrl] = useState('')
|
||||
const [ollamaApiUrl, setOllamaApiUrl] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
desktopApi.getSettings().then(settings => {
|
||||
if (cancelled) {
|
||||
return
|
||||
}
|
||||
setBackendApiUrl(resolveBackendApiUrl(settings))
|
||||
setOllamaApiUrl(settings.ollamaApiUrl || DEFAULT_OLLAMA_API_URL)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const toggleEngine = (name) => {
|
||||
const set = new Set(engines || []);
|
||||
if (set.has(name)) set.delete(name); else set.add(name);
|
||||
setEngines(normalizeWebsearchEngines(Array.from(set)));
|
||||
}
|
||||
|
||||
const handleBackendUrlChange = (event) => {
|
||||
const newUrl = event.target.value
|
||||
setBackendApiUrl(newUrl)
|
||||
desktopApi.setSetting(BACKEND_API_URL_KEY, newUrl)
|
||||
if (onBackendApiUrlChange) {
|
||||
onBackendApiUrlChange(newUrl)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOllamaUrlChange = (event) => {
|
||||
const newUrl = event.target.value
|
||||
setOllamaApiUrl(newUrl)
|
||||
desktopApi.setSetting(OLLAMA_API_URL_KEY, newUrl)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-content-panel">
|
||||
<div className="setting-section">
|
||||
<h3>Heimgeist Backend URL</h3>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
value={backendApiUrl}
|
||||
onChange={handleBackendUrlChange}
|
||||
placeholder={`e.g., ${DEFAULT_BACKEND_API_URL}`}
|
||||
/>
|
||||
<p className="setting-description">Internal UI requests like chats, sessions, and Knowledge go to this URL.</p>
|
||||
</div>
|
||||
|
||||
<div className="setting-section">
|
||||
<h3>Ollama URL</h3>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
value={ollamaApiUrl}
|
||||
onChange={handleOllamaUrlChange}
|
||||
placeholder={`e.g., ${DEFAULT_OLLAMA_API_URL}`}
|
||||
/>
|
||||
<p className="setting-description">Heimgeist uses this URL to talk to Ollama for models and chat generation.</p>
|
||||
</div>
|
||||
|
||||
<div className="setting-section">
|
||||
<h3>SearXNG URL</h3>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
value={searxUrl}
|
||||
onChange={e => setSearxUrl(e.target.value)}
|
||||
placeholder="e.g., http://127.0.0.1:8888"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="setting-section">
|
||||
<h3>Search Engines</h3>
|
||||
<div className="engine-grid">
|
||||
{WEBSEARCH_ENGINE_OPTIONS.map(({ value, label }) => (
|
||||
<label key={value} className="engine-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Array.isArray(engines) ? engines.includes(value) : false}
|
||||
onChange={() => toggleEngine(value)}
|
||||
/>
|
||||
<span>{label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
24
src/appConfig.js
Normal file
24
src/appConfig.js
Normal file
@@ -0,0 +1,24 @@
|
||||
export const API_URL_KEY = 'backendApiUrl'
|
||||
export const COLOR_SCHEME_KEY = 'colorScheme'
|
||||
export const WEBSEARCH_URL_KEY = 'websearch.searxUrl'
|
||||
export const WEBSEARCH_ENGINES_KEY = 'websearch.engines'
|
||||
export const CHAT_WORKFLOW_MAP_KEY = 'chat.workflowBySession'
|
||||
export const DEFAULT_SEARX_URL = 'http://127.0.0.1:8888'
|
||||
export const DEFAULT_BACKEND_API_URL = import.meta.env.VITE_API_URL ?? 'http://127.0.0.1:8000'
|
||||
export const MAX_IMAGE_ATTACHMENTS = 6
|
||||
export const MAX_IMAGE_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
||||
export const MAX_AUDIO_RECORDING_MS = 5 * 60 * 1000
|
||||
export const AUDIO_RECORDING_TICK_MS = 200
|
||||
export const TOP_ALIGN_OFFSET = 48
|
||||
export const BOTTOM_EPSILON = 24
|
||||
|
||||
export function resolveBackendApiUrl(settings) {
|
||||
return settings?.backendApiUrl || settings?.ollamaApiUrl || DEFAULT_BACKEND_API_URL
|
||||
}
|
||||
|
||||
export function migrateLegacySearxUrl(value) {
|
||||
const trimmed = typeof value === 'string' ? value.trim() : ''
|
||||
if (!trimmed) return DEFAULT_SEARX_URL
|
||||
if (trimmed === 'http://localhost:8888') return DEFAULT_SEARX_URL
|
||||
return trimmed
|
||||
}
|
||||
203
src/attachments.jsx
Normal file
203
src/attachments.jsx
Normal file
@@ -0,0 +1,203 @@
|
||||
const CHAT_IMAGE_EXTENSION_LIST = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.tif', '.tiff', '.heic', '.avif']
|
||||
const CHAT_FILE_EXTENSION_LIST = [
|
||||
'.pdf', '.html', '.htm', '.txt', '.md', '.rst', '.epub',
|
||||
'.mp3', '.wav', '.m4a', '.flac', '.ogg', '.opus', '.aac',
|
||||
'.mp4', '.mkv', '.mov', '.webm', '.avi', '.ts',
|
||||
]
|
||||
const CHAT_IMAGE_EXTENSION_SET = new Set(CHAT_IMAGE_EXTENSION_LIST)
|
||||
const CHAT_FILE_EXTENSION_SET = new Set(CHAT_FILE_EXTENSION_LIST)
|
||||
const CHAT_AUDIO_EXTENSION_SET = new Set(['.mp3', '.wav', '.m4a', '.flac', '.ogg', '.opus', '.aac'])
|
||||
const CHAT_VIDEO_EXTENSION_SET = new Set(['.mp4', '.mkv', '.mov', '.webm', '.avi', '.ts'])
|
||||
const CHAT_TEXT_EXTENSION_SET = new Set(['.txt', '.md', '.rst'])
|
||||
|
||||
export const CHAT_FILE_PICKER_FILTERS = [
|
||||
{ name: 'Documents and Media', extensions: CHAT_FILE_EXTENSION_LIST.map(extension => extension.slice(1)) },
|
||||
]
|
||||
|
||||
export function getFileExtension(value) {
|
||||
const text = String(value || '').trim()
|
||||
const match = /(?:\.([A-Za-z0-9]+))$/.exec(text)
|
||||
return match ? `.${match[1].toLowerCase()}` : ''
|
||||
}
|
||||
|
||||
export function getFileName(value, fallback = 'attachment') {
|
||||
const text = String(value || '').trim()
|
||||
if (!text) return fallback
|
||||
const parts = text.split(/[\\/]/)
|
||||
return parts[parts.length - 1] || fallback
|
||||
}
|
||||
|
||||
export function guessMimeTypeFromName(value) {
|
||||
const extension = getFileExtension(value)
|
||||
switch (extension) {
|
||||
case '.pdf': return 'application/pdf'
|
||||
case '.html':
|
||||
case '.htm': return 'text/html'
|
||||
case '.txt': return 'text/plain'
|
||||
case '.md': return 'text/markdown'
|
||||
case '.rst': return 'text/x-rst'
|
||||
case '.epub': return 'application/epub+zip'
|
||||
case '.mp3': return 'audio/mpeg'
|
||||
case '.wav': return 'audio/wav'
|
||||
case '.m4a': return 'audio/mp4'
|
||||
case '.flac': return 'audio/flac'
|
||||
case '.ogg': return 'audio/ogg'
|
||||
case '.opus': return 'audio/opus'
|
||||
case '.aac': return 'audio/aac'
|
||||
case '.mp4': return 'video/mp4'
|
||||
case '.mkv': return 'video/x-matroska'
|
||||
case '.mov': return 'video/quicktime'
|
||||
case '.webm': return 'video/webm'
|
||||
case '.avi': return 'video/x-msvideo'
|
||||
case '.ts': return 'video/mp2t'
|
||||
default: return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function attachmentIsImage(attachment) {
|
||||
return Boolean(attachment?.data_url) || String(attachment?.kind || '').toLowerCase() === 'image'
|
||||
}
|
||||
|
||||
export function attachmentIsFile(attachment) {
|
||||
return Boolean(attachment) && !attachmentIsImage(attachment)
|
||||
}
|
||||
|
||||
export function isSupportedChatFilePath(value) {
|
||||
return CHAT_FILE_EXTENSION_SET.has(getFileExtension(value))
|
||||
}
|
||||
|
||||
export function isSupportedChatImagePath(value) {
|
||||
return CHAT_IMAGE_EXTENSION_SET.has(getFileExtension(value))
|
||||
}
|
||||
|
||||
export function isImageFile(file) {
|
||||
if (!file) return false
|
||||
if (typeof file.type === 'string' && file.type.toLowerCase().startsWith('image/')) {
|
||||
return true
|
||||
}
|
||||
return /\.(png|jpe?g|gif|bmp|webp|tiff?|heic|avif)$/i.test(file.name || '')
|
||||
}
|
||||
|
||||
export function isSupportedChatFile(file) {
|
||||
if (!file || isImageFile(file)) return false
|
||||
return isSupportedChatFilePath(file.name || '')
|
||||
}
|
||||
|
||||
export function getAttachmentDisplayName(attachment, fallback = 'attachment') {
|
||||
return String(attachment?.name || '').trim() || getFileName(attachment?.source_path, fallback)
|
||||
}
|
||||
|
||||
export function getFileAttachmentBadge(attachment) {
|
||||
const mimeType = String(attachment?.mime_type || '').toLowerCase()
|
||||
const extension = getFileExtension(attachment?.name || attachment?.source_path || '')
|
||||
if (mimeType.startsWith('audio/') || CHAT_AUDIO_EXTENSION_SET.has(extension)) return 'AUDIO'
|
||||
if (mimeType.startsWith('video/') || CHAT_VIDEO_EXTENSION_SET.has(extension)) return 'VIDEO'
|
||||
if (CHAT_TEXT_EXTENSION_SET.has(extension)) return 'TEXT'
|
||||
return 'DOC'
|
||||
}
|
||||
|
||||
export function buildComposerAttachmentId(prefix = 'attachment') {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
}
|
||||
|
||||
export function buildComposerFileAttachment({ sourcePath, name, mimeType, size }) {
|
||||
const displayName = String(name || '').trim() || getFileName(sourcePath, 'file')
|
||||
return {
|
||||
id: buildComposerAttachmentId('file'),
|
||||
kind: 'file',
|
||||
name: displayName,
|
||||
mime_type: String(mimeType || '').trim() || guessMimeTypeFromName(displayName || sourcePath),
|
||||
source_path: sourcePath,
|
||||
size: Number.isFinite(Number(size)) ? Number(size) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export function hasFilePayload(event) {
|
||||
const types = Array.from(event?.dataTransfer?.types || [])
|
||||
return types.includes('Files')
|
||||
}
|
||||
|
||||
export function eventHasImageFiles(event) {
|
||||
const items = Array.from(event?.dataTransfer?.items || [])
|
||||
if (items.length > 0) {
|
||||
return items.some(item => item.kind === 'file' && isImageFile(item.getAsFile?.()))
|
||||
}
|
||||
const files = Array.from(event?.dataTransfer?.files || [])
|
||||
return files.some(isImageFile)
|
||||
}
|
||||
|
||||
export function readFileAsDataUrl(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onerror = () => reject(reader.error || new Error(`Failed to read ${file?.name || 'image'}`))
|
||||
reader.onload = () => resolve(String(reader.result || ''))
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
export function AttachmentStrip({ attachments, className = '', removable = false, onRemove }) {
|
||||
if (!Array.isArray(attachments) || attachments.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`attachment-strip ${className}`.trim()}>
|
||||
{attachments.map((attachment, index) => {
|
||||
const isImage = attachmentIsImage(attachment)
|
||||
const keySeed = isImage
|
||||
? attachment?.data_url?.length || attachment?.name || index
|
||||
: attachment?.source_path || attachment?.name || index
|
||||
const key = attachment.id || `${getAttachmentDisplayName(attachment, 'attachment')}-${index}-${keySeed}`
|
||||
|
||||
if (isImage) {
|
||||
const src = attachment?.data_url
|
||||
if (!src) return null
|
||||
return (
|
||||
<div key={key} className="image-attachment-card">
|
||||
{removable && (
|
||||
<button
|
||||
type="button"
|
||||
className="attachment-remove"
|
||||
onClick={() => onRemove?.(attachment.id)}
|
||||
aria-label={`Remove ${getAttachmentDisplayName(attachment, 'image')}`}
|
||||
title="Remove attachment"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
<img
|
||||
className="image-attachment-thumb"
|
||||
src={src}
|
||||
alt={getAttachmentDisplayName(attachment, `Attachment ${index + 1}`)}
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const label = getAttachmentDisplayName(attachment, `Attachment ${index + 1}`)
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className="file-attachment-card"
|
||||
title={attachment?.source_path || label}
|
||||
>
|
||||
{removable && (
|
||||
<button
|
||||
type="button"
|
||||
className="attachment-remove attachment-remove--file"
|
||||
onClick={() => onRemove?.(attachment.id)}
|
||||
aria-label={`Remove ${label}`}
|
||||
title="Remove attachment"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
<span className="file-attachment-badge">{getFileAttachmentBadge(attachment)}</span>
|
||||
<span className="file-attachment-name">{label}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
102
src/audioInput.js
Normal file
102
src/audioInput.js
Normal file
@@ -0,0 +1,102 @@
|
||||
export const AUDIO_INPUT_ENABLED_KEY = 'audioInputEnabled'
|
||||
export const AUDIO_INPUT_DEVICE_ID_KEY = 'audioInputDeviceId'
|
||||
export const AUDIO_INPUT_LANGUAGE_KEY = 'audioInputLanguage'
|
||||
|
||||
export const AUDIO_INPUT_LANGUAGE_OPTIONS = [
|
||||
{ value: '', label: 'Auto' },
|
||||
{ value: 'de', label: 'German' },
|
||||
{ value: 'en', label: 'English' },
|
||||
{ value: 'fr', label: 'French' },
|
||||
{ value: 'es', label: 'Spanish' },
|
||||
{ value: 'it', label: 'Italian' },
|
||||
{ value: 'pt', label: 'Portuguese' },
|
||||
{ value: 'nl', label: 'Dutch' },
|
||||
{ value: 'pl', label: 'Polish' },
|
||||
{ value: 'tr', label: 'Turkish' },
|
||||
{ value: 'ru', label: 'Russian' },
|
||||
{ value: 'ja', label: 'Japanese' },
|
||||
{ value: 'zh', label: 'Chinese' },
|
||||
]
|
||||
|
||||
const AUDIO_RECORDER_MIME_CANDIDATES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/mp4',
|
||||
'audio/ogg;codecs=opus',
|
||||
'',
|
||||
]
|
||||
|
||||
export function supportsAudioInputCapture() {
|
||||
return (
|
||||
typeof navigator !== 'undefined' &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.MediaRecorder !== 'undefined' &&
|
||||
Boolean(navigator.mediaDevices?.getUserMedia) &&
|
||||
Boolean(navigator.mediaDevices?.enumerateDevices)
|
||||
)
|
||||
}
|
||||
|
||||
export function getAudioInputConstraints(deviceId = '') {
|
||||
const audio = {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
}
|
||||
|
||||
if (deviceId) {
|
||||
audio.deviceId = { exact: deviceId }
|
||||
}
|
||||
|
||||
return { audio }
|
||||
}
|
||||
|
||||
export function stopMediaStream(stream) {
|
||||
stream?.getTracks?.().forEach(track => track.stop())
|
||||
}
|
||||
|
||||
export async function ensureAudioInputPermission() {
|
||||
if (!supportsAudioInputCapture()) {
|
||||
throw new Error('Microphone capture is not available in this environment.')
|
||||
}
|
||||
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
|
||||
stopMediaStream(stream)
|
||||
}
|
||||
|
||||
export async function listAudioInputDevices() {
|
||||
if (!supportsAudioInputCapture()) {
|
||||
return []
|
||||
}
|
||||
|
||||
const devices = await navigator.mediaDevices.enumerateDevices()
|
||||
return devices
|
||||
.filter(device => device.kind === 'audioinput')
|
||||
.map((device, index) => {
|
||||
const label = String(device.label || '').trim()
|
||||
return {
|
||||
deviceId: device.deviceId || `audio-input-${index + 1}`,
|
||||
label: label || `Microphone ${index + 1}`,
|
||||
hasLabel: Boolean(label),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function getPreferredAudioRecorderMimeType() {
|
||||
if (typeof window === 'undefined' || typeof window.MediaRecorder === 'undefined') {
|
||||
return ''
|
||||
}
|
||||
|
||||
for (const mimeType of AUDIO_RECORDER_MIME_CANDIDATES) {
|
||||
if (!mimeType) {
|
||||
return ''
|
||||
}
|
||||
if (
|
||||
typeof window.MediaRecorder.isTypeSupported !== 'function' ||
|
||||
window.MediaRecorder.isTypeSupported(mimeType)
|
||||
) {
|
||||
return mimeType
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
34
src/backendApi.js
Normal file
34
src/backendApi.js
Normal file
@@ -0,0 +1,34 @@
|
||||
export function isAbortError(error) {
|
||||
return error?.name === 'AbortError'
|
||||
}
|
||||
|
||||
export function getErrorText(error) {
|
||||
if (error instanceof Error && error.message) return error.message
|
||||
return String(error)
|
||||
}
|
||||
|
||||
export async function readBackendErrorText(response) {
|
||||
const bodyText = await response.text().catch(() => '')
|
||||
if (bodyText) {
|
||||
try {
|
||||
const data = JSON.parse(bodyText)
|
||||
if (typeof data?.detail === 'string' && data.detail.trim()) {
|
||||
return data.detail.trim()
|
||||
}
|
||||
if (typeof data?.message === 'string' && data.message.trim()) {
|
||||
return data.message.trim()
|
||||
}
|
||||
} catch {}
|
||||
return bodyText.trim()
|
||||
}
|
||||
return `HTTP ${response.status}`
|
||||
}
|
||||
|
||||
export async function expectBackendJson(response) {
|
||||
const data = await response.json().catch(() => null)
|
||||
if (response.ok) return data
|
||||
const detail = typeof data?.detail === 'string'
|
||||
? data.detail
|
||||
: (typeof data?.message === 'string' ? data.message : '')
|
||||
throw new Error(detail || `HTTP ${response.status}`)
|
||||
}
|
||||
141
src/chatApi.js
Normal file
141
src/chatApi.js
Normal file
@@ -0,0 +1,141 @@
|
||||
import { expectBackendJson } from './backendApi'
|
||||
|
||||
export async function fetchModelCapabilities(apiBase, modelName, signal) {
|
||||
const response = await fetch(
|
||||
`${apiBase}/models/capabilities?name=${encodeURIComponent(modelName)}`,
|
||||
{ signal }
|
||||
)
|
||||
return expectBackendJson(response)
|
||||
}
|
||||
|
||||
export async function fetchStartupOllamaStatus(apiBase) {
|
||||
const response = await fetch(`${apiBase}/ollama/startup-status`)
|
||||
return expectBackendJson(response)
|
||||
}
|
||||
|
||||
export async function prepareStartupModels(apiBase) {
|
||||
const response = await fetch(`${apiBase}/startup/prepare-models`, { method: 'POST' })
|
||||
return expectBackendJson(response)
|
||||
}
|
||||
|
||||
export async function fetchLocalLibraryContext(apiBase, prompt, signal) {
|
||||
const response = await fetch(`${apiBase}/knowledge/context`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
top_k: 5,
|
||||
}),
|
||||
})
|
||||
const data = await response.json()
|
||||
return {
|
||||
contextBlock: typeof data?.context_block === 'string' && data.context_block.trim()
|
||||
? data.context_block.trim()
|
||||
: null,
|
||||
sources: Array.isArray(data?.sources) ? data.sources : [],
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchWebSearchContext({
|
||||
apiBase,
|
||||
engines,
|
||||
historyLimit = 8,
|
||||
messages,
|
||||
model,
|
||||
prompt,
|
||||
searxUrl,
|
||||
signal,
|
||||
}) {
|
||||
const response = await fetch(`${apiBase}/websearch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
model,
|
||||
messages,
|
||||
history_limit: historyLimit,
|
||||
searx_url: searxUrl || null,
|
||||
engines: Array.isArray(engines) ? engines : null,
|
||||
}),
|
||||
})
|
||||
const data = await response.json()
|
||||
return {
|
||||
contextBlock: typeof data?.context_block === 'string' && data.context_block.trim()
|
||||
? data.context_block.trim()
|
||||
: null,
|
||||
sources: Array.isArray(data?.sources) ? data.sources : [],
|
||||
}
|
||||
}
|
||||
|
||||
export function postChatMessage({
|
||||
apiBase,
|
||||
attachments,
|
||||
enrichedMessage,
|
||||
message,
|
||||
model,
|
||||
sessionId,
|
||||
signal,
|
||||
sources,
|
||||
stream,
|
||||
transcriptionModel,
|
||||
visionModel,
|
||||
}) {
|
||||
return fetch(`${apiBase}/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
session_id: sessionId,
|
||||
model,
|
||||
message,
|
||||
enriched_message: enrichedMessage,
|
||||
stream,
|
||||
sources: sources || [],
|
||||
attachments,
|
||||
vision_model: visionModel || null,
|
||||
transcription_model: transcriptionModel || null,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
export function postRegenerateMessage({
|
||||
apiBase,
|
||||
enrichedMessage,
|
||||
index,
|
||||
model,
|
||||
sessionId,
|
||||
signal,
|
||||
sources,
|
||||
stream,
|
||||
transcriptionModel,
|
||||
visionModel,
|
||||
}) {
|
||||
return fetch(`${apiBase}/sessions/${sessionId}/regenerate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
signal,
|
||||
body: JSON.stringify({
|
||||
index,
|
||||
model,
|
||||
stream,
|
||||
enriched_message: enrichedMessage,
|
||||
sources: sources || [],
|
||||
vision_model: visionModel || null,
|
||||
transcription_model: transcriptionModel || null,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
export function requestGeneratedTitle({ apiBase, message, model, sessionId }) {
|
||||
return fetch(`${apiBase}/generate-title`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
session_id: sessionId,
|
||||
message,
|
||||
model,
|
||||
}),
|
||||
})
|
||||
}
|
||||
735
src/chatGeneration.js
Normal file
735
src/chatGeneration.js
Normal file
@@ -0,0 +1,735 @@
|
||||
import { flushSync } from 'react-dom'
|
||||
import { attachmentIsImage, getAttachmentDisplayName } from './attachments'
|
||||
import { getErrorText, isAbortError, readBackendErrorText } from './backendApi'
|
||||
import {
|
||||
fetchWebSearchContext,
|
||||
postChatMessage,
|
||||
postRegenerateMessage,
|
||||
requestGeneratedTitle,
|
||||
} from './chatApi'
|
||||
import { sanitizeChatTitle } from './chatText'
|
||||
import { createWorkflowRun, streamWorkflowEvents } from './workflows/workflowApi'
|
||||
|
||||
function messageHasImageAttachments(message) {
|
||||
return Array.isArray(message?.attachments) && message.attachments.some(attachmentIsImage)
|
||||
}
|
||||
|
||||
function buildAttachmentTitleSeed(text, attachments = []) {
|
||||
const trimmed = String(text || '').trim()
|
||||
if (trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
const firstAttachment = Array.isArray(attachments) ? attachments[0] : null
|
||||
const firstName = getAttachmentDisplayName(firstAttachment, '')
|
||||
return firstName || 'Attachment'
|
||||
}
|
||||
|
||||
function setAssistantMessageContent(setChatSessions, sessionId, messageId, content, options = {}) {
|
||||
const { removeIfEmpty = false } = options
|
||||
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session => {
|
||||
if (session.session_id !== sessionId) return session
|
||||
|
||||
const nextMessages = []
|
||||
for (const message of session.messages || []) {
|
||||
if (message.id !== messageId) {
|
||||
nextMessages.push(message)
|
||||
continue
|
||||
}
|
||||
|
||||
if (removeIfEmpty && !content) continue
|
||||
nextMessages.push({ ...message, content })
|
||||
}
|
||||
|
||||
return { ...session, messages: nextMessages }
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
export function createChatGenerationHandlers({
|
||||
activeSessionId,
|
||||
activeSessionIdRef,
|
||||
backendApiUrl,
|
||||
attachWorkflowRunToRequest,
|
||||
beginCancelableRequest,
|
||||
canAttachImages,
|
||||
chatSessions,
|
||||
composerAttachments,
|
||||
createNewChat,
|
||||
finishCancelableRequest,
|
||||
getChatWorkflowForSession,
|
||||
imageAttachmentUnavailableReason,
|
||||
input,
|
||||
isSending,
|
||||
model,
|
||||
onMessagesPersisted,
|
||||
onWorkflowRunEvent,
|
||||
restoredForRef,
|
||||
scrollMessageToTop,
|
||||
scrollToBottom,
|
||||
searxEngines,
|
||||
searxUrl,
|
||||
setChatSessions,
|
||||
setComposerAttachments,
|
||||
setInput,
|
||||
setIsAttachmentMenuOpen,
|
||||
setNewMsgTip,
|
||||
setPendingScrollToLastUser,
|
||||
setUnreadSessions,
|
||||
setUserScrolledUp,
|
||||
streamOutput,
|
||||
transcriptionModel,
|
||||
userScrolledUpRef,
|
||||
visionModel,
|
||||
webSearchEnabled,
|
||||
workflowRouterModel,
|
||||
workflowSelectionMode,
|
||||
}) {
|
||||
function getEffectiveWorkflowSelection(sessionId) {
|
||||
if (workflowSelectionMode !== 'manual') {
|
||||
return { mode: 'automatic', workflowId: null }
|
||||
}
|
||||
const selection = getChatWorkflowForSession?.(sessionId)
|
||||
if (selection?.mode === 'explicit') {
|
||||
return selection
|
||||
}
|
||||
return { mode: 'direct', workflowId: null }
|
||||
}
|
||||
|
||||
async function executeWorkflowRun({
|
||||
sessionId,
|
||||
userMessage,
|
||||
attachments,
|
||||
requestController,
|
||||
selection,
|
||||
workflowRevisionId = null,
|
||||
regenerateIndex = null,
|
||||
isNewChat = false,
|
||||
}) {
|
||||
const created = await createWorkflowRun(backendApiUrl, {
|
||||
session_id: sessionId,
|
||||
message: userMessage.content,
|
||||
model,
|
||||
selection_mode: selection.mode,
|
||||
workflow_id: selection.workflowId || null,
|
||||
workflow_revision_id: workflowRevisionId,
|
||||
web_search_enabled: Boolean(webSearchEnabled),
|
||||
searx_url: searxUrl || null,
|
||||
searx_engines: searxEngines || [],
|
||||
attachments,
|
||||
vision_model: visionModel || null,
|
||||
transcription_model: transcriptionModel || null,
|
||||
router_model: workflowRouterModel || null,
|
||||
regenerate_index: regenerateIndex,
|
||||
stream: true,
|
||||
}, requestController.signal)
|
||||
attachWorkflowRunToRequest?.(requestController, created.run_id)
|
||||
const assistantMsgId = `workflow-${created.run_id}`
|
||||
let fullReply = ''
|
||||
setChatSessions(previous => previous.map(session => session.session_id === sessionId
|
||||
? { ...session, messages: [...(session.messages || []), {
|
||||
role: 'assistant', content: '', id: assistantMsgId, sources: [],
|
||||
workflow_id: created.workflow?.id,
|
||||
workflow_revision_id: created.workflow?.revision_id,
|
||||
workflow_run_id: created.run_id,
|
||||
}] }
|
||||
: session))
|
||||
onWorkflowRunEvent?.(sessionId, {
|
||||
type: 'client_run_started',
|
||||
run_id: created.run_id,
|
||||
payload: { workflow: created.workflow },
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
await streamWorkflowEvents(backendApiUrl, created.run_id, {
|
||||
signal: requestController.signal,
|
||||
onEvent: event => {
|
||||
onWorkflowRunEvent?.(sessionId, event)
|
||||
if (event.type === 'model_token') {
|
||||
fullReply += event.payload?.text || ''
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, fullReply)
|
||||
} else if (event.type === 'run_completed') {
|
||||
const finalOutput = event.payload?.output || null
|
||||
const content = finalOutput?.content || fullReply
|
||||
setChatSessions(previous => previous.map(session => {
|
||||
if (session.session_id !== sessionId) return session
|
||||
return {
|
||||
...session,
|
||||
messages: (session.messages || []).map(message => message.id === assistantMsgId
|
||||
? { ...message, content, sources: finalOutput?.sources || message.sources || [] }
|
||||
: message),
|
||||
}
|
||||
}))
|
||||
} else if (event.type === 'run_failed') {
|
||||
const message = event.payload?.message || 'Workflow execution failed.'
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, `Error: ${message}`)
|
||||
} else if (event.type === 'run_cancelled') {
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, fullReply, { removeIfEmpty: true })
|
||||
} else if (event.type === 'run_interrupted') {
|
||||
const message = event.payload?.message || 'Workflow run was interrupted.'
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, `Error: ${message}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
if (onMessagesPersisted) await onMessagesPersisted(sessionId)
|
||||
if (activeSessionIdRef.current !== sessionId) {
|
||||
setUnreadSessions(previous => [...new Set([...previous, sessionId])])
|
||||
} else if (!userScrolledUpRef.current[sessionId]) {
|
||||
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', sessionId))
|
||||
}
|
||||
if (isNewChat) {
|
||||
requestGeneratedTitle({
|
||||
apiBase: backendApiUrl,
|
||||
message: buildAttachmentTitleSeed(userMessage.content, attachments),
|
||||
model,
|
||||
sessionId,
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const sanitizedTitle = sanitizeChatTitle(data.title)
|
||||
setChatSessions(previous => previous.map(session =>
|
||||
session.session_id === sessionId ? { ...session, name: sanitizedTitle } : session
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function regenerateFromIndex(index, overrideUserText = null) {
|
||||
const sessionId = activeSessionId
|
||||
if (isSending || !sessionId || typeof index !== 'number') return
|
||||
|
||||
const msgs = (chatSessions.find(s => s.session_id === sessionId)?.messages) || []
|
||||
let lastUserIdx = index
|
||||
for (let i = index; i >= 0; i--) {
|
||||
if (msgs[i]?.role === 'user') {
|
||||
lastUserIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
setChatSessions(prev =>
|
||||
prev.map(s => s.session_id === sessionId
|
||||
? { ...s, messages: (s.messages || []).slice(0, lastUserIdx + 1) }
|
||||
: s
|
||||
)
|
||||
)
|
||||
|
||||
const conversationNeedsVision = msgs
|
||||
.slice(0, lastUserIdx + 1)
|
||||
.some(messageHasImageAttachments)
|
||||
if (conversationNeedsVision && !canAttachImages) {
|
||||
window.alert(imageAttachmentUnavailableReason)
|
||||
return
|
||||
}
|
||||
|
||||
const requestController = beginCancelableRequest(sessionId)
|
||||
|
||||
if (getChatWorkflowForSession) {
|
||||
try {
|
||||
const currentSelection = getEffectiveWorkflowSelection(sessionId)
|
||||
const originalAssistant = msgs.slice(lastUserIdx + 1).find(message => message?.role === 'assistant')
|
||||
const originalWorkflowId = originalAssistant?.workflow_id || null
|
||||
const originalSelectionMode = originalAssistant?.agent_summary?.selection_mode || null
|
||||
let selection = currentSelection
|
||||
let workflowRevisionId = null
|
||||
if (currentSelection.mode === 'automatic' && originalSelectionMode === 'automatic' && originalWorkflowId) {
|
||||
selection = { mode: 'explicit', workflowId: originalWorkflowId }
|
||||
workflowRevisionId = originalAssistant?.workflow_revision_id || null
|
||||
} else if (
|
||||
originalWorkflowId
|
||||
&& (
|
||||
(currentSelection.mode === 'explicit' && originalSelectionMode === 'explicit' && currentSelection.workflowId === originalWorkflowId)
|
||||
|| (currentSelection.mode === 'direct' && originalSelectionMode === 'direct')
|
||||
)
|
||||
) {
|
||||
workflowRevisionId = originalAssistant?.workflow_revision_id || null
|
||||
}
|
||||
await executeWorkflowRun({
|
||||
sessionId,
|
||||
userMessage: { ...msgs[lastUserIdx], content: overrideUserText ?? msgs[lastUserIdx]?.content ?? '' },
|
||||
attachments: msgs[lastUserIdx]?.attachments || [],
|
||||
requestController,
|
||||
selection,
|
||||
workflowRevisionId,
|
||||
regenerateIndex: lastUserIdx,
|
||||
})
|
||||
} catch (error) {
|
||||
if (!isAbortError(error)) console.error('Failed to regenerate workflow response:', error)
|
||||
} finally {
|
||||
finishCancelableRequest(requestController)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let enrichedPrompt = overrideUserText != null ? overrideUserText : (msgs[lastUserIdx]?.content || '')
|
||||
let citationSources = []
|
||||
const contextBlocks = []
|
||||
try {
|
||||
const promptText = overrideUserText != null ? overrideUserText : (msgs[lastUserIdx]?.content || '')
|
||||
const hasPromptText = Boolean((promptText || '').trim())
|
||||
|
||||
if (hasPromptText && webSearchEnabled) {
|
||||
try {
|
||||
const historyForSearch = msgs
|
||||
.slice(Math.max(0, lastUserIdx - 7), lastUserIdx + 1)
|
||||
.map(m => ({ role: m.role, content: m.content || '' }))
|
||||
if (historyForSearch.length > 0) {
|
||||
historyForSearch[historyForSearch.length - 1] = { role: 'user', content: promptText }
|
||||
}
|
||||
|
||||
const searchContext = await fetchWebSearchContext({
|
||||
apiBase: backendApiUrl,
|
||||
engines: searxEngines,
|
||||
historyLimit: 8,
|
||||
messages: historyForSearch,
|
||||
model,
|
||||
prompt: promptText,
|
||||
searxUrl,
|
||||
signal: requestController.signal,
|
||||
})
|
||||
if (searchContext.contextBlock) {
|
||||
contextBlocks.push(searchContext.contextBlock)
|
||||
}
|
||||
if (Array.isArray(searchContext.sources)) {
|
||||
citationSources.push(...searchContext.sources)
|
||||
}
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) throw error
|
||||
console.warn('web search enrichment (regenerate) failed', error)
|
||||
}
|
||||
}
|
||||
|
||||
citationSources = [...new Set(citationSources)]
|
||||
if (hasPromptText && contextBlocks.length > 0) {
|
||||
enrichedPrompt = `${promptText}\n\n${contextBlocks.join('\n\n')}`
|
||||
} else {
|
||||
enrichedPrompt = null
|
||||
}
|
||||
|
||||
if (streamOutput) {
|
||||
const assistantMsgId = `msg-${Date.now()}-${Math.random()}`
|
||||
let full = ''
|
||||
|
||||
setChatSessions(prev =>
|
||||
prev.map(s => s.session_id === sessionId
|
||||
? { ...s, messages: [...(s.messages || []), { id: assistantMsgId, role: 'assistant', content: '', sources: citationSources }] }
|
||||
: s
|
||||
)
|
||||
)
|
||||
|
||||
try {
|
||||
const res = await postRegenerateMessage({
|
||||
apiBase: backendApiUrl,
|
||||
enrichedMessage: enrichedPrompt,
|
||||
index,
|
||||
model,
|
||||
sessionId,
|
||||
signal: requestController.signal,
|
||||
sources: citationSources || [],
|
||||
stream: true,
|
||||
transcriptionModel,
|
||||
visionModel,
|
||||
})
|
||||
if (!res.ok) throw new Error(await readBackendErrorText(res))
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) throw new Error('Missing response body')
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let unreadMarked = false
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true })
|
||||
full += chunk
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, full)
|
||||
|
||||
if (!unreadMarked && activeSessionIdRef.current !== sessionId) {
|
||||
unreadMarked = true
|
||||
setPendingScrollToLastUser(prev => ({ ...prev, [sessionId]: assistantMsgId }))
|
||||
setUnreadSessions(prev => [...new Set([...prev, sessionId])])
|
||||
}
|
||||
}
|
||||
|
||||
if (activeSessionIdRef.current !== sessionId) {
|
||||
setPendingScrollToLastUser(prev => ({ ...prev, [sessionId]: assistantMsgId }))
|
||||
setUnreadSessions(prev => [...new Set([...prev, sessionId])])
|
||||
} else if (!userScrolledUpRef.current[sessionId]) {
|
||||
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', sessionId))
|
||||
} else {
|
||||
setNewMsgTip(prev => ({ ...prev, [sessionId]: assistantMsgId }))
|
||||
}
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) {
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, full, { removeIfEmpty: true })
|
||||
return
|
||||
}
|
||||
|
||||
console.error(error)
|
||||
setAssistantMessageContent(setChatSessions, sessionId, assistantMsgId, `Error: ${getErrorText(error)}`, { removeIfEmpty: true })
|
||||
return
|
||||
}
|
||||
} else {
|
||||
const res = await postRegenerateMessage({
|
||||
apiBase: backendApiUrl,
|
||||
enrichedMessage: enrichedPrompt,
|
||||
index,
|
||||
model,
|
||||
sessionId,
|
||||
signal: requestController.signal,
|
||||
sources: citationSources || [],
|
||||
stream: false,
|
||||
transcriptionModel,
|
||||
visionModel,
|
||||
})
|
||||
if (!res.ok) throw new Error(await readBackendErrorText(res))
|
||||
|
||||
const data = await res.json()
|
||||
const assistantMsgId = `msg-${Date.now()}`
|
||||
setChatSessions(prev =>
|
||||
prev.map(s => s.session_id === sessionId
|
||||
? { ...s, messages: [...(s.messages || []), { role: 'assistant', content: data.reply, id: assistantMsgId, sources: citationSources }] }
|
||||
: s
|
||||
)
|
||||
)
|
||||
|
||||
if (activeSessionIdRef.current !== sessionId) {
|
||||
setPendingScrollToLastUser(prev => ({ ...prev, [sessionId]: assistantMsgId }))
|
||||
setUnreadSessions(prev => [...new Set([...prev, sessionId])])
|
||||
} else if (!userScrolledUpRef.current[sessionId]) {
|
||||
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', sessionId))
|
||||
} else {
|
||||
setNewMsgTip(prev => ({ ...prev, [sessionId]: assistantMsgId }))
|
||||
}
|
||||
}
|
||||
if (onMessagesPersisted) void onMessagesPersisted(sessionId)
|
||||
} catch (error) {
|
||||
if (!isAbortError(error)) {
|
||||
console.error(error)
|
||||
}
|
||||
} finally {
|
||||
finishCancelableRequest(requestController)
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const trimmedInput = input.trim()
|
||||
if (isSending || (!trimmedInput && composerAttachments.length === 0) || !model) return
|
||||
if (composerAttachments.some(attachmentIsImage) && !canAttachImages) {
|
||||
window.alert(imageAttachmentUnavailableReason)
|
||||
return
|
||||
}
|
||||
|
||||
let targetSessionId = activeSessionId
|
||||
let isNewChat = false
|
||||
if (!targetSessionId) {
|
||||
const newSession = await createNewChat()
|
||||
await new Promise(resolve => setTimeout(resolve, 200))
|
||||
targetSessionId = newSession.session_id
|
||||
isNewChat = true
|
||||
} else {
|
||||
const currentSession = chatSessions.find(s => s.session_id === targetSessionId)
|
||||
isNewChat = currentSession && currentSession.name === "New Chat" && currentSession.messages.length === 0
|
||||
}
|
||||
|
||||
const existingMessages = (chatSessions.find(s => s.session_id === targetSessionId)?.messages) || []
|
||||
const outgoingAttachments = composerAttachments.map(({ id, ...attachment }) => ({ ...attachment }))
|
||||
const historyNeedsVision = existingMessages.some(messageHasImageAttachments)
|
||||
if (historyNeedsVision && !canAttachImages) {
|
||||
window.alert(imageAttachmentUnavailableReason)
|
||||
return
|
||||
}
|
||||
const composerSnapshot = input
|
||||
const attachmentSnapshot = composerAttachments.map(attachment => ({ ...attachment }))
|
||||
const userMsg = {
|
||||
role: 'user',
|
||||
content: trimmedInput,
|
||||
attachments: outgoingAttachments,
|
||||
id: `msg-${Date.now()}-${Math.random()}`,
|
||||
}
|
||||
setIsAttachmentMenuOpen(false)
|
||||
setUserScrolledUp(targetSessionId, false)
|
||||
|
||||
if (activeSessionIdRef.current === targetSessionId) {
|
||||
restoredForRef.current = activeSessionIdRef.current
|
||||
}
|
||||
|
||||
flushSync(() => {
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId
|
||||
? { ...session, messages: [...(session.messages || []), userMsg] }
|
||||
: session
|
||||
)
|
||||
)
|
||||
setInput('')
|
||||
setComposerAttachments([])
|
||||
})
|
||||
requestAnimationFrame(() => scrollToBottom('auto', targetSessionId))
|
||||
|
||||
const requestController = beginCancelableRequest(targetSessionId)
|
||||
try {
|
||||
if (getChatWorkflowForSession) {
|
||||
const selection = getEffectiveWorkflowSelection(targetSessionId)
|
||||
await executeWorkflowRun({
|
||||
sessionId: targetSessionId,
|
||||
userMessage: userMsg,
|
||||
attachments: outgoingAttachments,
|
||||
requestController,
|
||||
selection,
|
||||
isNewChat,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
let historyForSearch = []
|
||||
if (userMsg.content) try {
|
||||
const existing = (chatSessions.find(s => s.session_id === targetSessionId)?.messages) || []
|
||||
const lastFew = existing.slice(-8).map(m => ({ role: m.role, content: m.content || '' }))
|
||||
historyForSearch = [...lastFew, { role: 'user', content: userMsg.content }]
|
||||
} catch {}
|
||||
|
||||
let enrichedPrompt = userMsg.content || null
|
||||
let citationSources = []
|
||||
const contextBlocks = []
|
||||
|
||||
if (userMsg.content && webSearchEnabled) {
|
||||
try {
|
||||
const searchContext = await fetchWebSearchContext({
|
||||
apiBase: backendApiUrl,
|
||||
engines: searxEngines,
|
||||
historyLimit: 8,
|
||||
messages: historyForSearch,
|
||||
model,
|
||||
prompt: userMsg.content,
|
||||
searxUrl,
|
||||
signal: requestController.signal,
|
||||
})
|
||||
if (searchContext.contextBlock) {
|
||||
contextBlocks.push(searchContext.contextBlock)
|
||||
}
|
||||
if (Array.isArray(searchContext.sources)) {
|
||||
citationSources.push(...searchContext.sources)
|
||||
}
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) throw error
|
||||
console.warn('web search enrichment failed', error)
|
||||
}
|
||||
}
|
||||
|
||||
citationSources = [...new Set(citationSources)]
|
||||
if (userMsg.content && contextBlocks.length > 0) {
|
||||
enrichedPrompt = `${userMsg.content}\n\n${contextBlocks.join('\n\n')}`
|
||||
}
|
||||
|
||||
if (streamOutput) {
|
||||
const assistantMsgId = `msg-${Date.now()}-${Math.random()}`
|
||||
let fullReply = ''
|
||||
const assistantMsg = { role: 'assistant', content: '', id: assistantMsgId, sources: citationSources }
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId
|
||||
? { ...session, messages: [...(session.messages || []), assistantMsg] }
|
||||
: session
|
||||
)
|
||||
)
|
||||
|
||||
try {
|
||||
const res = await postChatMessage({
|
||||
apiBase: backendApiUrl,
|
||||
attachments: outgoingAttachments,
|
||||
enrichedMessage: userMsg.content && contextBlocks.length > 0 ? enrichedPrompt : null,
|
||||
message: userMsg.content,
|
||||
model,
|
||||
sessionId: targetSessionId,
|
||||
signal: requestController.signal,
|
||||
sources: citationSources || [],
|
||||
stream: true,
|
||||
transcriptionModel,
|
||||
visionModel,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const error = new Error(await readBackendErrorText(res))
|
||||
error.status = res.status
|
||||
throw error
|
||||
}
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) throw new Error('Missing response body')
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let pendingMarked = false
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) {
|
||||
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply)
|
||||
|
||||
if (activeSessionIdRef.current === targetSessionId) {
|
||||
if (!userScrolledUpRef.current[targetSessionId]) {
|
||||
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', targetSessionId))
|
||||
} else {
|
||||
setNewMsgTip(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
|
||||
}
|
||||
} else {
|
||||
setPendingScrollToLastUser(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
|
||||
setUnreadSessions(prev => [...new Set([...prev, targetSessionId])])
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true })
|
||||
fullReply += chunk
|
||||
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply)
|
||||
|
||||
if (activeSessionIdRef.current === targetSessionId && !userScrolledUpRef.current[targetSessionId]) {
|
||||
scrollToBottom('auto', targetSessionId)
|
||||
}
|
||||
if (activeSessionIdRef.current !== targetSessionId && !pendingMarked) {
|
||||
setPendingScrollToLastUser(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
|
||||
pendingMarked = true
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) {
|
||||
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply, { removeIfEmpty: true })
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Failed to send message:', error)
|
||||
if (Number(error?.status) >= 400 && Number(error?.status) < 500) {
|
||||
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, fullReply, { removeIfEmpty: true })
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId
|
||||
? {
|
||||
...session,
|
||||
messages: (session.messages || []).filter(message => message.id !== userMsg.id),
|
||||
}
|
||||
: session
|
||||
)
|
||||
)
|
||||
setInput(composerSnapshot)
|
||||
setComposerAttachments(attachmentSnapshot)
|
||||
window.alert(getErrorText(error))
|
||||
return
|
||||
}
|
||||
setAssistantMessageContent(setChatSessions, targetSessionId, assistantMsgId, 'Error: ' + getErrorText(error), { removeIfEmpty: true })
|
||||
return
|
||||
}
|
||||
} else {
|
||||
const res = await postChatMessage({
|
||||
apiBase: backendApiUrl,
|
||||
attachments: outgoingAttachments,
|
||||
enrichedMessage: userMsg.content && contextBlocks.length > 0 ? enrichedPrompt : null,
|
||||
message: userMsg.content,
|
||||
model,
|
||||
sessionId: targetSessionId,
|
||||
signal: requestController.signal,
|
||||
sources: citationSources || [],
|
||||
stream: false,
|
||||
transcriptionModel,
|
||||
visionModel,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const error = new Error(await readBackendErrorText(res))
|
||||
error.status = res.status
|
||||
throw error
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
const assistantMsgId = `msg-${Date.now()}`
|
||||
const assistantMsg = {
|
||||
role: 'assistant',
|
||||
content: data.reply,
|
||||
id: assistantMsgId,
|
||||
sources: citationSources,
|
||||
}
|
||||
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId
|
||||
? { ...session, messages: [...(session.messages || []), assistantMsg] }
|
||||
: session
|
||||
)
|
||||
)
|
||||
|
||||
if (assistantMsgId) {
|
||||
if (activeSessionIdRef.current === targetSessionId) {
|
||||
if (!userScrolledUpRef.current[targetSessionId]) {
|
||||
requestAnimationFrame(() => scrollMessageToTop(assistantMsgId, 'smooth', targetSessionId))
|
||||
} else {
|
||||
setNewMsgTip(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
|
||||
}
|
||||
} else {
|
||||
setPendingScrollToLastUser(prev => ({ ...prev, [targetSessionId]: assistantMsgId }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (activeSessionIdRef.current !== targetSessionId) {
|
||||
setUnreadSessions(prev => [...new Set([...prev, targetSessionId])])
|
||||
}
|
||||
if (onMessagesPersisted) void onMessagesPersisted(targetSessionId)
|
||||
|
||||
if (isNewChat) {
|
||||
requestGeneratedTitle({
|
||||
apiBase: backendApiUrl,
|
||||
message: buildAttachmentTitleSeed(userMsg.content, outgoingAttachments),
|
||||
model,
|
||||
sessionId: targetSessionId,
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const sanitizedTitle = sanitizeChatTitle(data.title)
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId ? { ...session, name: sanitizedTitle } : session
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) {
|
||||
finishCancelableRequest(requestController)
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Failed to send message:', error)
|
||||
if (Number(error?.status) >= 400 && Number(error?.status) < 500) {
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId
|
||||
? {
|
||||
...session,
|
||||
messages: (session.messages || []).filter(message => message.id !== userMsg.id),
|
||||
}
|
||||
: session
|
||||
)
|
||||
)
|
||||
setInput(composerSnapshot)
|
||||
setComposerAttachments(attachmentSnapshot)
|
||||
window.alert(getErrorText(error))
|
||||
return
|
||||
}
|
||||
const errorMsg = { role: 'assistant', content: 'Error: ' + getErrorText(error), id: `msg-${Date.now()}-${Math.random()}` }
|
||||
setChatSessions(prevSessions =>
|
||||
prevSessions.map(session =>
|
||||
session.session_id === targetSessionId
|
||||
? { ...session, messages: [...session.messages, errorMsg] }
|
||||
: session
|
||||
)
|
||||
)
|
||||
} finally {
|
||||
finishCancelableRequest(requestController)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
regenerateFromIndex,
|
||||
sendMessage,
|
||||
}
|
||||
}
|
||||
124
src/chatText.js
Normal file
124
src/chatText.js
Normal file
@@ -0,0 +1,124 @@
|
||||
export function sanitizeChatTitle(title) {
|
||||
let cleanedTitle = String(title || '')
|
||||
.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '')
|
||||
.trim()
|
||||
|
||||
let previousTitle = null
|
||||
while (cleanedTitle && cleanedTitle !== previousTitle) {
|
||||
previousTitle = cleanedTitle
|
||||
cleanedTitle = cleanedTitle
|
||||
.replace(/^\s*#+\s*/, '')
|
||||
.replace(/^\s*\*{1,2}\s*/, '')
|
||||
.replace(/\s*\*{1,2}\s*$/, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
return cleanedTitle.replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
function appendOllamaErrorHint(text, marker, block) {
|
||||
if (text.includes(marker)) {
|
||||
return text
|
||||
}
|
||||
return `${text}\n\n${block}`
|
||||
}
|
||||
|
||||
export function enrichOllamaErrorText(text) {
|
||||
const raw = String(text || '')
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed) {
|
||||
return raw
|
||||
}
|
||||
|
||||
const lower = trimmed.toLowerCase()
|
||||
const looksLikeOllamaError = (
|
||||
lower.startsWith('error:') ||
|
||||
lower.startsWith('ollama error:') ||
|
||||
lower.includes("client error '") ||
|
||||
lower.includes("server error '") ||
|
||||
(lower.includes('http') && lower.includes('error')) ||
|
||||
lower.includes('unknown model architecture') ||
|
||||
lower.includes('out of memory')
|
||||
)
|
||||
|
||||
if (!looksLikeOllamaError) {
|
||||
return raw
|
||||
}
|
||||
|
||||
if (lower.includes('unknown model architecture')) {
|
||||
return appendOllamaErrorHint(
|
||||
raw,
|
||||
'[ERROR - Unsupported Model]',
|
||||
'[ERROR - Unsupported Model]\nThis Ollama version does not support the model.\nUpdate Ollama.'
|
||||
)
|
||||
}
|
||||
if (lower.includes('out of memory')) {
|
||||
return appendOllamaErrorHint(
|
||||
raw,
|
||||
'[ERROR - Out of Memory]',
|
||||
'[ERROR - Out of Memory]\nThe model is too large for available memory.\nUse a smaller or quantized model.'
|
||||
)
|
||||
}
|
||||
if (lower.includes('502')) {
|
||||
return appendOllamaErrorHint(
|
||||
raw,
|
||||
'[ERROR 502 - Bad Gateway]',
|
||||
'[ERROR 502 - Bad Gateway]\nOllama did not return a valid response.\nTry restarting or updating Ollama.'
|
||||
)
|
||||
}
|
||||
if (lower.includes('500')) {
|
||||
return appendOllamaErrorHint(
|
||||
raw,
|
||||
'[ERROR 500 - Internal Server Error]',
|
||||
"[ERROR 500 - Internal Server Error]\nOllama crashed while processing the request.\nCheck 'ollama logs' and memory usage."
|
||||
)
|
||||
}
|
||||
if (lower.includes('404')) {
|
||||
return appendOllamaErrorHint(
|
||||
raw,
|
||||
'[ERROR 404 - Not Found]',
|
||||
"[ERROR 404 - Not Found]\nThe model or endpoint was not found.\nCheck the model name or run 'ollama pull <model>'."
|
||||
)
|
||||
}
|
||||
if (lower.includes('400')) {
|
||||
return appendOllamaErrorHint(
|
||||
raw,
|
||||
'[ERROR 400 - Bad Request]',
|
||||
'[ERROR 400 - Bad Request]\nThe request sent to Ollama was invalid.\nCheck parameters or payload format.'
|
||||
)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
export function splitThinkBlocks(text) {
|
||||
if (!text) return { think: null, answer: '' }
|
||||
|
||||
const openTagRe = /<think(?:ing)?>/i
|
||||
const closeTagRe = /<\/think(?:ing)?>/i
|
||||
|
||||
const openMatch = text.match(openTagRe)
|
||||
|
||||
if (!openMatch) {
|
||||
return { think: null, answer: text }
|
||||
}
|
||||
|
||||
const openTagIndex = openMatch.index
|
||||
const openTagLength = openMatch[0].length
|
||||
|
||||
const answerPartBeforeThink = text.substring(0, openTagIndex).trim()
|
||||
const contentAfterOpenTag = text.substring(openTagIndex + openTagLength)
|
||||
|
||||
const closeMatch = contentAfterOpenTag.match(closeTagRe)
|
||||
|
||||
let thinkInner = null
|
||||
let finalAnswer = answerPartBeforeThink
|
||||
|
||||
if (closeMatch) {
|
||||
thinkInner = contentAfterOpenTag.substring(0, closeMatch.index).trim()
|
||||
finalAnswer += contentAfterOpenTag.substring(closeMatch.index + closeMatch[0].length)
|
||||
} else {
|
||||
thinkInner = contentAfterOpenTag.trim()
|
||||
}
|
||||
|
||||
return { think: thinkInner || null, answer: finalAnswer.trim() }
|
||||
}
|
||||
@@ -1,5 +1,18 @@
|
||||
const colorSchemes = {
|
||||
'Nightsky': {
|
||||
Default: {
|
||||
'--bg': '#0b1020',
|
||||
'--panel': '#141b34',
|
||||
'--text': '#e6e8ef',
|
||||
'--muted': '#9aa3b2',
|
||||
'--accent': '#6ea8fe',
|
||||
'--border': '#24304f',
|
||||
'--input-bg': '#121933',
|
||||
'--user-msg-bg': '#18213d',
|
||||
'--assistant-msg-bg': '#10172d',
|
||||
'--active-bg': 'rgba(110, 168, 254, 0.16)',
|
||||
'--hover-bg': 'rgba(255, 255, 255, 0.06)',
|
||||
},
|
||||
Nightsky: {
|
||||
'--bg': '#0a0e1a',
|
||||
'--panel': '#18203a',
|
||||
'--text': '#ffffff',
|
||||
@@ -12,7 +25,7 @@ const colorSchemes = {
|
||||
'--active-bg': 'rgba(74, 144, 226, 0.15)',
|
||||
'--hover-bg': 'rgba(255, 255, 255, 0.05)',
|
||||
},
|
||||
'Grayscale': {
|
||||
Grayscale: {
|
||||
'--bg': '#1a1a1a',
|
||||
'--panel': '#2a2a2a',
|
||||
'--text': '#f0f0f0',
|
||||
@@ -25,20 +38,20 @@ const colorSchemes = {
|
||||
'--active-bg': 'rgba(136, 136, 136, 0.15)',
|
||||
'--hover-bg': 'rgba(255, 255, 255, 0.05)',
|
||||
},
|
||||
'Japan': {
|
||||
Japan: {
|
||||
'--bg': '#ffffff',
|
||||
'--panel': '#f5f5f5',
|
||||
'--text': '#000000',
|
||||
'--muted': '#444444',
|
||||
'--accent': '#e74c3c', /* Vibrant Red */
|
||||
'--accent': '#e74c3c',
|
||||
'--border': '#999999',
|
||||
'--input-bg': '#ffffff',
|
||||
'--user-msg-bg': '#f0f0f0',
|
||||
'--assistant-msg-bg': '#f0f0f0',
|
||||
'--active-bg': 'rgba(231, 76, 60, 0.15)', /* Light red for active */
|
||||
'--hover-bg': 'rgba(231, 76, 60, 0.08)', /* Lighter red for hover */
|
||||
'--active-bg': 'rgba(231, 76, 60, 0.15)',
|
||||
'--hover-bg': 'rgba(231, 76, 60, 0.08)',
|
||||
},
|
||||
'Lime': {
|
||||
Lime: {
|
||||
'--bg': '#f0fff0',
|
||||
'--panel': '#e0ffe0',
|
||||
'--text': '#1a1a1a',
|
||||
@@ -51,7 +64,7 @@ const colorSchemes = {
|
||||
'--active-bg': 'rgba(104, 159, 56, 0.2)',
|
||||
'--hover-bg': 'rgba(104, 159, 56, 0.1)',
|
||||
},
|
||||
'Vampire': {
|
||||
Vampire: {
|
||||
'--bg': '#1a050a',
|
||||
'--panel': '#2a1015',
|
||||
'--text': '#ffefff',
|
||||
@@ -64,15 +77,80 @@ const colorSchemes = {
|
||||
'--active-bg': 'rgba(216, 27, 96, 0.15)',
|
||||
'--hover-bg': 'rgba(255, 255, 255, 0.05)',
|
||||
},
|
||||
};
|
||||
'Sunset Drive': {
|
||||
'--bg': '#1f1024',
|
||||
'--panel': '#2e1632',
|
||||
'--text': '#fff2ea',
|
||||
'--muted': '#caa8b7',
|
||||
'--accent': '#ff8a5b',
|
||||
'--border': '#593050',
|
||||
'--input-bg': '#26132a',
|
||||
'--user-msg-bg': '#442038',
|
||||
'--assistant-msg-bg': '#32172c',
|
||||
'--active-bg': 'rgba(255, 138, 91, 0.18)',
|
||||
'--hover-bg': 'rgba(255, 138, 91, 0.08)',
|
||||
},
|
||||
'Aurora Pulse': {
|
||||
'--bg': '#07171d',
|
||||
'--panel': '#102730',
|
||||
'--text': '#eafcff',
|
||||
'--muted': '#9bc8cf',
|
||||
'--accent': '#54f2c2',
|
||||
'--border': '#214853',
|
||||
'--input-bg': '#0b2028',
|
||||
'--user-msg-bg': '#12313d',
|
||||
'--assistant-msg-bg': '#0f2530',
|
||||
'--active-bg': 'rgba(84, 242, 194, 0.18)',
|
||||
'--hover-bg': 'rgba(84, 242, 194, 0.08)',
|
||||
},
|
||||
'Sakura Neon': {
|
||||
'--bg': '#160b1d',
|
||||
'--panel': '#251331',
|
||||
'--text': '#fff5fd',
|
||||
'--muted': '#d4abc7',
|
||||
'--accent': '#ff4fb6',
|
||||
'--border': '#52315f',
|
||||
'--input-bg': '#1d1027',
|
||||
'--user-msg-bg': '#341844',
|
||||
'--assistant-msg-bg': '#281534',
|
||||
'--active-bg': 'rgba(255, 79, 182, 0.18)',
|
||||
'--hover-bg': 'rgba(255, 79, 182, 0.09)',
|
||||
},
|
||||
'Cobalt Punch': {
|
||||
'--bg': '#081527',
|
||||
'--panel': '#102643',
|
||||
'--text': '#eef6ff',
|
||||
'--muted': '#9fb7d0',
|
||||
'--accent': '#ffb703',
|
||||
'--border': '#234164',
|
||||
'--input-bg': '#0d1f37',
|
||||
'--user-msg-bg': '#162f54',
|
||||
'--assistant-msg-bg': '#102640',
|
||||
'--active-bg': 'rgba(255, 183, 3, 0.18)',
|
||||
'--hover-bg': 'rgba(255, 183, 3, 0.08)',
|
||||
},
|
||||
'Mango Mojito': {
|
||||
'--bg': '#fff7ea',
|
||||
'--panel': '#ffe9c8',
|
||||
'--text': '#2a1c13',
|
||||
'--muted': '#7c6150',
|
||||
'--accent': '#ff6b35',
|
||||
'--border': '#e6bf91',
|
||||
'--input-bg': '#fffdf9',
|
||||
'--user-msg-bg': '#fff0d7',
|
||||
'--assistant-msg-bg': '#fff8ed',
|
||||
'--active-bg': 'rgba(255, 107, 53, 0.14)',
|
||||
'--hover-bg': 'rgba(255, 107, 53, 0.08)',
|
||||
},
|
||||
}
|
||||
|
||||
function applyColorScheme(schemeName) {
|
||||
const scheme = colorSchemes[schemeName];
|
||||
if (scheme) {
|
||||
for (const [key, value] of Object.entries(scheme)) {
|
||||
document.documentElement.style.setProperty(key, value);
|
||||
}
|
||||
const scheme = colorSchemes[schemeName] || colorSchemes.Default
|
||||
if (!scheme) return
|
||||
|
||||
for (const [key, value] of Object.entries(scheme)) {
|
||||
document.documentElement.style.setProperty(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
export { colorSchemes, applyColorScheme };
|
||||
export { colorSchemes, applyColorScheme }
|
||||
|
||||
176
src/desktop/desktopApi.js
Normal file
176
src/desktop/desktopApi.js
Normal file
@@ -0,0 +1,176 @@
|
||||
import { DEFAULT_BACKEND_API_URL } from '../appConfig'
|
||||
|
||||
const DEFAULT_SETTINGS = Object.freeze({
|
||||
backendApiUrl: DEFAULT_BACKEND_API_URL,
|
||||
ollamaApiUrl: 'http://127.0.0.1:11434',
|
||||
chatModel: 'llama3',
|
||||
visionModel: '',
|
||||
embedModel: 'nomic-embed-text:latest',
|
||||
rerankModel: 'nomic-embed-text:latest',
|
||||
transcriptionModel: 'base',
|
||||
workflowRouterModel: '',
|
||||
autoDeepEnrichment: true,
|
||||
colorScheme: 'Default',
|
||||
uiScale: 1,
|
||||
openDevToolsOnStartup: false,
|
||||
audioInputEnabled: true,
|
||||
audioInputDeviceId: '',
|
||||
audioInputLanguage: '',
|
||||
})
|
||||
|
||||
const DEFAULT_UPDATE_STATUS = Object.freeze({
|
||||
state: 'unavailable',
|
||||
message: 'Desktop update checks are not available in this runtime.',
|
||||
checkedAt: null,
|
||||
localCommit: null,
|
||||
remoteCommit: null,
|
||||
branch: null,
|
||||
restartScheduled: false,
|
||||
})
|
||||
|
||||
const DEFAULT_UI_SCALE = 1
|
||||
const MIN_UI_SCALE = 0.7
|
||||
const MAX_UI_SCALE = 1.3
|
||||
|
||||
const hasWindow = () => typeof window !== 'undefined'
|
||||
const getTauriCore = () => (hasWindow() ? window.__TAURI__?.core : undefined)
|
||||
const getTauriEvent = () => (hasWindow() ? window.__TAURI__?.event : undefined)
|
||||
const tauriWindowFocusUnlisteners = new WeakMap()
|
||||
|
||||
function callTauriCommand(commandName, args = {}) {
|
||||
const invoke = getTauriCore()?.invoke
|
||||
if (typeof invoke !== 'function') {
|
||||
return undefined
|
||||
}
|
||||
return invoke(commandName, args)
|
||||
}
|
||||
|
||||
function fallbackPromise(value) {
|
||||
return Promise.resolve(typeof value === 'function' ? value() : value)
|
||||
}
|
||||
|
||||
function defaultSettings() {
|
||||
return { ...DEFAULT_SETTINGS }
|
||||
}
|
||||
|
||||
function normalizeUiScale(value) {
|
||||
const numericValue = Number(value)
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
return DEFAULT_UI_SCALE
|
||||
}
|
||||
|
||||
return Math.min(MAX_UI_SCALE, Math.max(MIN_UI_SCALE, Math.round(numericValue * 100) / 100))
|
||||
}
|
||||
|
||||
function applyRendererUiScale(value) {
|
||||
if (!hasWindow() || !window.document) {
|
||||
return false
|
||||
}
|
||||
|
||||
const scale = normalizeUiScale(value)
|
||||
const root = window.document.documentElement
|
||||
const body = window.document.body
|
||||
|
||||
root?.style?.setProperty('--heimgeist-ui-scale', String(scale))
|
||||
if (body?.style) {
|
||||
body.style.zoom = scale === DEFAULT_UI_SCALE ? '' : String(scale)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function defaultUpdateStatus(message = DEFAULT_UPDATE_STATUS.message) {
|
||||
return { ...DEFAULT_UPDATE_STATUS, message }
|
||||
}
|
||||
|
||||
function defaultChangelogPage(page = 1) {
|
||||
const normalizedPage = Number.isFinite(Number(page)) && Number(page) > 0 ? Number(page) : 1
|
||||
return {
|
||||
page: normalizedPage,
|
||||
pageSize: 50,
|
||||
hasMore: false,
|
||||
entries: [],
|
||||
}
|
||||
}
|
||||
|
||||
function resultOrFallback(result, fallback) {
|
||||
return result === undefined ? fallbackPromise(fallback) : result
|
||||
}
|
||||
|
||||
function getExternalUrl(eventOrUrl) {
|
||||
if (typeof eventOrUrl === 'string') {
|
||||
return eventOrUrl
|
||||
}
|
||||
return eventOrUrl?.currentTarget?.href || eventOrUrl?.target?.href || ''
|
||||
}
|
||||
|
||||
function listenForTauriWindowFocus(callback) {
|
||||
const listen = getTauriEvent()?.listen
|
||||
if (typeof listen !== 'function') {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const unlistenPromise = listen('window-focused', () => callback())
|
||||
tauriWindowFocusUnlisteners.set(callback, unlistenPromise)
|
||||
return unlistenPromise
|
||||
}
|
||||
|
||||
function unlistenForTauriWindowFocus(callback) {
|
||||
const unlistenPromise = tauriWindowFocusUnlisteners.get(callback)
|
||||
if (!unlistenPromise) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
tauriWindowFocusUnlisteners.delete(callback)
|
||||
Promise.resolve(unlistenPromise).then((unlisten) => {
|
||||
if (typeof unlisten === 'function') {
|
||||
unlisten()
|
||||
}
|
||||
})
|
||||
return unlistenPromise
|
||||
}
|
||||
|
||||
const desktopApi = {
|
||||
getSettings: () => resultOrFallback(
|
||||
callTauriCommand('get_settings'),
|
||||
defaultSettings,
|
||||
),
|
||||
applyUiScale: (value) => applyRendererUiScale(value),
|
||||
getUpdateStatus: () => resultOrFallback(
|
||||
callTauriCommand('get_update_status'),
|
||||
defaultUpdateStatus,
|
||||
),
|
||||
checkForUpdates: () => resultOrFallback(
|
||||
callTauriCommand('check_for_updates'),
|
||||
() => defaultUpdateStatus('Desktop update checks are not implemented in this runtime.'),
|
||||
),
|
||||
getChangelogPage: (page) => resultOrFallback(
|
||||
callTauriCommand('get_changelog_page', { page }),
|
||||
() => defaultChangelogPage(page),
|
||||
),
|
||||
setSetting: (key, value) => resultOrFallback(
|
||||
callTauriCommand('set_setting', { key, value }),
|
||||
false,
|
||||
),
|
||||
updateSettings: (settings) => resultOrFallback(
|
||||
callTauriCommand('update_settings', { settings }),
|
||||
false,
|
||||
),
|
||||
pickPaths: (options) => resultOrFallback(
|
||||
callTauriCommand('pick_paths', { options }),
|
||||
[],
|
||||
),
|
||||
openPath: (filePath) => resultOrFallback(
|
||||
callTauriCommand('open_path', { filePath }),
|
||||
false,
|
||||
),
|
||||
openExternalLink: (eventOrUrl) => {
|
||||
eventOrUrl?.preventDefault?.()
|
||||
const url = getExternalUrl(eventOrUrl)
|
||||
return resultOrFallback(callTauriCommand('open_external_link', { url }), false)
|
||||
},
|
||||
onWindowFocus: (callback) => listenForTauriWindowFocus(callback),
|
||||
offWindowFocus: (callback) => unlistenForTauriWindowFocus(callback),
|
||||
}
|
||||
|
||||
export default desktopApi
|
||||
@@ -5,13 +5,13 @@ import { HashRouter as Router, Routes, Route } from 'react-router-dom'
|
||||
import App from './App.jsx'
|
||||
import './styles.css'
|
||||
import { applyColorScheme } from './colorSchemes'
|
||||
import desktopApi from './desktop/desktopApi'
|
||||
|
||||
function Main() {
|
||||
useEffect(() => {
|
||||
window.electronAPI.getSettings().then(settings => {
|
||||
if (settings.colorScheme) {
|
||||
applyColorScheme(settings.colorScheme)
|
||||
}
|
||||
desktopApi.getSettings().then(settings => {
|
||||
applyColorScheme(settings.colorScheme || 'Default')
|
||||
desktopApi.applyUiScale(settings.uiScale)
|
||||
})
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ export function markdownToHTML(text) {
|
||||
// </think> or </thinking> tag is found, OR the end of the string ($).
|
||||
text = text.replace(/<think(?:ing)?>[\s\S]*?(?:<\/think(?:ing)?>|$)/gi, '');
|
||||
|
||||
text = balanceStreamingCodeFence(text);
|
||||
|
||||
// 1) Normalize line endings
|
||||
let tmp = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||
|
||||
@@ -164,4 +166,45 @@ export function markdownToHTML(text) {
|
||||
.replace(/(<div class="codeblock"[^>]*>[\s\S]*?<\/div>)\s*<br>/g, "$1"); // <br> right after closing
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
// Virtually close an unfinished fenced code block so it renders during streaming.
|
||||
function balanceStreamingCodeFence(md) {
|
||||
// Split into lines; we only consider fences that start a line.
|
||||
const lines = md.split(/\r?\n/);
|
||||
|
||||
// Track the last unmatched opening fence we see while scanning.
|
||||
// { fenceChar: '`' or '~', fenceLen: number }
|
||||
let open = null;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
// Opening fence? ^\s*([`~]{3,})(.*)$
|
||||
if (!open) {
|
||||
const m = line.match(/^\s*([`~]{3,})([^\s]*)?.*$/);
|
||||
if (m) {
|
||||
// Treat as an opening fence
|
||||
open = { fenceChar: m[1][0], fenceLen: m[1].length };
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// Closing fence: must match same char and length or longer
|
||||
const re = new RegExp(`^\\s*(${open.fenceChar}{${open.fenceLen},})\\s*$`);
|
||||
if (re.test(line)) {
|
||||
// Closed
|
||||
open = null;
|
||||
continue;
|
||||
}
|
||||
// Otherwise still inside the code block; keep scanning
|
||||
}
|
||||
}
|
||||
|
||||
if (open) {
|
||||
// Virtually close with the same fence so the block renders now
|
||||
const virtual = `${open.fenceChar.repeat(open.fenceLen)}`;
|
||||
return md.endsWith('\n') ? md + virtual : md + '\n' + virtual;
|
||||
}
|
||||
|
||||
return md;
|
||||
}
|
||||
13
src/modelPicker.js
Normal file
13
src/modelPicker.js
Normal file
@@ -0,0 +1,13 @@
|
||||
export function buildModelPickerOptions(values, currentValue, missingLabel) {
|
||||
const uniqueValues = [...new Set((Array.isArray(values) ? values : []).filter(Boolean))]
|
||||
const options = uniqueValues.map(value => ({ value, label: value }))
|
||||
|
||||
if (currentValue && !uniqueValues.includes(currentValue)) {
|
||||
options.unshift({
|
||||
value: currentValue,
|
||||
label: `${currentValue} (${missingLabel})`,
|
||||
})
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
1825
src/styles.css
1825
src/styles.css
File diff suppressed because it is too large
Load Diff
327
src/useAudioInput.js
Normal file
327
src/useAudioInput.js
Normal file
@@ -0,0 +1,327 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { readFileAsDataUrl } from './attachments'
|
||||
import {
|
||||
AUDIO_RECORDING_TICK_MS,
|
||||
MAX_AUDIO_RECORDING_MS,
|
||||
} from './appConfig'
|
||||
import { expectBackendJson, getErrorText, isAbortError } from './backendApi'
|
||||
import {
|
||||
getAudioInputConstraints,
|
||||
getPreferredAudioRecorderMimeType,
|
||||
stopMediaStream,
|
||||
supportsAudioInputCapture,
|
||||
} from './audioInput'
|
||||
|
||||
function appendTranscriptToComposer(currentInput, transcript) {
|
||||
const nextTranscript = String(transcript || '').trim()
|
||||
if (!nextTranscript) {
|
||||
return currentInput || ''
|
||||
}
|
||||
|
||||
const existing = String(currentInput || '')
|
||||
if (!existing.trim()) {
|
||||
return nextTranscript
|
||||
}
|
||||
|
||||
const separator = /[\s\n]$/.test(existing) ? '' : '\n'
|
||||
return `${existing}${separator}${nextTranscript}`
|
||||
}
|
||||
|
||||
export function formatRecordingDuration(milliseconds) {
|
||||
const totalSeconds = Math.max(0, Math.floor(Number(milliseconds || 0) / 1000))
|
||||
const minutes = Math.floor(totalSeconds / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function useAudioInput({
|
||||
activeSidebarMode,
|
||||
audioInputDeviceId,
|
||||
audioInputEnabled,
|
||||
audioInputLanguage,
|
||||
backendApiUrl,
|
||||
isSending,
|
||||
setInput,
|
||||
textareaRef,
|
||||
transcriptionModel,
|
||||
}) {
|
||||
const [audioInputRuntimeReady, setAudioInputRuntimeReady] = useState(true)
|
||||
const [audioInputRuntimeMessage, setAudioInputRuntimeMessage] = useState('')
|
||||
const [isRecordingAudio, setIsRecordingAudio] = useState(false)
|
||||
const [isTranscribingAudio, setIsTranscribingAudio] = useState(false)
|
||||
const [audioRecordingMs, setAudioRecordingMs] = useState(0)
|
||||
const audioRecorderRef = useRef(null)
|
||||
const audioStreamRef = useRef(null)
|
||||
const audioChunksRef = useRef([])
|
||||
const audioStopPromiseRef = useRef(null)
|
||||
const audioRecorderMimeTypeRef = useRef('')
|
||||
const audioTickTimerRef = useRef(null)
|
||||
const audioAutoStopTimerRef = useRef(null)
|
||||
const audioStartedAtRef = useRef(0)
|
||||
const audioTranscriptionAbortRef = useRef(null)
|
||||
|
||||
function syncAudioInputRuntimeFromStartupStatus(status) {
|
||||
const whisperReady = Boolean(status?.whisper_model_available)
|
||||
if (whisperReady) {
|
||||
setAudioInputRuntimeReady(true)
|
||||
setAudioInputRuntimeMessage('')
|
||||
return
|
||||
}
|
||||
|
||||
const modelName = status?.whisper_model || 'base'
|
||||
const reason = String(status?.whisper_error || '').trim()
|
||||
setAudioInputRuntimeReady(false)
|
||||
setAudioInputRuntimeMessage(reason || `Whisper ${modelName} is not available.`)
|
||||
}
|
||||
|
||||
function clearAudioTimers() {
|
||||
if (audioTickTimerRef.current) {
|
||||
window.clearInterval(audioTickTimerRef.current)
|
||||
audioTickTimerRef.current = null
|
||||
}
|
||||
if (audioAutoStopTimerRef.current) {
|
||||
window.clearTimeout(audioAutoStopTimerRef.current)
|
||||
audioAutoStopTimerRef.current = null
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupAudioRecorder(stream = audioStreamRef.current) {
|
||||
clearAudioTimers()
|
||||
stopMediaStream(stream)
|
||||
if (audioStreamRef.current === stream) {
|
||||
audioStreamRef.current = null
|
||||
}
|
||||
audioRecorderRef.current = null
|
||||
}
|
||||
|
||||
async function transcribeRecordedAudio(blob, mimeType) {
|
||||
if (!backendApiUrl) {
|
||||
throw new Error('The Heimgeist backend is not configured.')
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
audioTranscriptionAbortRef.current = controller
|
||||
setIsTranscribingAudio(true)
|
||||
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(blob)
|
||||
const commaIndex = dataUrl.indexOf(',')
|
||||
if (commaIndex <= 5) {
|
||||
throw new Error('Recorded audio could not be encoded for upload.')
|
||||
}
|
||||
const header = dataUrl.slice(0, commaIndex)
|
||||
const payload = dataUrl.slice(commaIndex + 1)
|
||||
if (!/^data:[^,]+;base64$/i.test(header) || !payload) {
|
||||
throw new Error('Recorded audio could not be encoded for upload.')
|
||||
}
|
||||
const detectedMimeType = header
|
||||
.slice(5)
|
||||
.replace(/;base64$/i, '')
|
||||
.trim()
|
||||
|
||||
const response = await fetch(`${backendApiUrl}/audio/transcribe`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
mime_type: mimeType || detectedMimeType || 'audio/webm',
|
||||
audio_base64: payload,
|
||||
model: transcriptionModel || null,
|
||||
language: audioInputLanguage || null,
|
||||
}),
|
||||
})
|
||||
const data = await expectBackendJson(response)
|
||||
const transcript = String(data?.text || '').trim()
|
||||
|
||||
if (!transcript) {
|
||||
window.alert('No speech was detected. Try again and speak closer to the selected microphone.')
|
||||
return
|
||||
}
|
||||
|
||||
setInput(prev => appendTranscriptToComposer(prev, transcript))
|
||||
requestAnimationFrame(() => textareaRef.current?.focus())
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) {
|
||||
return
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
if (audioTranscriptionAbortRef.current === controller) {
|
||||
audioTranscriptionAbortRef.current = null
|
||||
}
|
||||
setIsTranscribingAudio(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAudioRecording(options = {}) {
|
||||
const { shouldTranscribe = true } = options
|
||||
const recorder = audioRecorderRef.current
|
||||
const stopPromise = audioStopPromiseRef.current
|
||||
const mimeType = audioRecorderMimeTypeRef.current || recorder?.mimeType || 'audio/webm'
|
||||
|
||||
if (!recorder || !stopPromise) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsRecordingAudio(false)
|
||||
clearAudioTimers()
|
||||
|
||||
try {
|
||||
if (recorder.state !== 'inactive') {
|
||||
recorder.stop()
|
||||
}
|
||||
|
||||
const blob = await stopPromise
|
||||
if (!shouldTranscribe) {
|
||||
return
|
||||
}
|
||||
if (!blob || blob.size <= 0) {
|
||||
throw new Error('Recorded audio was empty.')
|
||||
}
|
||||
await transcribeRecordedAudio(blob, mimeType)
|
||||
} catch (error) {
|
||||
if (shouldTranscribe) {
|
||||
console.error('Failed to stop microphone recording', error)
|
||||
window.alert(`Microphone transcription failed: ${getErrorText(error)}`)
|
||||
}
|
||||
} finally {
|
||||
audioStopPromiseRef.current = null
|
||||
audioChunksRef.current = []
|
||||
audioRecorderMimeTypeRef.current = ''
|
||||
audioStartedAtRef.current = 0
|
||||
setAudioRecordingMs(0)
|
||||
}
|
||||
}
|
||||
|
||||
async function startAudioRecording() {
|
||||
if (!audioInputEnabled || !audioInputRuntimeReady || isRecordingAudio || isTranscribingAudio || isSending) {
|
||||
return
|
||||
}
|
||||
if (!supportsAudioInputCapture()) {
|
||||
window.alert('Microphone capture is not available in this environment.')
|
||||
return
|
||||
}
|
||||
|
||||
let stream = null
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia(getAudioInputConstraints(audioInputDeviceId))
|
||||
} catch (error) {
|
||||
console.error('Failed to access microphone', error)
|
||||
window.alert(`Microphone access failed: ${getErrorText(error)}`)
|
||||
return
|
||||
}
|
||||
|
||||
const preferredMimeType = getPreferredAudioRecorderMimeType()
|
||||
let recorder = null
|
||||
try {
|
||||
recorder = preferredMimeType
|
||||
? new MediaRecorder(stream, { mimeType: preferredMimeType })
|
||||
: new MediaRecorder(stream)
|
||||
} catch (error) {
|
||||
cleanupAudioRecorder(stream)
|
||||
console.error('Failed to create audio recorder', error)
|
||||
window.alert(`Microphone recording is not available: ${getErrorText(error)}`)
|
||||
return
|
||||
}
|
||||
|
||||
audioStreamRef.current = stream
|
||||
audioRecorderRef.current = recorder
|
||||
audioChunksRef.current = []
|
||||
audioRecorderMimeTypeRef.current = recorder.mimeType || preferredMimeType || 'audio/webm'
|
||||
audioStartedAtRef.current = Date.now()
|
||||
setAudioRecordingMs(0)
|
||||
setIsRecordingAudio(true)
|
||||
|
||||
recorder.ondataavailable = (event) => {
|
||||
if (event.data && event.data.size > 0) {
|
||||
audioChunksRef.current.push(event.data)
|
||||
}
|
||||
}
|
||||
|
||||
audioStopPromiseRef.current = new Promise((resolve, reject) => {
|
||||
recorder.onstop = () => {
|
||||
const blob = new Blob(audioChunksRef.current, {
|
||||
type: recorder.mimeType || audioRecorderMimeTypeRef.current || 'audio/webm',
|
||||
})
|
||||
cleanupAudioRecorder(stream)
|
||||
resolve(blob)
|
||||
}
|
||||
recorder.onerror = (event) => {
|
||||
cleanupAudioRecorder(stream)
|
||||
reject(event?.error || new Error('Audio recording failed.'))
|
||||
}
|
||||
})
|
||||
|
||||
audioTickTimerRef.current = window.setInterval(() => {
|
||||
setAudioRecordingMs(Date.now() - audioStartedAtRef.current)
|
||||
}, AUDIO_RECORDING_TICK_MS)
|
||||
audioAutoStopTimerRef.current = window.setTimeout(() => {
|
||||
stopAudioRecording()
|
||||
}, MAX_AUDIO_RECORDING_MS)
|
||||
|
||||
recorder.start()
|
||||
}
|
||||
|
||||
async function toggleAudioRecording() {
|
||||
if (isTranscribingAudio) {
|
||||
return
|
||||
}
|
||||
if (isRecordingAudio) {
|
||||
await stopAudioRecording()
|
||||
return
|
||||
}
|
||||
await startAudioRecording()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (audioInputEnabled || !isRecordingAudio) {
|
||||
return
|
||||
}
|
||||
stopAudioRecording({ shouldTranscribe: false })
|
||||
}, [audioInputEnabled, isRecordingAudio])
|
||||
|
||||
useEffect(() => {
|
||||
if (audioInputRuntimeReady || !isRecordingAudio) {
|
||||
return
|
||||
}
|
||||
stopAudioRecording({ shouldTranscribe: false })
|
||||
}, [audioInputRuntimeReady, isRecordingAudio])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeSidebarMode === 'chats' || !isRecordingAudio) {
|
||||
return
|
||||
}
|
||||
stopAudioRecording()
|
||||
}, [activeSidebarMode, isRecordingAudio])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
audioTranscriptionAbortRef.current?.abort()
|
||||
clearAudioTimers()
|
||||
const recorder = audioRecorderRef.current
|
||||
if (recorder) {
|
||||
recorder.ondataavailable = null
|
||||
recorder.onstop = null
|
||||
recorder.onerror = null
|
||||
try {
|
||||
if (recorder.state !== 'inactive') {
|
||||
recorder.stop()
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
stopMediaStream(audioStreamRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return {
|
||||
audioInputRuntimeMessage,
|
||||
audioInputRuntimeReady,
|
||||
audioRecordingMs,
|
||||
isRecordingAudio,
|
||||
isTranscribingAudio,
|
||||
setAudioInputRuntimeMessage,
|
||||
setAudioInputRuntimeReady,
|
||||
syncAudioInputRuntimeFromStartupStatus,
|
||||
toggleAudioRecording,
|
||||
}
|
||||
}
|
||||
249
src/useChatScroll.js
Normal file
249
src/useChatScroll.js
Normal file
@@ -0,0 +1,249 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { BOTTOM_EPSILON, TOP_ALIGN_OFFSET } from './appConfig'
|
||||
import desktopApi from './desktop/desktopApi'
|
||||
|
||||
export function useChatScroll({
|
||||
activeSessionId,
|
||||
activeSidebarMode,
|
||||
chatRef,
|
||||
messagesLength,
|
||||
}) {
|
||||
const [scrollPositions, setScrollPositions] = useState({})
|
||||
const [userScrolledUpState, setUserScrolledUpState] = useState({})
|
||||
const userScrolledUpRef = useRef({})
|
||||
const [pendingScrollToLastUser, setPendingScrollToLastUser] = useState({})
|
||||
const scrollTopsRef = useRef({})
|
||||
const prevScrollTopsRef = useRef({})
|
||||
const [newMsgTip, setNewMsgTip] = useState({})
|
||||
const restoredForRef = useRef(null)
|
||||
const activeSessionIdRef = useRef(activeSessionId)
|
||||
|
||||
useEffect(() => {
|
||||
activeSessionIdRef.current = activeSessionId
|
||||
}, [activeSessionId])
|
||||
|
||||
const setUserScrolledUp = useCallback((sessionId, value) => {
|
||||
setUserScrolledUpState(prev => {
|
||||
const next = { ...prev, [sessionId]: value }
|
||||
userScrolledUpRef.current = next
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const leavingSessionId = activeSessionId
|
||||
const leavingMode = activeSidebarMode
|
||||
|
||||
return () => {
|
||||
if (leavingMode === 'chats' && leavingSessionId) {
|
||||
const top = typeof scrollTopsRef.current[leavingSessionId] === 'number'
|
||||
? scrollTopsRef.current[leavingSessionId]
|
||||
: (chatRef.current ? chatRef.current.scrollTop : 0)
|
||||
|
||||
setScrollPositions(prev => {
|
||||
const updated = { ...prev, [leavingSessionId]: top }
|
||||
desktopApi.updateSettings({ scrollPositions: updated })
|
||||
return updated
|
||||
})
|
||||
}
|
||||
}
|
||||
}, [activeSessionId, activeSidebarMode, chatRef])
|
||||
|
||||
useEffect(() => {
|
||||
const chatDiv = chatRef.current
|
||||
if (!chatDiv) return
|
||||
|
||||
const handleScroll = () => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = chatDiv
|
||||
const isAtBottom = (scrollHeight - scrollTop - clientHeight) <= BOTTOM_EPSILON
|
||||
|
||||
if (activeSessionId) {
|
||||
const prevScrollTop = prevScrollTopsRef.current[activeSessionId]
|
||||
const scrolledUp = typeof prevScrollTop === 'number' && scrollTop < prevScrollTop
|
||||
|
||||
scrollTopsRef.current[activeSessionId] = scrollTop
|
||||
|
||||
if (isAtBottom) {
|
||||
setUserScrolledUp(activeSessionId, false)
|
||||
} else if (scrolledUp) {
|
||||
setUserScrolledUp(activeSessionId, true)
|
||||
}
|
||||
prevScrollTopsRef.current[activeSessionId] = scrollTop
|
||||
}
|
||||
}
|
||||
|
||||
chatDiv.addEventListener('scroll', handleScroll)
|
||||
return () => chatDiv.removeEventListener('scroll', handleScroll)
|
||||
}, [activeSessionId, chatRef, setUserScrolledUp])
|
||||
|
||||
useEffect(() => {
|
||||
const sid = activeSessionId
|
||||
if (!sid) return
|
||||
if (userScrolledUpState[sid] === false) {
|
||||
setNewMsgTip(prev => {
|
||||
if (!(sid in prev)) return prev
|
||||
const rest = { ...prev }
|
||||
delete rest[sid]
|
||||
return rest
|
||||
})
|
||||
}
|
||||
}, [activeSessionId, userScrolledUpState])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (activeSidebarMode !== 'chats' || !activeSessionId) return
|
||||
|
||||
const div = chatRef.current
|
||||
if (!div) return
|
||||
|
||||
restoredForRef.current = null
|
||||
|
||||
const applyRestore = () => {
|
||||
if (restoredForRef.current === activeSessionId) return
|
||||
|
||||
const liveSaved = typeof scrollTopsRef.current[activeSessionId] === 'number'
|
||||
? scrollTopsRef.current[activeSessionId]
|
||||
: undefined
|
||||
const saved = typeof liveSaved === 'number'
|
||||
? liveSaved
|
||||
: scrollPositions[activeSessionId]
|
||||
|
||||
if (typeof saved === 'number') {
|
||||
div.scrollTop = saved
|
||||
restoredForRef.current = activeSessionId
|
||||
return
|
||||
}
|
||||
if (messagesLength > 0) {
|
||||
div.scrollTop = div.scrollHeight
|
||||
restoredForRef.current = activeSessionId
|
||||
}
|
||||
}
|
||||
|
||||
applyRestore()
|
||||
const r0 = requestAnimationFrame(applyRestore)
|
||||
|
||||
const onDomChange = () => {
|
||||
if (restoredForRef.current !== activeSessionId) {
|
||||
requestAnimationFrame(applyRestore)
|
||||
}
|
||||
}
|
||||
|
||||
const mo = new MutationObserver(onDomChange)
|
||||
mo.observe(div, { childList: true, subtree: true })
|
||||
|
||||
const ro = new ResizeObserver(onDomChange)
|
||||
ro.observe(div)
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(r0)
|
||||
mo.disconnect()
|
||||
ro.disconnect()
|
||||
}
|
||||
}, [activeSessionId, activeSidebarMode, chatRef, messagesLength, scrollPositions])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeSidebarMode !== 'chats' || !activeSessionId) return
|
||||
if (restoredForRef.current === activeSessionId) return
|
||||
|
||||
const liveSaved = typeof scrollTopsRef.current[activeSessionId] === 'number'
|
||||
? scrollTopsRef.current[activeSessionId]
|
||||
: undefined
|
||||
const savedScrollTop = typeof liveSaved === 'number'
|
||||
? liveSaved
|
||||
: scrollPositions[activeSessionId]
|
||||
|
||||
if (typeof savedScrollTop !== 'number' && messagesLength > 0) {
|
||||
requestAnimationFrame(() => {
|
||||
const div = chatRef.current
|
||||
if (!div) return
|
||||
div.scrollTop = div.scrollHeight
|
||||
restoredForRef.current = activeSessionId
|
||||
})
|
||||
}
|
||||
}, [messagesLength, activeSessionId, activeSidebarMode, chatRef, scrollPositions])
|
||||
|
||||
const scrollToBottom = useCallback((behavior = 'smooth', sessionId = null) => {
|
||||
const chatDiv = chatRef.current
|
||||
if (!chatDiv) return
|
||||
const target = sessionId ?? activeSessionIdRef.current
|
||||
if (activeSessionIdRef.current !== target) return
|
||||
chatDiv.scrollTo({ top: chatDiv.scrollHeight, behavior })
|
||||
setUserScrolledUp(target, false)
|
||||
}, [chatRef, setUserScrolledUp])
|
||||
|
||||
const scrollMessageToTop = useCallback((msgId, behavior = 'auto', sessionId = null) => {
|
||||
const chatDiv = chatRef.current
|
||||
if (!chatDiv) return
|
||||
const target = sessionId ?? activeSessionIdRef.current
|
||||
if (activeSessionIdRef.current !== target) return
|
||||
const el = document.getElementById(msgId)
|
||||
if (el) {
|
||||
const top = Math.max(0, el.offsetTop - TOP_ALIGN_OFFSET)
|
||||
chatDiv.scrollTo({ top, behavior })
|
||||
}
|
||||
}, [chatRef])
|
||||
|
||||
const handleNewMsgTipClick = useCallback(() => {
|
||||
const sid = activeSessionIdRef.current
|
||||
const msgId = newMsgTip[sid]
|
||||
if (msgId) {
|
||||
scrollMessageToTop(msgId, 'smooth', sid)
|
||||
setNewMsgTip(prev => {
|
||||
const { [sid]: _omit, ...rest } = prev
|
||||
return rest
|
||||
})
|
||||
}
|
||||
}, [newMsgTip, scrollMessageToTop])
|
||||
|
||||
const scrollPendingMessageForSession = useCallback((sessionId, chatSessions) => {
|
||||
const pendingId = pendingScrollToLastUser[sessionId]
|
||||
if (!pendingId) return
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
let tries = 12
|
||||
const attempt = () => {
|
||||
const chatDiv = chatRef.current
|
||||
if (!chatDiv) return
|
||||
|
||||
let el = document.getElementById(pendingId)
|
||||
if (!el) {
|
||||
const sess = chatSessions.find(s => s.session_id === sessionId)
|
||||
if (sess && Array.isArray(sess.messages)) {
|
||||
for (let i = sess.messages.length - 1; i >= 0; i--) {
|
||||
const m = sess.messages[i]
|
||||
if (m.role === 'assistant' && m.id) {
|
||||
el = document.getElementById(m.id)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (el) {
|
||||
scrollMessageToTop(el.id, 'smooth', sessionId)
|
||||
setPendingScrollToLastUser(prev => {
|
||||
const { [sessionId]: _omit, ...rest } = prev
|
||||
return rest
|
||||
})
|
||||
} else if (tries-- > 0) {
|
||||
requestAnimationFrame(attempt)
|
||||
}
|
||||
}
|
||||
requestAnimationFrame(attempt)
|
||||
})
|
||||
}, [chatRef, pendingScrollToLastUser, scrollMessageToTop])
|
||||
|
||||
return {
|
||||
activeSessionIdRef,
|
||||
handleNewMsgTipClick,
|
||||
newMsgTip,
|
||||
restoredForRef,
|
||||
scrollMessageToTop,
|
||||
scrollPendingMessageForSession,
|
||||
scrollToBottom,
|
||||
setNewMsgTip,
|
||||
setPendingScrollToLastUser,
|
||||
setScrollPositions,
|
||||
setUserScrolledUp,
|
||||
userScrolledUpRef,
|
||||
}
|
||||
}
|
||||
75
src/useChatWorkflowSelection.js
Normal file
75
src/useChatWorkflowSelection.js
Normal file
@@ -0,0 +1,75 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { CHAT_WORKFLOW_MAP_KEY } from './appConfig'
|
||||
|
||||
const DIRECT_SELECTION = Object.freeze({ mode: 'direct', workflowId: null })
|
||||
|
||||
function normalizeSelection(selection, validIds = null) {
|
||||
if (selection?.mode === 'explicit' && (!validIds || validIds.has(selection.workflowId))) {
|
||||
return selection
|
||||
}
|
||||
return DIRECT_SELECTION
|
||||
}
|
||||
|
||||
function loadMap() {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(CHAT_WORKFLOW_MAP_KEY) || '{}')
|
||||
return Object.fromEntries(Object.entries(raw).map(([sessionId, selection]) => [sessionId, normalizeSelection(selection)]))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export function useChatWorkflowSelection({ activeSessionId, workflows }) {
|
||||
const [selectionBySession, setSelectionBySession] = useState(loadMap)
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem(CHAT_WORKFLOW_MAP_KEY, JSON.stringify(selectionBySession))
|
||||
} catch {}
|
||||
}, [selectionBySession])
|
||||
|
||||
useEffect(() => {
|
||||
const validIds = new Set(workflows.filter(item => item.enabled).map(item => item.id))
|
||||
setSelectionBySession(previous => {
|
||||
let changed = false
|
||||
const next = { ...previous }
|
||||
Object.entries(next).forEach(([sessionId, selection]) => {
|
||||
const normalized = normalizeSelection(selection, validIds)
|
||||
if (normalized !== selection) {
|
||||
next[sessionId] = DIRECT_SELECTION
|
||||
changed = true
|
||||
}
|
||||
})
|
||||
return changed ? next : previous
|
||||
})
|
||||
}, [workflows])
|
||||
|
||||
const selection = activeSessionId
|
||||
? normalizeSelection(selectionBySession[activeSessionId])
|
||||
: DIRECT_SELECTION
|
||||
|
||||
const selectedWorkflow = useMemo(() => {
|
||||
if (selection.mode === 'direct') return workflows.find(item => item.slug === 'input-output') || null
|
||||
if (selection.mode === 'automatic') return null
|
||||
return workflows.find(item => item.id === selection.workflowId) || null
|
||||
}, [selection, workflows])
|
||||
|
||||
function getSelectionForSession(sessionId) {
|
||||
return normalizeSelection(selectionBySession[sessionId])
|
||||
}
|
||||
|
||||
function setSelectionForSession(sessionId, nextSelection) {
|
||||
if (!sessionId) return
|
||||
setSelectionBySession(previous => ({
|
||||
...previous,
|
||||
[sessionId]: normalizeSelection(nextSelection),
|
||||
}))
|
||||
}
|
||||
|
||||
return {
|
||||
getSelectionForSession,
|
||||
selectedWorkflow,
|
||||
selection,
|
||||
setSelectionForSession,
|
||||
}
|
||||
}
|
||||
72
src/websearchEngines.js
Normal file
72
src/websearchEngines.js
Normal file
@@ -0,0 +1,72 @@
|
||||
export const WEBSEARCH_ENGINE_OPTIONS = [
|
||||
{ value: 'google', label: 'Google' },
|
||||
{ value: 'bing', label: 'Bing' },
|
||||
{ value: 'yahoo', label: 'Yahoo' },
|
||||
{ value: 'duckduckgo', label: 'DuckDuckGo' },
|
||||
{ value: 'brave', label: 'Brave' },
|
||||
{ value: 'github', label: 'GitHub' },
|
||||
{ value: 'stack_overflow', label: 'Stack Overflow' },
|
||||
{ value: 'reddit', label: 'Reddit' },
|
||||
{ value: 'arxiv', label: 'arXiv' },
|
||||
]
|
||||
|
||||
export const DEFAULT_WEBSEARCH_ENGINES = [
|
||||
'google',
|
||||
'bing',
|
||||
'yahoo',
|
||||
'duckduckgo',
|
||||
'brave',
|
||||
]
|
||||
|
||||
const WEBSEARCH_ENGINE_ALIASES = {
|
||||
stackoverflow: 'stack_overflow',
|
||||
}
|
||||
|
||||
const ENGINE_ORDER = new Map(
|
||||
WEBSEARCH_ENGINE_OPTIONS.map((option, index) => [option.value, index])
|
||||
)
|
||||
|
||||
export function normalizeWebsearchEngineId(value) {
|
||||
if (typeof value !== 'string') return null
|
||||
|
||||
const trimmed = value.trim().toLowerCase()
|
||||
if (!trimmed) return null
|
||||
|
||||
const canonical = WEBSEARCH_ENGINE_ALIASES[trimmed] ?? trimmed
|
||||
return ENGINE_ORDER.has(canonical) ? canonical : null
|
||||
}
|
||||
|
||||
export function normalizeWebsearchEngines(value) {
|
||||
if (!Array.isArray(value)) return []
|
||||
|
||||
const seen = new Set()
|
||||
const normalized = []
|
||||
|
||||
for (const entry of value) {
|
||||
const canonical = normalizeWebsearchEngineId(entry)
|
||||
if (!canonical || seen.has(canonical)) continue
|
||||
seen.add(canonical)
|
||||
normalized.push(canonical)
|
||||
}
|
||||
|
||||
normalized.sort((left, right) => ENGINE_ORDER.get(left) - ENGINE_ORDER.get(right))
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function loadStoredWebsearchEngines(rawValue) {
|
||||
if (typeof rawValue !== 'string') return [...DEFAULT_WEBSEARCH_ENGINES]
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawValue)
|
||||
if (!Array.isArray(parsed)) return [...DEFAULT_WEBSEARCH_ENGINES]
|
||||
|
||||
const normalized = normalizeWebsearchEngines(parsed)
|
||||
if (parsed.length > 0 && normalized.length === 0) {
|
||||
return [...DEFAULT_WEBSEARCH_ENGINES]
|
||||
}
|
||||
|
||||
return normalized
|
||||
} catch {
|
||||
return [...DEFAULT_WEBSEARCH_ENGINES]
|
||||
}
|
||||
}
|
||||
65
src/workflows/NodeInspector.jsx
Normal file
65
src/workflows/NodeInspector.jsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import React from 'react'
|
||||
|
||||
const CONDITION_OPERATIONS = ['equals', 'not_equals', 'exists', 'greater_than', 'less_than', 'contains', 'array_not_empty', 'score_at_least']
|
||||
|
||||
export default function NodeInspector({ node, tools, onChange, onDelete, readOnly }) {
|
||||
const [configText, setConfigText] = React.useState('{}')
|
||||
const [configError, setConfigError] = React.useState('')
|
||||
|
||||
React.useEffect(() => {
|
||||
setConfigText(JSON.stringify(node?.data?.config || {}, null, 2))
|
||||
setConfigError('')
|
||||
}, [node])
|
||||
|
||||
if (!node) return <div className="workflow-inspector empty">Select a node to edit it.</div>
|
||||
const nodeType = node.data.nodeType
|
||||
const patchConfig = (config) => onChange({ ...node, data: { ...node.data, config, tool: config.tool || '' } })
|
||||
return (
|
||||
<div className="workflow-inspector">
|
||||
<div className="workflow-inspector-heading">
|
||||
<strong>{node.id}</strong>
|
||||
{!readOnly && <button type="button" className="button danger ghost" onClick={onDelete}>Delete</button>}
|
||||
</div>
|
||||
<label>Label
|
||||
<input disabled={readOnly} value={node.data.label || ''} onChange={(event) => onChange({ ...node, data: { ...node.data, label: event.target.value } })} />
|
||||
</label>
|
||||
{nodeType === 'tool' && (
|
||||
<label>Registered tool
|
||||
<select
|
||||
disabled={readOnly}
|
||||
value={node.data.config?.tool || ''}
|
||||
onChange={(event) => patchConfig({ ...node.data.config, tool: event.target.value, arguments: node.data.config?.arguments || {} })}
|
||||
>
|
||||
<option value="">Select a tool</option>
|
||||
{tools.map(tool => <option key={tool.name} value={tool.name}>{tool.name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{nodeType === 'condition' && (
|
||||
<label>Operation
|
||||
<select disabled={readOnly} value={node.data.config?.operation || 'equals'} onChange={(event) => patchConfig({ ...node.data.config, operation: event.target.value })}>
|
||||
{CONDITION_OPERATIONS.map(operation => <option key={operation}>{operation}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label>Configuration JSON
|
||||
<textarea
|
||||
rows={18}
|
||||
disabled={readOnly}
|
||||
value={configText}
|
||||
onChange={(event) => {
|
||||
const text = event.target.value
|
||||
setConfigText(text)
|
||||
try {
|
||||
patchConfig(JSON.parse(text))
|
||||
setConfigError('')
|
||||
} catch (error) {
|
||||
setConfigError(error.message)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{configError && <p className="workflow-validation-error">{configError}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
22
src/workflows/NodePalette.jsx
Normal file
22
src/workflows/NodePalette.jsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import React from 'react'
|
||||
|
||||
export const NODE_TYPES = ['input', 'output', 'tool', 'prompt', 'agent', 'condition', 'merge', 'template', 'select', 'limit']
|
||||
|
||||
export default function NodePalette({ onAdd }) {
|
||||
return (
|
||||
<div className="workflow-palette">
|
||||
<strong>Nodes</strong>
|
||||
{NODE_TYPES.map(type => (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
draggable
|
||||
onDragStart={(event) => event.dataTransfer.setData('application/heimgeist-workflow-node', type)}
|
||||
onClick={() => onAdd(type)}
|
||||
>
|
||||
{type}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
45
src/workflows/WorkflowCanvas.jsx
Normal file
45
src/workflows/WorkflowCanvas.jsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import React from 'react'
|
||||
import {
|
||||
Background,
|
||||
Controls,
|
||||
MiniMap,
|
||||
ReactFlow,
|
||||
addEdge,
|
||||
applyEdgeChanges,
|
||||
applyNodeChanges,
|
||||
} from '@xyflow/react'
|
||||
import '@xyflow/react/dist/style.css'
|
||||
import WorkflowNode from './WorkflowNode'
|
||||
|
||||
const nodeTypes = { workflow: WorkflowNode }
|
||||
|
||||
export default function WorkflowCanvas({ edges, nodes, onEdgesChange, onNodesChange, onSelectNode, onDropNode }) {
|
||||
const [instance, setInstance] = React.useState(null)
|
||||
return (
|
||||
<div className="workflow-canvas">
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
onInit={setInstance}
|
||||
onNodesChange={(changes) => onNodesChange(applyNodeChanges(changes, nodes))}
|
||||
onEdgesChange={(changes) => onEdgesChange(applyEdgeChanges(changes, edges))}
|
||||
onConnect={(connection) => onEdgesChange(addEdge({ ...connection, id: `${connection.source}-${connection.target}-${Date.now()}` }, edges))}
|
||||
onNodeClick={(_event, node) => onSelectNode(node.id)}
|
||||
onPaneClick={() => onSelectNode(null)}
|
||||
onDragOver={(event) => { event.preventDefault(); event.dataTransfer.dropEffect = 'move' }}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
const type = event.dataTransfer.getData('application/heimgeist-workflow-node')
|
||||
if (!type || !instance) return
|
||||
onDropNode(type, instance.screenToFlowPosition({ x: event.clientX, y: event.clientY }))
|
||||
}}
|
||||
fitView
|
||||
>
|
||||
<Background gap={20} />
|
||||
<MiniMap pannable zoomable />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user