mirror of
https://github.com/infiniflow/ragflow.git
synced 2025-12-08 20:42:30 +08:00
Compare commits
617 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 92a4a095c9 | |||
| 2368d738ab | |||
| 833e3a08cd | |||
| 7a73fec2e5 | |||
| 2f8e0e66ef | |||
| 5b4b252895 | |||
| 9081150c2c | |||
| cb295ec106 | |||
| 4f5210352c | |||
| f98ec9034f | |||
| 4b8ecba32b | |||
| 892166ec24 | |||
| a411330b09 | |||
| 5a8ae4a289 | |||
| 3f16377412 | |||
| d3b37b0b70 | |||
| 01db00b587 | |||
| 25f07e8e29 | |||
| daa65199e8 | |||
| fc867cb959 | |||
| fb694143ee | |||
| a8280d9fd2 | |||
| aea553c3a8 | |||
| 57237634f1 | |||
| 604061c4a5 | |||
| c103dd2746 | |||
| e82e8fde13 | |||
| a44ed9626a | |||
| ff9c11c970 | |||
| 674d342761 | |||
| a246e5644b | |||
| 96f56a3c43 | |||
| 1b2f66fc11 | |||
| ca2de896c7 | |||
| 34abcf7704 | |||
| 4c0b79c4f6 | |||
| e11a74eed5 | |||
| 297b2d0ac9 | |||
| b16f16e19e | |||
| 35598c04ce | |||
| 09d1f7f333 | |||
| 240450ea52 | |||
| 1de3032650 | |||
| 41548bf019 | |||
| b68d349bd6 | |||
| f6bfe4d970 | |||
| cb2ae708f3 | |||
| d7f26786d4 | |||
| b05fab14f7 | |||
| e6da0c7c7b | |||
| ef89e3ebea | |||
| 8ede1c7bf5 | |||
| 6363d58e98 | |||
| c262011393 | |||
| dda1367ab2 | |||
| e4c9cf2264 | |||
| e3b3ec3f79 | |||
| 08d5637770 | |||
| 7bb28ca2bd | |||
| 9251fb39af | |||
| 91dbce30bd | |||
| 949a999478 | |||
| d40041cc82 | |||
| 832c90ac3e | |||
| 7b3099b1a1 | |||
| 4681638974 | |||
| ecf441c830 | |||
| d9c2a128a5 | |||
| 38e3475714 | |||
| 90644246d6 | |||
| 100c60017f | |||
| 51dd6d1f90 | |||
| 521ea6afcb | |||
| dd019e7ba1 | |||
| db1be22a2f | |||
| 139268de6f | |||
| f6ceb43e36 | |||
| d8a43416f5 | |||
| 4a6a2a0f1b | |||
| 9bbef8216d | |||
| 78856703c4 | |||
| 099c37ba95 | |||
| a44f1f735d | |||
| ae6f68e625 | |||
| 5dd19c6a57 | |||
| 5968f148bc | |||
| 4f962d6bff | |||
| ddb8be9219 | |||
| 422c229e52 | |||
| b5d1d2fec4 | |||
| d545633a6c | |||
| af0b4b0828 | |||
| 6c6380d27a | |||
| 2324b88579 | |||
| 2b0dc01a88 | |||
| 01acc3fd5a | |||
| 2484e26cb5 | |||
| 7195742ca5 | |||
| 62cb5f1bac | |||
| e7dd487779 | |||
| e41268efc6 | |||
| 2f33ec7ad0 | |||
| 3b1375ef99 | |||
| 2c05e6e6bd | |||
| 8ccc696723 | |||
| 1621313c0f | |||
| b94c15ef1e | |||
| 8a16c8cc44 | |||
| b12a437a30 | |||
| deeb950e1c | |||
| 6a0702f55f | |||
| 3044cb85fd | |||
| d3262ca378 | |||
| 99a7c0fb97 | |||
| 7e75b9d778 | |||
| a467f31238 | |||
| 54342ae0a2 | |||
| bdcf195b20 | |||
| 3f571a13c2 | |||
| 9d4bb5767c | |||
| 5e7b93e802 | |||
| ec4def9a44 | |||
| 2bd71d722b | |||
| 8f2c0176b4 | |||
| b261b6aac0 | |||
| cbdf54cf36 | |||
| db0606e064 | |||
| cfae63d107 | |||
| 88f8c8ed86 | |||
| 4158697fe6 | |||
| 5f9cb16a3c | |||
| 4730145696 | |||
| 68d0210e92 | |||
| f8e9a0590f | |||
| ba834aee26 | |||
| 983540614e | |||
| 6722b3d558 | |||
| 6000c3e304 | |||
| 333608a1d4 | |||
| 8052cbc70e | |||
| b0e0e1fdd0 | |||
| 8e3228d461 | |||
| f789098e9f | |||
| d6e6c530d7 | |||
| 22c5affacc | |||
| 35b7d17d97 | |||
| 1fc14ff6d4 | |||
| 7fad48f42c | |||
| 77988fe3c2 | |||
| cb00f36f62 | |||
| 7edb4ad7dc | |||
| 66c54e75f3 | |||
| f60dfffb4b | |||
| f1ad778250 | |||
| 7c8f159751 | |||
| c57cc0769b | |||
| 869df1f704 | |||
| 42eeb38247 | |||
| 7241c73c7a | |||
| 336a639164 | |||
| ceae4df889 | |||
| 884dcbcb7e | |||
| 4b57177523 | |||
| 4130519599 | |||
| 0c73f77c4d | |||
| fbe68034aa | |||
| 22acd0ac67 | |||
| 4cf122c6db | |||
| 6a77c94365 | |||
| 80656309f7 | |||
| 9f7d187ab3 | |||
| 63da2cb7d5 | |||
| cb69c742b0 | |||
| 2ac72899ef | |||
| 473f9892fb | |||
| fe4b2bf969 | |||
| c18b78b261 | |||
| 8dd3adc443 | |||
| e85fea31a8 | |||
| 1aba978de2 | |||
| 7e0b3d19d6 | |||
| 788ca41d9e | |||
| 6b23308f26 | |||
| 925dd2aa85 | |||
| b5a2711c05 | |||
| c6e723f2ee | |||
| fd3e55cfcf | |||
| 6ae0da92cb | |||
| 9377192859 | |||
| 42671e08f1 | |||
| b2f87a9f8f | |||
| 878dca26bb | |||
| 445576ec88 | |||
| 04de0c4cef | |||
| 7e65df87dd | |||
| 7c98cb5075 | |||
| 6df0f44e71 | |||
| c998ad7a18 | |||
| 1dcc416c70 | |||
| 8c075f8287 | |||
| 9b90a44323 | |||
| 426fdafb66 | |||
| 02fb7a88e3 | |||
| 0fe19f3fbc | |||
| 9b4cceb3f7 | |||
| 65255f2a8e | |||
| 9dd380d474 | |||
| 0164856343 | |||
| 4f05803690 | |||
| abc32803cc | |||
| 07de36ec86 | |||
| 87a998e9e5 | |||
| 0aafa281a5 | |||
| 2871455e4e | |||
| f09b204ae4 | |||
| 5a2c542ce2 | |||
| 4d9e9f0dbb | |||
| 6d232f1bdb | |||
| 21179a9be9 | |||
| 9081bc969a | |||
| e949594579 | |||
| 1a1888ed22 | |||
| 97e4eccf03 | |||
| b10eb8d085 | |||
| 1d2c081710 | |||
| ad09d4bb24 | |||
| b9c383612d | |||
| ab9efb3c23 | |||
| 922f79e757 | |||
| c04686d426 | |||
| 9a85f83569 | |||
| 5decdde182 | |||
| def18308d0 | |||
| fc6d8ee77f | |||
| 5400467da1 | |||
| 2c771fb0b4 | |||
| 667632ba00 | |||
| a82f092dac | |||
| 742d0f0ea9 | |||
| 69bbf8e9c5 | |||
| 12975cf128 | |||
| 99993e5026 | |||
| 15b78bd894 | |||
| f8a479bf88 | |||
| f87e7242cd | |||
| fc1ac3a962 | |||
| 212bb8e601 | |||
| 06abef66ef | |||
| 0abc01311b | |||
| 1eb6286339 | |||
| 4bd6c3145c | |||
| 190e144a70 | |||
| 527ebec2f5 | |||
| a0b7c78dca | |||
| 54f7c6ea8e | |||
| f843dd05e5 | |||
| 3abc9be1c2 | |||
| e627ee9ea4 | |||
| 6c1f1a9f53 | |||
| b51237be17 | |||
| 5daed10136 | |||
| 074d4f5031 | |||
| e9f5468a49 | |||
| a2b4d0190c | |||
| c8097e97cb | |||
| fc172b4a79 | |||
| 0bea7f21ae | |||
| 61d2a74b25 | |||
| 1d88b197fb | |||
| b88c3897b9 | |||
| 2da4e7aa46 | |||
| cf038e099f | |||
| 88d52e335c | |||
| 13785edaae | |||
| 6d3e3e4e3c | |||
| 6b7c028578 | |||
| c3e344b0f1 | |||
| e9202999cb | |||
| a6d85c6c2f | |||
| 7539d142a9 | |||
| e953f01951 | |||
| eb20b60b13 | |||
| d48731ac8c | |||
| b4a5d83b44 | |||
| 99af1cbeac | |||
| 63d0b39c5c | |||
| 863cec1bad | |||
| e14e0ec695 | |||
| 6228b1bd53 | |||
| e18f407604 | |||
| 60767e66e0 | |||
| cc6a48b128 | |||
| 19396998eb | |||
| 89b05ad79f | |||
| 884fd83dc7 | |||
| c739b68b29 | |||
| 35e880c432 | |||
| 733219cc3f | |||
| 21f2c5838b | |||
| 20f3f54714 | |||
| e4765ebe0c | |||
| 3f263df3ef | |||
| 404cdc0b6d | |||
| f2c4d53c58 | |||
| 642006c8e2 | |||
| 59ba34e167 | |||
| 4580ad2fd7 | |||
| 11dd23d8aa | |||
| c5c3240c4c | |||
| 0f95086813 | |||
| 9b3f5fd38b | |||
| 6c26872799 | |||
| 85247e6837 | |||
| 17ada637db | |||
| c9d7a34690 | |||
| 96438ca821 | |||
| 7927d80a84 | |||
| be431449bd | |||
| 02985fc905 | |||
| 6f438e0a49 | |||
| 5efb3476f2 | |||
| 83c673e093 | |||
| 8d2f8ed561 | |||
| 73a03287a5 | |||
| 85f10f84bd | |||
| 9cfd521d67 | |||
| e91af1dff9 | |||
| 9065fb1050 | |||
| 99b634c68d | |||
| 79426fc41f | |||
| be5a67895e | |||
| 5a4e64e741 | |||
| 2302a6baba | |||
| a74c0ccce0 | |||
| 8e75a23ad0 | |||
| 4121636084 | |||
| 3738dd71ab | |||
| 9729ca2aed | |||
| e5caa702f5 | |||
| 644f68de97 | |||
| b4ef50bdb5 | |||
| 5b5e3677b6 | |||
| c9551b7f68 | |||
| 4810cb2dc9 | |||
| d92e927685 | |||
| 7bdd5a48c0 | |||
| d3ff1a30bf | |||
| 6acc46bc7b | |||
| ef8728a314 | |||
| 5169299826 | |||
| bd19656c8f | |||
| c59c1b603d | |||
| c9caccf354 | |||
| eedec157a7 | |||
| c6c3961250 | |||
| 6b3a40be5c | |||
| 1328d715db | |||
| a3a5a9966f | |||
| 78ed8fe9a5 | |||
| 853aa121a9 | |||
| 54fc6dcf01 | |||
| da8802d010 | |||
| d73a75506e | |||
| 13bcfd7ebd | |||
| aa8b021478 | |||
| e013ac52af | |||
| 06700850df | |||
| 7a08e91909 | |||
| 77f0fb03e3 | |||
| da2d8b8267 | |||
| b75115264d | |||
| 8badf3f423 | |||
| eb8feaf20a | |||
| 936d8ab7dd | |||
| 68d1315079 | |||
| 6baba54e9e | |||
| ad48e8d915 | |||
| cafdee536f | |||
| cd861e3653 | |||
| e9e39d57ce | |||
| 94cb66ba80 | |||
| 9a6dc89156 | |||
| fdd5b1b8cf | |||
| 827042f72b | |||
| 37be0ff3d3 | |||
| a313b77cdd | |||
| 4fecc2fae6 | |||
| ff75008801 | |||
| e3cf14a3c9 | |||
| 6529c764c9 | |||
| 44184d12a8 | |||
| 8779aa1986 | |||
| 411c645134 | |||
| afccbc88e8 | |||
| 33e78cf638 | |||
| 193aa3ba88 | |||
| ffb3fc4bf5 | |||
| 6ccfbca204 | |||
| 439da32234 | |||
| db8f83104f | |||
| f43db8bc51 | |||
| ce587cba56 | |||
| 5164835681 | |||
| c981a57616 | |||
| c7d00c2272 | |||
| aed1bbbcaa | |||
| 19ded65c66 | |||
| ad6def4178 | |||
| ed6a693820 | |||
| 1d5a9b74ff | |||
| e34817c2a9 | |||
| 60428c4ad2 | |||
| 7bc9742674 | |||
| a199572bf8 | |||
| 06dfb83529 | |||
| 3c19e3125b | |||
| 4ae9de76d4 | |||
| c55e9d16da | |||
| 4c2906d6fd | |||
| 1e2c0c6705 | |||
| ede733e130 | |||
| b67484e77d | |||
| 66e4113e0b | |||
| 0dba1743e3 | |||
| 43199c45c3 | |||
| 3fd7db40ea | |||
| 5650442b0b | |||
| 5b013da4d6 | |||
| fe797bcc66 | |||
| 9542f4484c | |||
| 2452c5624f | |||
| a5c03ccd4c | |||
| d2213141e0 | |||
| 3da3260eb5 | |||
| 07f283b73e | |||
| 29509ff69d | |||
| 216f6495c4 | |||
| f60a249fe1 | |||
| 152072f900 | |||
| 80032b1fc0 | |||
| 5d55e6a049 | |||
| 418700b455 | |||
| eea6565472 | |||
| 3f21603558 | |||
| 3a739e3dd7 | |||
| 4ba1ba973a | |||
| e8b9871fb9 | |||
| e37b0d217d | |||
| 50e9df4c76 | |||
| b9a50ef4b8 | |||
| da11a20c92 | |||
| 955619c8ac | |||
| ad2e116367 | |||
| ccbd4365be | |||
| 9169643157 | |||
| 5cff780ec4 | |||
| ceb0419fe5 | |||
| 74ebc497c1 | |||
| 161cb08bbd | |||
| ff8702f7de | |||
| a973b9e01f | |||
| 5e19423d82 | |||
| 29f7f8b81e | |||
| 6012f376ca | |||
| 8468031e39 | |||
| aac460ad29 | |||
| 753c13d76f | |||
| 0cb588f7bf | |||
| ebdd71ce68 | |||
| 013856b604 | |||
| 61096596bc | |||
| 549d67e281 | |||
| 79c873344b | |||
| 548f01850f | |||
| 3f495b2d22 | |||
| c943517932 | |||
| 935687998e | |||
| 375f621405 | |||
| a99d19bdea | |||
| 906c0c5c89 | |||
| c92d334b29 | |||
| d38f995ba6 | |||
| bc50f68127 | |||
| b24abee364 | |||
| 6fee2962cb | |||
| e67bfca552 | |||
| d5f87a5498 | |||
| d7426d86d5 | |||
| 7ca98848ac | |||
| 32d5885b68 | |||
| f4d182e4ee | |||
| 69b9581417 | |||
| 1e21056364 | |||
| fdfa5d0ad4 | |||
| d96348eb22 | |||
| 100b3165d8 | |||
| 7e60800c95 | |||
| 4b195cc14c | |||
| 7034dc8dea | |||
| 71f2ba1452 | |||
| 1ec84a589e | |||
| eb40377700 | |||
| bbf9d6d786 | |||
| 8c2b91d3db | |||
| 55028b2db7 | |||
| daf86dbf74 | |||
| b2ef6a05a1 | |||
| 6bc3a2d58a | |||
| d69f4ec829 | |||
| ef45526700 | |||
| 79034bd194 | |||
| 60356b52c6 | |||
| 80d703f9c2 | |||
| 022afbb39d | |||
| 792a1a9d91 | |||
| d2b70e73dd | |||
| 37b0829e28 | |||
| b4a281eca1 | |||
| 95821f6fb6 | |||
| bf2ea04d02 | |||
| ac7a0d4fbf | |||
| 9f109adf28 | |||
| cf12c3cc1f | |||
| 29a7b7a040 | |||
| eb42adc818 | |||
| a4d230f12b | |||
| 9352a09c53 | |||
| a0c1d83ddc | |||
| 657019a5a9 | |||
| 58df013722 | |||
| 347cb61f26 | |||
| 264303ba98 | |||
| 1c90c39897 | |||
| 3fcdba1683 | |||
| 915354bec9 | |||
| c0090a1b4f | |||
| be6d5b76c3 | |||
| fb21efd77d | |||
| cf4fff64f8 | |||
| 0b94376cd4 | |||
| 2b5812d0a9 | |||
| 4da3ee400b | |||
| f8602b5286 | |||
| fc8a752cd5 | |||
| 478cd006d6 | |||
| 4d10dbcf95 | |||
| 43cd455b52 | |||
| b54d5807f3 | |||
| 58e95f76c1 | |||
| 06fd35d420 | |||
| 4df75ca84e | |||
| 701e5be535 | |||
| 9ae57eb370 | |||
| fe5dd5b70a | |||
| 1015436691 | |||
| 83c9f1ed39 | |||
| e4f4b30ae3 | |||
| 9bf6f7c9a0 | |||
| b06957e561 | |||
| baeedc699d | |||
| 00943dc04a | |||
| f43cf7c2b0 | |||
| 9e1421b77c | |||
| 13389be3f4 | |||
| a5306e6345 | |||
| 99adeabc85 | |||
| 6a5e1d597c | |||
| 266119bf62 | |||
| 75086f41a9 | |||
| 3657b1f2a2 | |||
| 975798c643 | |||
| 607de74ace | |||
| 2a647162a8 | |||
| d4332643c4 | |||
| 2ea696934b | |||
| 5a6a34cef9 | |||
| 1daa0b4d46 | |||
| 60d406acaa | |||
| 1a6bd437f5 | |||
| 258a10fb74 | |||
| fdc21ec853 | |||
| c2693d2f46 | |||
| ca9c9c4e1e | |||
| bafe137502 | |||
| 2dea8448a6 | |||
| d9868d0229 | |||
| 38a90c32b2 | |||
| eecec7b119 | |||
| 4eeb535946 | |||
| 26de9adb41 | |||
| 0c9a7caa9d | |||
| a5a617b7a3 | |||
| d5618749c9 | |||
| de8267cfd7 | |||
| 740714b79d | |||
| 013db9410f | |||
| b96ba6f831 | |||
| d29fd52e14 | |||
| 99f7bbaaa2 | |||
| 575099df2d | |||
| ddeac9ab3d | |||
| 009e18f094 | |||
| 9c023b6d8c | |||
| 2c2b2e0779 | |||
| 8d7fb12305 | |||
| 7f4c63d102 | |||
| 3e9f444e6b | |||
| 2290c2a2f0 | |||
| dbb8f7b77b | |||
| 8964817d72 | |||
| 0b950da73f | |||
| 30b88e2b91 | |||
| fb66b1e726 | |||
| 198a8b6592 | |||
| 56e3fa2d6a | |||
| 24f9b17ff6 | |||
| 427fb97562 |
@ -1,16 +1,10 @@
|
|||||||
---
|
|
||||||
sidebar_position: 0
|
|
||||||
slug: /contribution_guidelines
|
|
||||||
---
|
|
||||||
|
|
||||||
# Contribution guidelines
|
# Contribution guidelines
|
||||||
|
|
||||||
Thanks for wanting to contribute to RAGFlow. This document offers guidlines and major considerations for submitting your contributions.
|
This document offers guidlines and major considerations for submitting your contributions to RAGFlow.
|
||||||
|
|
||||||
- To report a bug, file a [GitHub issue](https://github.com/infiniflow/ragflow/issues/new/choose) with us.
|
- To report a bug, file a [GitHub issue](https://github.com/infiniflow/ragflow/issues/new/choose) with us.
|
||||||
- For further questions, you can explore existing discussions or initiate a new one in [Discussions](https://github.com/orgs/infiniflow/discussions).
|
- For further questions, you can explore existing discussions or initiate a new one in [Discussions](https://github.com/orgs/infiniflow/discussions).
|
||||||
|
|
||||||
|
|
||||||
## What you can contribute
|
## What you can contribute
|
||||||
|
|
||||||
The list below mentions some contributions you can make, but it is not a complete list.
|
The list below mentions some contributions you can make, but it is not a complete list.
|
||||||
@ -42,6 +36,7 @@ The list below mentions some contributions you can make, but it is not a complet
|
|||||||
- Consider splitting a large PR into multiple smaller, standalone PRs to keep a traceable development history.
|
- Consider splitting a large PR into multiple smaller, standalone PRs to keep a traceable development history.
|
||||||
- Ensure that your PR addresses just one issue, or keep any unrelated changes small.
|
- Ensure that your PR addresses just one issue, or keep any unrelated changes small.
|
||||||
- Add test cases when contributing new features. They demonstrate that your code functions correctly and protect against potential issues from future changes.
|
- Add test cases when contributing new features. They demonstrate that your code functions correctly and protect against potential issues from future changes.
|
||||||
|
|
||||||
### Describing your PR
|
### Describing your PR
|
||||||
|
|
||||||
- Ensure that your PR title is concise and clear, providing all the required information.
|
- Ensure that your PR title is concise and clear, providing all the required information.
|
||||||
@ -49,4 +44,5 @@ The list below mentions some contributions you can make, but it is not a complet
|
|||||||
- Include sufficient design details for *breaking changes* or *API changes* in your description.
|
- Include sufficient design details for *breaking changes* or *API changes* in your description.
|
||||||
|
|
||||||
### Reviewing & merging a PR
|
### Reviewing & merging a PR
|
||||||
- Ensure that your PR passes all Continuous Integration (CI) tests before merging it.
|
|
||||||
|
Ensure that your PR passes all Continuous Integration (CI) tests before merging it.
|
||||||
110
Dockerfile
110
Dockerfile
@ -1,22 +1,108 @@
|
|||||||
FROM infiniflow/ragflow-base:v2.0
|
# base stage
|
||||||
USER root
|
FROM ubuntu:24.04 AS base
|
||||||
|
USER root
|
||||||
|
|
||||||
|
ENV LIGHTEN=0
|
||||||
|
|
||||||
WORKDIR /ragflow
|
WORKDIR /ragflow
|
||||||
|
|
||||||
ADD ./web ./web
|
RUN rm -f /etc/apt/apt.conf.d/docker-clean \
|
||||||
RUN cd ./web && npm i --force && npm run build
|
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
|
||||||
|
|
||||||
ADD ./api ./api
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
ADD ./conf ./conf
|
apt update && apt-get --no-install-recommends install -y ca-certificates
|
||||||
ADD ./deepdoc ./deepdoc
|
|
||||||
ADD ./rag ./rag
|
# if you located in China, you can use tsinghua mirror to speed up apt
|
||||||
ADD ./graph ./graph
|
RUN sed -i 's|http://archive.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/ubuntu.sources
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt install -y curl libpython3-dev nginx libglib2.0-0 libglx-mesa0 pkg-config libicu-dev libgdiplus \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
|
||||||
|
RUN curl -o libssl1.deb http://archive.ubuntu.com/ubuntu/pool/main/o/openssl1.0/libssl1.0.0_1.0.2n-1ubuntu5_amd64.deb && dpkg -i libssl1.deb && rm -f libssl1.deb
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
|
||||||
|
|
||||||
|
# Configure Poetry
|
||||||
|
ENV POETRY_NO_INTERACTION=1
|
||||||
|
ENV POETRY_VIRTUALENVS_IN_PROJECT=true
|
||||||
|
ENV POETRY_VIRTUALENVS_CREATE=true
|
||||||
|
ENV POETRY_REQUESTS_TIMEOUT=15
|
||||||
|
|
||||||
|
# builder stage
|
||||||
|
FROM base AS builder
|
||||||
|
USER root
|
||||||
|
|
||||||
|
WORKDIR /ragflow
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt install -y nodejs npm cargo && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY web web
|
||||||
|
RUN cd web && npm i --force && npm run build
|
||||||
|
|
||||||
|
# install dependencies from poetry.lock file
|
||||||
|
COPY pyproject.toml poetry.toml poetry.lock ./
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/pypoetry,sharing=locked \
|
||||||
|
if [ "$LIGHTEN" -eq 0 ]; then \
|
||||||
|
/root/.local/bin/poetry install --sync --no-cache --no-root --with=full; \
|
||||||
|
else \
|
||||||
|
/root/.local/bin/poetry install --sync --no-cache --no-root; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
# production stage
|
||||||
|
FROM base AS production
|
||||||
|
USER root
|
||||||
|
|
||||||
|
WORKDIR /ragflow
|
||||||
|
|
||||||
|
# Install python packages' dependencies
|
||||||
|
# cv2 requires libGL.so.1
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt install -y --no-install-recommends nginx libgl1 vim less && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY web web
|
||||||
|
COPY api api
|
||||||
|
COPY conf conf
|
||||||
|
COPY deepdoc deepdoc
|
||||||
|
COPY rag rag
|
||||||
|
COPY agent agent
|
||||||
|
COPY graphrag graphrag
|
||||||
|
COPY pyproject.toml poetry.toml poetry.lock ./
|
||||||
|
|
||||||
|
# Copy models downloaded via download_deps.py
|
||||||
|
RUN mkdir -p /ragflow/rag/res/deepdoc /root/.ragflow
|
||||||
|
RUN --mount=type=bind,source=huggingface.co,target=/huggingface.co \
|
||||||
|
tar --exclude='.*' -cf - \
|
||||||
|
/huggingface.co/InfiniFlow/text_concat_xgb_v1.0 \
|
||||||
|
/huggingface.co/InfiniFlow/deepdoc \
|
||||||
|
| tar -xf - --strip-components=3 -C /ragflow/rag/res/deepdoc
|
||||||
|
RUN --mount=type=bind,source=huggingface.co,target=/huggingface.co \
|
||||||
|
tar -cf - \
|
||||||
|
/huggingface.co/BAAI/bge-large-zh-v1.5 \
|
||||||
|
/huggingface.co/BAAI/bge-reranker-v2-m3 \
|
||||||
|
/huggingface.co/maidalun1020/bce-embedding-base_v1 \
|
||||||
|
/huggingface.co/maidalun1020/bce-reranker-base_v1 \
|
||||||
|
| tar -xf - --strip-components=2 -C /root/.ragflow
|
||||||
|
|
||||||
|
# Copy compiled web pages
|
||||||
|
COPY --from=builder /ragflow/web/dist /ragflow/web/dist
|
||||||
|
|
||||||
|
# Copy Python environment and packages
|
||||||
|
ENV VIRTUAL_ENV=/ragflow/.venv
|
||||||
|
COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
|
||||||
|
ENV PATH="${VIRTUAL_ENV}/bin:/root/.local/bin:${PATH}"
|
||||||
|
|
||||||
|
# Download nltk data
|
||||||
|
RUN python3 -m nltk.downloader wordnet punkt punkt_tab
|
||||||
|
|
||||||
ENV PYTHONPATH=/ragflow/
|
ENV PYTHONPATH=/ragflow/
|
||||||
ENV HF_ENDPOINT=https://hf-mirror.com
|
|
||||||
|
|
||||||
ADD docker/entrypoint.sh ./entrypoint.sh
|
COPY docker/entrypoint.sh ./entrypoint.sh
|
||||||
ADD docker/.env ./
|
|
||||||
RUN chmod +x ./entrypoint.sh
|
RUN chmod +x ./entrypoint.sh
|
||||||
|
|
||||||
ENTRYPOINT ["./entrypoint.sh"]
|
ENTRYPOINT ["./entrypoint.sh"]
|
||||||
@ -1,33 +0,0 @@
|
|||||||
FROM python:3.11
|
|
||||||
USER root
|
|
||||||
|
|
||||||
WORKDIR /ragflow
|
|
||||||
|
|
||||||
COPY requirements_arm.txt /ragflow/requirements.txt
|
|
||||||
RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ --default-timeout=1000 -r requirements.txt &&\
|
|
||||||
python -c "import nltk;nltk.download('punkt');nltk.download('wordnet')"
|
|
||||||
|
|
||||||
RUN apt-get update && \
|
|
||||||
apt-get install -y curl gnupg && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
RUN curl -sL https://deb.nodesource.com/setup_20.x | bash - && \
|
|
||||||
apt-get install -y --fix-missing nodejs nginx ffmpeg libsm6 libxext6 libgl1
|
|
||||||
|
|
||||||
ADD ./web ./web
|
|
||||||
RUN cd ./web && npm i --force && npm run build
|
|
||||||
|
|
||||||
ADD ./api ./api
|
|
||||||
ADD ./conf ./conf
|
|
||||||
ADD ./deepdoc ./deepdoc
|
|
||||||
ADD ./rag ./rag
|
|
||||||
ADD ./graph ./graph
|
|
||||||
|
|
||||||
ENV PYTHONPATH=/ragflow/
|
|
||||||
ENV HF_ENDPOINT=https://hf-mirror.com
|
|
||||||
|
|
||||||
ADD docker/entrypoint.sh ./entrypoint.sh
|
|
||||||
ADD docker/.env ./
|
|
||||||
RUN chmod +x ./entrypoint.sh
|
|
||||||
|
|
||||||
ENTRYPOINT ["./entrypoint.sh"]
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
FROM infiniflow/ragflow-base:v2.0
|
|
||||||
USER root
|
|
||||||
|
|
||||||
WORKDIR /ragflow
|
|
||||||
|
|
||||||
## for cuda > 12.0
|
|
||||||
RUN /root/miniconda3/envs/py11/bin/pip uninstall -y onnxruntime-gpu
|
|
||||||
RUN /root/miniconda3/envs/py11/bin/pip install onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/
|
|
||||||
|
|
||||||
|
|
||||||
ADD ./web ./web
|
|
||||||
RUN cd ./web && npm i --force && npm run build
|
|
||||||
|
|
||||||
ADD ./api ./api
|
|
||||||
ADD ./conf ./conf
|
|
||||||
ADD ./deepdoc ./deepdoc
|
|
||||||
ADD ./rag ./rag
|
|
||||||
|
|
||||||
ENV PYTHONPATH=/ragflow/
|
|
||||||
ENV HF_ENDPOINT=https://hf-mirror.com
|
|
||||||
|
|
||||||
ADD docker/entrypoint.sh ./entrypoint.sh
|
|
||||||
RUN chmod +x ./entrypoint.sh
|
|
||||||
|
|
||||||
ENTRYPOINT ["./entrypoint.sh"]
|
|
||||||
@ -1,55 +0,0 @@
|
|||||||
FROM ubuntu:22.04
|
|
||||||
USER root
|
|
||||||
|
|
||||||
WORKDIR /ragflow
|
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y wget curl build-essential libopenmpi-dev
|
|
||||||
|
|
||||||
RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \
|
|
||||||
bash ~/miniconda.sh -b -p /root/miniconda3 && \
|
|
||||||
rm ~/miniconda.sh && ln -s /root/miniconda3/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \
|
|
||||||
echo ". /root/miniconda3/etc/profile.d/conda.sh" >> ~/.bashrc && \
|
|
||||||
echo "conda activate base" >> ~/.bashrc
|
|
||||||
|
|
||||||
ENV PATH /root/miniconda3/bin:$PATH
|
|
||||||
|
|
||||||
RUN conda create -y --name py11 python=3.11
|
|
||||||
|
|
||||||
ENV CONDA_DEFAULT_ENV py11
|
|
||||||
ENV CONDA_PREFIX /root/miniconda3/envs/py11
|
|
||||||
ENV PATH $CONDA_PREFIX/bin:$PATH
|
|
||||||
|
|
||||||
RUN curl -sL https://deb.nodesource.com/setup_14.x | bash -
|
|
||||||
RUN apt-get install -y nodejs
|
|
||||||
|
|
||||||
RUN apt-get install -y nginx
|
|
||||||
|
|
||||||
ADD ./web ./web
|
|
||||||
ADD ./api ./api
|
|
||||||
ADD ./conf ./conf
|
|
||||||
ADD ./deepdoc ./deepdoc
|
|
||||||
ADD ./rag ./rag
|
|
||||||
ADD ./requirements.txt ./requirements.txt
|
|
||||||
ADD ./graph ./graph
|
|
||||||
|
|
||||||
RUN apt install openmpi-bin openmpi-common libopenmpi-dev
|
|
||||||
ENV LD_LIBRARY_PATH /usr/lib/x86_64-linux-gnu/openmpi/lib:$LD_LIBRARY_PATH
|
|
||||||
RUN rm /root/miniconda3/envs/py11/compiler_compat/ld
|
|
||||||
RUN cd ./web && npm i --force && npm run build
|
|
||||||
RUN conda run -n py11 pip install -i https://mirrors.aliyun.com/pypi/simple/ -r ./requirements.txt
|
|
||||||
|
|
||||||
RUN apt-get update && \
|
|
||||||
apt-get install -y libglib2.0-0 libgl1-mesa-glx && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
RUN conda run -n py11 pip install -i https://mirrors.aliyun.com/pypi/simple/ ollama
|
|
||||||
RUN conda run -n py11 python -m nltk.downloader punkt
|
|
||||||
RUN conda run -n py11 python -m nltk.downloader wordnet
|
|
||||||
|
|
||||||
ENV PYTHONPATH=/ragflow/
|
|
||||||
ENV HF_ENDPOINT=https://hf-mirror.com
|
|
||||||
|
|
||||||
ADD docker/entrypoint.sh ./entrypoint.sh
|
|
||||||
RUN chmod +x ./entrypoint.sh
|
|
||||||
|
|
||||||
ENTRYPOINT ["./entrypoint.sh"]
|
|
||||||
@ -30,7 +30,8 @@ ADD ./conf ./conf
|
|||||||
ADD ./deepdoc ./deepdoc
|
ADD ./deepdoc ./deepdoc
|
||||||
ADD ./rag ./rag
|
ADD ./rag ./rag
|
||||||
ADD ./requirements.txt ./requirements.txt
|
ADD ./requirements.txt ./requirements.txt
|
||||||
ADD ./graph ./graph
|
ADD ./agent ./agent
|
||||||
|
ADD ./graphrag ./graphrag
|
||||||
|
|
||||||
RUN dnf install -y openmpi openmpi-devel python3-openmpi
|
RUN dnf install -y openmpi openmpi-devel python3-openmpi
|
||||||
ENV C_INCLUDE_PATH /usr/include/openmpi-x86_64:$C_INCLUDE_PATH
|
ENV C_INCLUDE_PATH /usr/include/openmpi-x86_64:$C_INCLUDE_PATH
|
||||||
|
|||||||
101
Dockerfile.slim
Normal file
101
Dockerfile.slim
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
# base stage
|
||||||
|
FROM ubuntu:24.04 AS base
|
||||||
|
USER root
|
||||||
|
|
||||||
|
ENV LIGHTEN=1
|
||||||
|
|
||||||
|
WORKDIR /ragflow
|
||||||
|
|
||||||
|
RUN rm -f /etc/apt/apt.conf.d/docker-clean \
|
||||||
|
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt-get --no-install-recommends install -y ca-certificates
|
||||||
|
|
||||||
|
# if you located in China, you can use tsinghua mirror to speed up apt
|
||||||
|
RUN sed -i 's|http://archive.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/ubuntu.sources
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt install -y curl libpython3-dev nginx libglib2.0-0 libglx-mesa0 pkg-config libicu-dev libgdiplus \
|
||||||
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
|
&& curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
|
||||||
|
RUN curl -o libssl1.deb http://archive.ubuntu.com/ubuntu/pool/main/o/openssl1.0/libssl1.0.0_1.0.2n-1ubuntu5_amd64.deb && dpkg -i libssl1.deb && rm -f libssl1.deb
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
|
||||||
|
|
||||||
|
# Configure Poetry
|
||||||
|
ENV POETRY_NO_INTERACTION=1
|
||||||
|
ENV POETRY_VIRTUALENVS_IN_PROJECT=true
|
||||||
|
ENV POETRY_VIRTUALENVS_CREATE=true
|
||||||
|
ENV POETRY_REQUESTS_TIMEOUT=15
|
||||||
|
|
||||||
|
# builder stage
|
||||||
|
FROM base AS builder
|
||||||
|
USER root
|
||||||
|
|
||||||
|
WORKDIR /ragflow
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt install -y nodejs npm cargo && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY web web
|
||||||
|
RUN cd web && npm i --force && npm run build
|
||||||
|
|
||||||
|
# install dependencies from poetry.lock file
|
||||||
|
COPY pyproject.toml poetry.toml poetry.lock ./
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/pypoetry,sharing=locked \
|
||||||
|
if [ "$LIGHTEN" -eq 0 ]; then \
|
||||||
|
/root/.local/bin/poetry install --sync --no-cache --no-root --with=full; \
|
||||||
|
else \
|
||||||
|
/root/.local/bin/poetry install --sync --no-cache --no-root; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
# production stage
|
||||||
|
FROM base AS production
|
||||||
|
USER root
|
||||||
|
|
||||||
|
WORKDIR /ragflow
|
||||||
|
|
||||||
|
# Install python packages' dependencies
|
||||||
|
# cv2 requires libGL.so.1
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
apt update && apt install -y --no-install-recommends nginx libgl1 vim less && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY web web
|
||||||
|
COPY api api
|
||||||
|
COPY conf conf
|
||||||
|
COPY deepdoc deepdoc
|
||||||
|
COPY rag rag
|
||||||
|
COPY agent agent
|
||||||
|
COPY graphrag graphrag
|
||||||
|
COPY pyproject.toml poetry.toml poetry.lock ./
|
||||||
|
|
||||||
|
# Copy models downloaded via download_deps.py
|
||||||
|
RUN mkdir -p /ragflow/rag/res/deepdoc /root/.ragflow
|
||||||
|
RUN --mount=type=bind,source=huggingface.co,target=/huggingface.co \
|
||||||
|
tar --exclude='.*' -cf - \
|
||||||
|
/huggingface.co/InfiniFlow/text_concat_xgb_v1.0 \
|
||||||
|
/huggingface.co/InfiniFlow/deepdoc \
|
||||||
|
| tar -xf - --strip-components=3 -C /ragflow/rag/res/deepdoc
|
||||||
|
|
||||||
|
# Copy compiled web pages
|
||||||
|
COPY --from=builder /ragflow/web/dist /ragflow/web/dist
|
||||||
|
|
||||||
|
# Copy Python environment and packages
|
||||||
|
ENV VIRTUAL_ENV=/ragflow/.venv
|
||||||
|
COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
|
||||||
|
ENV PATH="${VIRTUAL_ENV}/bin:/root/.local/bin:${PATH}"
|
||||||
|
|
||||||
|
# Download nltk data
|
||||||
|
RUN python3 -m nltk.downloader wordnet punkt punkt_tab
|
||||||
|
|
||||||
|
ENV PYTHONPATH=/ragflow/
|
||||||
|
|
||||||
|
COPY docker/entrypoint.sh ./entrypoint.sh
|
||||||
|
RUN chmod +x ./entrypoint.sh
|
||||||
|
|
||||||
|
ENTRYPOINT ["./entrypoint.sh"]
|
||||||
181
README.md
181
README.md
@ -7,7 +7,8 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="./README.md">English</a> |
|
<a href="./README.md">English</a> |
|
||||||
<a href="./README_zh.md">简体中文</a> |
|
<a href="./README_zh.md">简体中文</a> |
|
||||||
<a href="./README_ja.md">日本語</a>
|
<a href="./README_ja.md">日本語</a> |
|
||||||
|
<a href="./README_ko.md">한국어</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@ -17,7 +18,7 @@
|
|||||||
<a href="https://demo.ragflow.io" target="_blank">
|
<a href="https://demo.ragflow.io" target="_blank">
|
||||||
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
||||||
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
||||||
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.8.0-brightgreen" alt="docker pull infiniflow/ragflow:v0.8.0"></a>
|
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.12.0-brightgreen" alt="docker pull infiniflow/ragflow:v0.12.0"></a>
|
||||||
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
||||||
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
||||||
</a>
|
</a>
|
||||||
@ -41,8 +42,9 @@
|
|||||||
- 🔎 [System Architecture](#-system-architecture)
|
- 🔎 [System Architecture](#-system-architecture)
|
||||||
- 🎬 [Get Started](#-get-started)
|
- 🎬 [Get Started](#-get-started)
|
||||||
- 🔧 [Configurations](#-configurations)
|
- 🔧 [Configurations](#-configurations)
|
||||||
- 🛠️ [Build from source](#-build-from-source)
|
- 🪛 [Build the docker image without embedding models](#-build-the-docker-image-without-embedding-models)
|
||||||
- 🛠️ [Launch service from source](#-launch-service-from-source)
|
- 🪚 [Build the docker image including embedding models](#-build-the-docker-image-including-embedding-models)
|
||||||
|
- 🔨 [Launch service from source for development](#-launch-service-from-source-for-development)
|
||||||
- 📚 [Documentation](#-documentation)
|
- 📚 [Documentation](#-documentation)
|
||||||
- 📜 [Roadmap](#-roadmap)
|
- 📜 [Roadmap](#-roadmap)
|
||||||
- 🏄 [Community](#-community)
|
- 🏄 [Community](#-community)
|
||||||
@ -59,21 +61,22 @@
|
|||||||
Try our demo at [https://demo.ragflow.io](https://demo.ragflow.io).
|
Try our demo at [https://demo.ragflow.io](https://demo.ragflow.io).
|
||||||
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
||||||
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
||||||
|
<img src="https://github.com/infiniflow/ragflow/assets/12318111/b083d173-dadc-4ea9-bdeb-180d7df514eb" width="1200"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
## 📌 Latest Updates
|
## 🔥 Latest Updates
|
||||||
|
|
||||||
- 2024-07-08 Supports [Graph](./graph/README.md).
|
- 2024-09-29 Optimizes multi-round conversations.
|
||||||
|
- 2024-09-13 Adds search mode for knowledge base Q&A.
|
||||||
- 2024-06-27 Supports Markdown and Docx in the Q&A parsing method. Supports extracting images from Docx files. Supports extracting tables from Markdown files.
|
- 2024-09-09 Adds a medical consultant agent template.
|
||||||
- 2024-06-14 Supports PDF in the Q&A parsing method.
|
- 2024-08-22 Support text to SQL statements through RAG.
|
||||||
- 2024-06-06 Supports [Self-RAG](https://huggingface.co/papers/2310.11511), which is enabled by default in dialog settings.
|
- 2024-08-02 Supports GraphRAG inspired by [graphrag](https://github.com/microsoft/graphrag) and mind map.
|
||||||
- 2024-05-30 Integrates [BCE](https://github.com/netease-youdao/BCEmbedding) and [BGE](https://github.com/FlagOpen/FlagEmbedding) reranker models.
|
- 2024-07-23 Supports audio file parsing.
|
||||||
- 2024-05-28 Supports LLM Baichuan and VolcanoArk.
|
- 2024-07-08 Supports workflow based on [Graph](./agent/README.md).
|
||||||
|
- 2024-06-27 Supports Markdown and Docx in the Q&A parsing method, extracting images from Docx files, extracting tables from Markdown files.
|
||||||
- 2024-05-23 Supports [RAPTOR](https://arxiv.org/html/2401.18059v1) for better text retrieval.
|
- 2024-05-23 Supports [RAPTOR](https://arxiv.org/html/2401.18059v1) for better text retrieval.
|
||||||
- 2024-05-21 Supports streaming output and text chunk retrieval API.
|
|
||||||
- 2024-05-15 Integrates OpenAI GPT-4o.
|
|
||||||
|
|
||||||
## 🌟 Key Features
|
## 🌟 Key Features
|
||||||
|
|
||||||
@ -149,16 +152,13 @@ Try our demo at [https://demo.ragflow.io](https://demo.ragflow.io).
|
|||||||
```
|
```
|
||||||
|
|
||||||
3. Build the pre-built Docker images and start up the server:
|
3. Build the pre-built Docker images and start up the server:
|
||||||
|
> Running the following commands automatically downloads the *dev* version RAGFlow Docker image. To download and run a specified Docker version, update `RAGFLOW_IMAGE` in **docker/.env** to the intended version, for example `RAGFLOW_IMAGE=infiniflow/ragflow:v0.12.0`, before running the following commands.
|
||||||
> Running the following commands automatically downloads the *dev* version RAGFlow Docker image. To download and run a specified Docker version, update `RAGFLOW_VERSION` in **docker/.env** to the intended version, for example `RAGFLOW_VERSION=v0.8.0`, before running the following commands.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ cd ragflow/docker
|
$ cd ragflow/docker
|
||||||
$ chmod +x ./entrypoint.sh
|
|
||||||
$ docker compose up -d
|
$ docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
> The core image is about 9 GB in size and may take a while to load.
|
> The core image is about 9 GB in size and may take a while to load.
|
||||||
|
|
||||||
4. Check the server status after having the server up and running:
|
4. Check the server status after having the server up and running:
|
||||||
@ -170,19 +170,19 @@ Try our demo at [https://demo.ragflow.io](https://demo.ragflow.io).
|
|||||||
_The following output confirms a successful launch of the system:_
|
_The following output confirms a successful launch of the system:_
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
____ ______ __
|
____ ___ ______ ______ __
|
||||||
/ __ \ ____ _ ____ _ / ____// /____ _ __
|
/ __ \ / | / ____// ____// /____ _ __
|
||||||
/ /_/ // __ `// __ `// /_ / // __ \| | /| / /
|
/ /_/ // /| | / / __ / /_ / // __ \| | /| / /
|
||||||
/ _, _// /_/ // /_/ // __/ / // /_/ /| |/ |/ /
|
/ _, _// ___ |/ /_/ // __/ / // /_/ /| |/ |/ /
|
||||||
/_/ |_| \__,_/ \__, //_/ /_/ \____/ |__/|__/
|
/_/ |_|/_/ |_|\____//_/ /_/ \____/ |__/|__/
|
||||||
/____/
|
|
||||||
|
|
||||||
* Running on all addresses (0.0.0.0)
|
* Running on all addresses (0.0.0.0)
|
||||||
* Running on http://127.0.0.1:9380
|
* Running on http://127.0.0.1:9380
|
||||||
* Running on http://x.x.x.x:9380
|
* Running on http://x.x.x.x:9380
|
||||||
INFO:werkzeug:Press CTRL+C to quit
|
INFO:werkzeug:Press CTRL+C to quit
|
||||||
```
|
```
|
||||||
> If you skip this confirmation step and directly log in to RAGFlow, your browser may prompt a `network anomaly` error because, at that moment, your RAGFlow may not be fully initialized.
|
> If you skip this confirmation step and directly log in to RAGFlow, your browser may prompt a `network abnormal` error because, at that moment, your RAGFlow may not be fully initialized.
|
||||||
|
|
||||||
5. In your web browser, enter the IP address of your server and log in to RAGFlow.
|
5. In your web browser, enter the IP address of your server and log in to RAGFlow.
|
||||||
> With the default settings, you only need to enter `http://IP_OF_YOUR_MACHINE` (**sans** port number) as the default HTTP serving port `80` can be omitted when using the default configurations.
|
> With the default settings, you only need to enter `http://IP_OF_YOUR_MACHINE` (**sans** port number) as the default HTTP serving port `80` can be omitted when using the default configurations.
|
||||||
@ -190,7 +190,7 @@ Try our demo at [https://demo.ragflow.io](https://demo.ragflow.io).
|
|||||||
|
|
||||||
> See [llm_api_key_setup](https://ragflow.io/docs/dev/llm_api_key_setup) for more information.
|
> See [llm_api_key_setup](https://ragflow.io/docs/dev/llm_api_key_setup) for more information.
|
||||||
|
|
||||||
_The show is now on!_
|
_The show is on!_
|
||||||
|
|
||||||
## 🔧 Configurations
|
## 🔧 Configurations
|
||||||
|
|
||||||
@ -206,118 +206,89 @@ You must ensure that changes to the [.env](./docker/.env) file are in line with
|
|||||||
|
|
||||||
To update the default HTTP serving port (80), go to [docker-compose.yml](./docker/docker-compose.yml) and change `80:80` to `<YOUR_SERVING_PORT>:80`.
|
To update the default HTTP serving port (80), go to [docker-compose.yml](./docker/docker-compose.yml) and change `80:80` to `<YOUR_SERVING_PORT>:80`.
|
||||||
|
|
||||||
> Updates to all system configurations require a system reboot to take effect:
|
Updates to the above configurations require a reboot of all containers to take effect:
|
||||||
>
|
|
||||||
> ```bash
|
> ```bash
|
||||||
> $ docker-compose up -d
|
> $ docker-compose -f docker/docker-compose.yml up -d
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
## 🛠️ Build from source
|
## 🪛 Build the Docker image without embedding models
|
||||||
|
|
||||||
To build the Docker images from source:
|
This image is approximately 1 GB in size and relies on external LLM and embedding services.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ git clone https://github.com/infiniflow/ragflow.git
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
$ cd ragflow/
|
cd ragflow/
|
||||||
$ docker build -t infiniflow/ragflow:dev .
|
pip3 install huggingface-hub
|
||||||
$ cd ragflow/docker
|
python3 download_deps.py
|
||||||
$ chmod +x ./entrypoint.sh
|
docker build -f Dockerfile.slim -t infiniflow/ragflow:dev-slim .
|
||||||
$ docker compose up -d
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ Launch service from source
|
## 🪚 Build the Docker image including embedding models
|
||||||
|
|
||||||
To launch the service from source:
|
This image is approximately 9 GB in size. As it includes embedding models, it relies on external LLM services only.
|
||||||
|
|
||||||
1. Clone the repository:
|
```bash
|
||||||
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
|
cd ragflow/
|
||||||
|
pip3 install huggingface-hub
|
||||||
|
python3 download_deps.py
|
||||||
|
docker build -f Dockerfile -t infiniflow/ragflow:dev .
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔨 Launch service from source for development
|
||||||
|
|
||||||
|
1. Install Poetry, or skip this step if it is already installed:
|
||||||
```bash
|
```bash
|
||||||
$ git clone https://github.com/infiniflow/ragflow.git
|
curl -sSL https://install.python-poetry.org | python3 -
|
||||||
$ cd ragflow/
|
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Create a virtual environment, ensuring that Anaconda or Miniconda is installed:
|
2. Clone the source code and install Python dependencies:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ conda create -n ragflow python=3.11.0
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
$ conda activate ragflow
|
cd ragflow/
|
||||||
$ pip install -r requirements.txt
|
export POETRY_VIRTUALENVS_CREATE=true POETRY_VIRTUALENVS_IN_PROJECT=true
|
||||||
|
~/.local/bin/poetry install --sync --no-root # install RAGFlow dependent python modules
|
||||||
```
|
```
|
||||||
|
|
||||||
|
3. Launch the dependent services (MinIO, Elasticsearch, Redis, and MySQL) using Docker Compose:
|
||||||
```bash
|
```bash
|
||||||
# If your CUDA version is higher than 12.0, run the following additional commands:
|
docker compose -f docker/docker-compose-base.yml up -d
|
||||||
$ pip uninstall -y onnxruntime-gpu
|
|
||||||
$ pip install onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/
|
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Copy the entry script and configure environment variables:
|
Add the following line to `/etc/hosts` to resolve all hosts specified in **docker/service_conf.yaml** to `127.0.0.1`:
|
||||||
|
|
||||||
```bash
|
|
||||||
# Get the Python path:
|
|
||||||
$ which python
|
|
||||||
# Get the ragflow project path:
|
|
||||||
$ pwd
|
|
||||||
```
|
```
|
||||||
|
127.0.0.1 es01 mysql minio redis
|
||||||
```bash
|
|
||||||
$ cp docker/entrypoint.sh .
|
|
||||||
$ vi entrypoint.sh
|
|
||||||
```
|
```
|
||||||
|
In **docker/service_conf.yaml**, update mysql port to `5455` and es port to `1200`, as specified in **docker/.env**.
|
||||||
|
|
||||||
|
4. If you cannot access HuggingFace, set the `HF_ENDPOINT` environment variable to use a mirror site:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Adjust configurations according to your actual situation (the following two export commands are newly added):
|
|
||||||
# - Assign the result of `which python` to `PY`.
|
|
||||||
# - Assign the result of `pwd` to `PYTHONPATH`.
|
|
||||||
# - Comment out `LD_LIBRARY_PATH`, if it is configured.
|
|
||||||
# - Optional: Add Hugging Face mirror.
|
|
||||||
PY=${PY}
|
|
||||||
export PYTHONPATH=${PYTHONPATH}
|
|
||||||
export HF_ENDPOINT=https://hf-mirror.com
|
export HF_ENDPOINT=https://hf-mirror.com
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Launch the third-party services (MinIO, Elasticsearch, Redis, and MySQL):
|
5. Launch backend service:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ cd docker
|
source .venv/bin/activate
|
||||||
$ docker compose -f docker-compose-base.yml up -d
|
export PYTHONPATH=$(pwd)
|
||||||
|
bash docker/launch_backend_service.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
5. Check the configuration files, ensuring that:
|
6. Install frontend dependencies:
|
||||||
|
|
||||||
- The settings in **docker/.env** match those in **conf/service_conf.yaml**.
|
|
||||||
- The IP addresses and ports for related services in **service_conf.yaml** match the local machine IP and ports exposed by the container.
|
|
||||||
|
|
||||||
6. Launch the RAGFlow backend service:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ chmod +x ./entrypoint.sh
|
cd web
|
||||||
$ bash ./entrypoint.sh
|
npm install --force
|
||||||
|
```
|
||||||
|
7. Configure frontend to update `proxy.target` in **.umirc.ts** to `http://127.0.0.1:9380`:
|
||||||
|
8. Launch frontend service:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
7. Launch the frontend service:
|
_The following output confirms a successful launch of the system:_
|
||||||
|
|
||||||
```bash
|

|
||||||
$ cd web
|
|
||||||
$ npm install --registry=https://registry.npmmirror.com --force
|
|
||||||
$ vim .umirc.ts
|
|
||||||
# Update proxy.target to http://127.0.0.1:9380
|
|
||||||
$ npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
8. Deploy the frontend service:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ cd web
|
|
||||||
$ npm install --registry=https://registry.npmmirror.com --force
|
|
||||||
$ umi build
|
|
||||||
$ mkdir -p /ragflow/web
|
|
||||||
$ cp -r dist /ragflow/web
|
|
||||||
$ apt install nginx -y
|
|
||||||
$ cp ../docker/nginx/proxy.conf /etc/nginx
|
|
||||||
$ cp ../docker/nginx/nginx.conf /etc/nginx
|
|
||||||
$ cp ../docker/nginx/ragflow.conf /etc/nginx/conf.d
|
|
||||||
$ systemctl start nginx
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📚 Documentation
|
## 📚 Documentation
|
||||||
|
|
||||||
@ -338,4 +309,4 @@ See the [RAGFlow Roadmap 2024](https://github.com/infiniflow/ragflow/issues/162)
|
|||||||
|
|
||||||
## 🙌 Contributing
|
## 🙌 Contributing
|
||||||
|
|
||||||
RAGFlow flourishes via open-source collaboration. In this spirit, we embrace diverse contributions from the community. If you would like to be a part, review our [Contribution Guidelines](./docs/references/CONTRIBUTING.md) first.
|
RAGFlow flourishes via open-source collaboration. In this spirit, we embrace diverse contributions from the community. If you would like to be a part, review our [Contribution Guidelines](./CONTRIBUTING.md) first.
|
||||||
|
|||||||
168
README_ja.md
168
README_ja.md
@ -7,7 +7,8 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="./README.md">English</a> |
|
<a href="./README.md">English</a> |
|
||||||
<a href="./README_zh.md">简体中文</a> |
|
<a href="./README_zh.md">简体中文</a> |
|
||||||
<a href="./README_ja.md">日本語</a>
|
<a href="./README_ja.md">日本語</a> |
|
||||||
|
<a href="./README_ko.md">한국어</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@ -17,8 +18,8 @@
|
|||||||
<a href="https://demo.ragflow.io" target="_blank">
|
<a href="https://demo.ragflow.io" target="_blank">
|
||||||
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
||||||
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
||||||
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.8.0-brightgreen"
|
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.12.0-brightgreen"
|
||||||
alt="docker pull infiniflow/ragflow:v0.8.0"></a>
|
alt="docker pull infiniflow/ragflow:v0.12.0"></a>
|
||||||
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
||||||
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
||||||
</a>
|
</a>
|
||||||
@ -41,19 +42,22 @@
|
|||||||
デモをお試しください:[https://demo.ragflow.io](https://demo.ragflow.io)。
|
デモをお試しください:[https://demo.ragflow.io](https://demo.ragflow.io)。
|
||||||
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
||||||
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
||||||
|
<img src="https://github.com/infiniflow/ragflow/assets/12318111/b083d173-dadc-4ea9-bdeb-180d7df514eb" width="1200"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
## 📌 最新情報
|
## 🔥 最新情報
|
||||||
- 2024-07-08 [Graph](./graph/README.md) に対応しました。.
|
|
||||||
- 2024-06-27 Q&A解析方式はMarkdownファイルとDocxファイルをサポートしています。Docxファイルからの画像の抽出をサポートします。Markdownファイルからテーブルを抽出することをサポートします。
|
- 2024-09-29 マルチラウンドダイアログを最適化。
|
||||||
- 2024-06-14 Q&A 解析メソッドは PDF ファイルをサポートしています。
|
- 2024-09-13 ナレッジベース Q&A の検索モードを追加しました。
|
||||||
- 2024-06-06 会話設定でデフォルトでチェックされている [Self-RAG](https://huggingface.co/papers/2310.11511) をサポートします。
|
- 2024-09-09 エージェントに医療相談テンプレートを追加しました。
|
||||||
- 2024-05-30 [BCE](https://github.com/netease-youdao/BCEmbedding) 、[BGE](https://github.com/FlagOpen/FlagEmbedding) reranker を統合。
|
- 2024-08-22 RAG を介して SQL ステートメントへのテキストをサポートします。
|
||||||
- 2024-05-28 LLM BaichuanとVolcanoArkを統合しました。
|
- 2024-08-02 [graphrag](https://github.com/microsoft/graphrag) からインスピレーションを得た GraphRAG とマインド マップをサポートします。
|
||||||
|
- 2024-07-23 音声ファイルの解析をサポートしました。
|
||||||
|
- 2024-07-08 [Graph](./agent/README.md) ベースのワークフローをサポート
|
||||||
|
- 2024-06-27 Q&A 解析メソッドで Markdown と Docx をサポートし、Docx ファイルから画像を抽出し、Markdown ファイルからテーブルを抽出します。
|
||||||
- 2024-05-23 より良いテキスト検索のために [RAPTOR](https://arxiv.org/html/2401.18059v1) をサポート。
|
- 2024-05-23 より良いテキスト検索のために [RAPTOR](https://arxiv.org/html/2401.18059v1) をサポート。
|
||||||
- 2024-05-21 ストリーミング出力とテキストチャンク取得APIをサポート。
|
|
||||||
- 2024-05-15 OpenAI GPT-4oを統合しました。
|
|
||||||
|
|
||||||
## 🌟 主な特徴
|
## 🌟 主な特徴
|
||||||
|
|
||||||
@ -136,7 +140,7 @@
|
|||||||
$ docker compose up -d
|
$ docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
> 上記のコマンドを実行すると、RAGFlowの開発版dockerイメージが自動的にダウンロードされます。 特定のバージョンのDockerイメージをダウンロードして実行したい場合は、docker/.envファイルのRAGFLOW_VERSION変数を見つけて、対応するバージョンに変更してください。 例えば、RAGFLOW_VERSION=v0.8.0として、上記のコマンドを実行してください。
|
> 上記のコマンドを実行すると、RAGFlowの開発版dockerイメージが自動的にダウンロードされます。 特定のバージョンのDockerイメージをダウンロードして実行したい場合は、docker/.envファイルのRAGFLOW_IMAGE変数を見つけて、対応するバージョンに変更してください。 例えば、`RAGFLOW_IMAGE=infiniflow/ragflow:v0.12.0`として、上記のコマンドを実行してください。
|
||||||
|
|
||||||
> コアイメージのサイズは約 9 GB で、ロードに時間がかかる場合があります。
|
> コアイメージのサイズは約 9 GB で、ロードに時間がかかる場合があります。
|
||||||
|
|
||||||
@ -149,12 +153,11 @@
|
|||||||
_以下の出力は、システムが正常に起動したことを確認するものです:_
|
_以下の出力は、システムが正常に起動したことを確認するものです:_
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
____ ______ __
|
____ ___ ______ ______ __
|
||||||
/ __ \ ____ _ ____ _ / ____// /____ _ __
|
/ __ \ / | / ____// ____// /____ _ __
|
||||||
/ /_/ // __ `// __ `// /_ / // __ \| | /| / /
|
/ /_/ // /| | / / __ / /_ / // __ \| | /| / /
|
||||||
/ _, _// /_/ // /_/ // __/ / // /_/ /| |/ |/ /
|
/ _, _// ___ |/ /_/ // __/ / // /_/ /| |/ |/ /
|
||||||
/_/ |_| \__,_/ \__, //_/ /_/ \____/ |__/|__/
|
/_/ |_|/_/ |_|\____//_/ /_/ \____/ |__/|__/
|
||||||
/____/
|
|
||||||
|
|
||||||
* Running on all addresses (0.0.0.0)
|
* Running on all addresses (0.0.0.0)
|
||||||
* Running on http://127.0.0.1:9380
|
* Running on http://127.0.0.1:9380
|
||||||
@ -191,78 +194,83 @@
|
|||||||
> $ docker-compose up -d
|
> $ docker-compose up -d
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
## 🛠️ ソースからビルドする
|
## 🪛 ソースコードでDockerイメージを作成(埋め込みモデルなし)
|
||||||
|
|
||||||
ソースからDockerイメージをビルドするには:
|
この Docker イメージのサイズは約 1GB で、外部の大モデルと埋め込みサービスに依存しています。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ git clone https://github.com/infiniflow/ragflow.git
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
$ cd ragflow/
|
cd ragflow/
|
||||||
$ docker build -t infiniflow/ragflow:v0.8.0 .
|
pip3 install huggingface-hub
|
||||||
$ cd ragflow/docker
|
python3 download_deps.py
|
||||||
$ chmod +x ./entrypoint.sh
|
docker build -f Dockerfile.slim -t infiniflow/ragflow:dev-slim .
|
||||||
$ docker compose up -d
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ ソースコードからサービスを起動する方法
|
## 🪚 ソースコードをコンパイルしたDockerイメージ(埋め込みモデルを含む)
|
||||||
|
|
||||||
ソースコードからサービスを起動する場合は、以下の手順に従ってください:
|
この Docker のサイズは約 9GB で、埋め込みモデルを含むため、外部の大モデルサービスのみが必要です。
|
||||||
|
|
||||||
1. リポジトリをクローンします
|
|
||||||
```bash
|
|
||||||
$ git clone https://github.com/infiniflow/ragflow.git
|
|
||||||
$ cd ragflow/
|
|
||||||
```
|
|
||||||
|
|
||||||
2. 仮想環境を作成します(AnacondaまたはMinicondaがインストールされていることを確認してください)
|
|
||||||
```bash
|
|
||||||
$ conda create -n ragflow python=3.11.0
|
|
||||||
$ conda activate ragflow
|
|
||||||
$ pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
CUDAのバージョンが12.0以上の場合、以下の追加コマンドを実行してください:
|
|
||||||
```bash
|
|
||||||
$ pip uninstall -y onnxruntime-gpu
|
|
||||||
$ pip install onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/
|
|
||||||
```
|
|
||||||
|
|
||||||
3. エントリースクリプトをコピーし、環境変数を設定します
|
|
||||||
```bash
|
|
||||||
$ cp docker/entrypoint.sh .
|
|
||||||
$ vi entrypoint.sh
|
|
||||||
```
|
|
||||||
以下のコマンドでPythonのパスとragflowプロジェクトのパスを取得します:
|
|
||||||
```bash
|
|
||||||
$ which python
|
|
||||||
$ pwd
|
|
||||||
```
|
|
||||||
|
|
||||||
`which python`の出力を`PY`の値として、`pwd`の出力を`PYTHONPATH`の値として設定します。
|
|
||||||
|
|
||||||
`LD_LIBRARY_PATH`が既に設定されている場合は、コメントアウトできます。
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 実際の状況に応じて設定を調整してください。以下の二つのexportは新たに追加された設定です
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
PY=${PY}
|
cd ragflow/
|
||||||
export PYTHONPATH=${PYTHONPATH}
|
pip3 install huggingface-hub
|
||||||
# オプション:Hugging Faceミラーを追加
|
python3 download_deps.py
|
||||||
export HF_ENDPOINT=https://hf-mirror.com
|
docker build -f Dockerfile -t infiniflow/ragflow:dev .
|
||||||
```
|
```
|
||||||
|
|
||||||
4. 基本サービスを起動します
|
## 🔨 ソースコードからサービスを起動する方法
|
||||||
```bash
|
|
||||||
$ cd docker
|
|
||||||
$ docker compose -f docker-compose-base.yml up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
5. 設定ファイルを確認します
|
1. Poetry をインストールする。すでにインストールされている場合は、このステップをスキップしてください:
|
||||||
**docker/.env**内の設定が**conf/service_conf.yaml**内の設定と一致していることを確認してください。**service_conf.yaml**内の関連サービスのIPアドレスとポートは、ローカルマシンのIPアドレスとコンテナが公開するポートに変更する必要があります。
|
```bash
|
||||||
|
curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
```
|
||||||
|
|
||||||
6. サービスを起動します
|
2. ソースコードをクローンし、Python の依存関係をインストールする:
|
||||||
```bash
|
```bash
|
||||||
$ chmod +x ./entrypoint.sh
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
$ bash ./entrypoint.sh
|
cd ragflow/
|
||||||
```
|
export POETRY_VIRTUALENVS_CREATE=true POETRY_VIRTUALENVS_IN_PROJECT=true
|
||||||
|
~/.local/bin/poetry install --sync --no-root # install RAGFlow dependent python modules
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Docker Compose を使用して依存サービス(MinIO、Elasticsearch、Redis、MySQL)を起動する:
|
||||||
|
```bash
|
||||||
|
docker compose -f docker/docker-compose-base.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
`/etc/hosts` に以下の行を追加して、**docker/service_conf.yaml** に指定されたすべてのホストを `127.0.0.1` に解決します:
|
||||||
|
```
|
||||||
|
127.0.0.1 es01 mysql minio redis
|
||||||
|
```
|
||||||
|
**docker/service_conf.yaml** で mysql のポートを `5455` に、es のポートを `1200` に更新します(**docker/.env** に指定された通り).
|
||||||
|
|
||||||
|
4. HuggingFace にアクセスできない場合は、`HF_ENDPOINT` 環境変数を設定してミラーサイトを使用してください:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export HF_ENDPOINT=https://hf-mirror.com
|
||||||
|
```
|
||||||
|
|
||||||
|
5. バックエンドサービスを起動する:
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
export PYTHONPATH=$(pwd)
|
||||||
|
bash docker/launch_backend_service.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
6. フロントエンドの依存関係をインストールする:
|
||||||
|
```bash
|
||||||
|
cd web
|
||||||
|
npm install --force
|
||||||
|
```
|
||||||
|
7. フロントエンドを設定し、**.umirc.ts** の `proxy.target` を `http://127.0.0.1:9380` に更新します:
|
||||||
|
8. フロントエンドサービスを起動する:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
_以下の画面で、システムが正常に起動したことを示します:_
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## 📚 ドキュメンテーション
|
## 📚 ドキュメンテーション
|
||||||
|
|
||||||
@ -283,4 +291,4 @@ $ bash ./entrypoint.sh
|
|||||||
|
|
||||||
## 🙌 コントリビュート
|
## 🙌 コントリビュート
|
||||||
|
|
||||||
RAGFlow はオープンソースのコラボレーションによって発展してきました。この精神に基づき、私たちはコミュニティからの多様なコントリビュートを受け入れています。 参加を希望される方は、まず[コントリビューションガイド](./docs/references/CONTRIBUTING.md)をご覧ください。
|
RAGFlow はオープンソースのコラボレーションによって発展してきました。この精神に基づき、私たちはコミュニティからの多様なコントリビュートを受け入れています。 参加を希望される方は、まず [コントリビューションガイド](./CONTRIBUTING.md)をご覧ください。
|
||||||
|
|||||||
299
README_ko.md
Normal file
299
README_ko.md
Normal file
@ -0,0 +1,299 @@
|
|||||||
|
<div align="center">
|
||||||
|
<a href="https://demo.ragflow.io/">
|
||||||
|
<img src="web/src/assets/logo-with-text.png" width="520" alt="ragflow logo">
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="./README.md">English</a> |
|
||||||
|
<a href="./README_zh.md">简体中文</a> |
|
||||||
|
<a href="./README_ja.md">日本語</a> |
|
||||||
|
<a href="./README_ko.md">한국어</a> |
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/infiniflow/ragflow/releases/latest">
|
||||||
|
<img src="https://img.shields.io/github/v/release/infiniflow/ragflow?color=blue&label=Latest%20Release" alt="Latest Release">
|
||||||
|
</a>
|
||||||
|
<a href="https://demo.ragflow.io" target="_blank">
|
||||||
|
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
||||||
|
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
||||||
|
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.12.0-brightgreen" alt="docker pull infiniflow/ragflow:v0.12.0"></a>
|
||||||
|
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
||||||
|
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h4 align="center">
|
||||||
|
<a href="https://ragflow.io/docs/dev/">Document</a> |
|
||||||
|
<a href="https://github.com/infiniflow/ragflow/issues/162">Roadmap</a> |
|
||||||
|
<a href="https://twitter.com/infiniflowai">Twitter</a> |
|
||||||
|
<a href="https://discord.gg/4XxujFgUN7">Discord</a> |
|
||||||
|
<a href="https://demo.ragflow.io">Demo</a>
|
||||||
|
</h4>
|
||||||
|
|
||||||
|
|
||||||
|
## 💡 RAGFlow란?
|
||||||
|
|
||||||
|
[RAGFlow](https://ragflow.io/)는 심층 문서 이해에 기반한 오픈소스 RAG (Retrieval-Augmented Generation) 엔진입니다. 이 엔진은 대규모 언어 모델(LLM)과 결합하여 정확한 질문 응답 기능을 제공하며, 다양한 복잡한 형식의 데이터에서 신뢰할 수 있는 출처를 바탕으로 한 인용을 통해 이를 뒷받침합니다. RAGFlow는 규모에 상관없이 모든 기업에 최적화된 RAG 워크플로우를 제공합니다.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 🎮 데모
|
||||||
|
데모를 [https://demo.ragflow.io](https://demo.ragflow.io)에서 실행해 보세요.
|
||||||
|
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
||||||
|
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
||||||
|
<img src="https://github.com/infiniflow/ragflow/assets/12318111/b083d173-dadc-4ea9-bdeb-180d7df514eb" width="1200"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
## 🔥 업데이트
|
||||||
|
|
||||||
|
- 2024-09-29 다단계 대화를 최적화합니다.
|
||||||
|
|
||||||
|
- 2024-09-13 지식베이스 Q&A 검색 모드를 추가합니다.
|
||||||
|
|
||||||
|
- 2024-09-09 Agent에 의료상담 템플릿을 추가하였습니다.
|
||||||
|
|
||||||
|
- 2024-08-22 RAG를 통해 SQL 문에 텍스트를 지원합니다.
|
||||||
|
|
||||||
|
- 2024-08-02: [graphrag](https://github.com/microsoft/graphrag)와 마인드맵에서 영감을 받은 GraphRAG를 지원합니다.
|
||||||
|
|
||||||
|
- 2024-07-23: 오디오 파일 분석을 지원합니다.
|
||||||
|
|
||||||
|
- 2024-07-08: [Graph](./agent/README.md)를 기반으로 한 워크플로우를 지원합니다.
|
||||||
|
|
||||||
|
- 2024-06-27 Q&A 구문 분석 방식에서 Markdown 및 Docx를 지원하고, Docx 파일에서 이미지 추출, Markdown 파일에서 테이블 추출을 지원합니다.
|
||||||
|
|
||||||
|
- 2024-05-23: 더 나은 텍스트 검색을 위해 [RAPTOR](https://arxiv.org/html/2401.18059v1)를 지원합니다.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 🌟 주요 기능
|
||||||
|
|
||||||
|
### 🍭 **"Quality in, quality out"**
|
||||||
|
- [심층 문서 이해](./deepdoc/README.md)를 기반으로 복잡한 형식의 비정형 데이터에서 지식을 추출합니다.
|
||||||
|
- 문자 그대로 무한한 토큰에서 "데이터 속의 바늘"을 찾아냅니다.
|
||||||
|
|
||||||
|
### 🍱 **템플릿 기반의 chunking**
|
||||||
|
- 똑똑하고 설명 가능한 방식.
|
||||||
|
- 다양한 템플릿 옵션을 제공합니다.
|
||||||
|
|
||||||
|
|
||||||
|
### 🌱 **할루시네이션을 줄인 신뢰할 수 있는 인용**
|
||||||
|
- 텍스트 청킹을 시각화하여 사용자가 개입할 수 있도록 합니다.
|
||||||
|
- 중요한 참고 자료와 추적 가능한 인용을 빠르게 확인하여 신뢰할 수 있는 답변을 지원합니다.
|
||||||
|
|
||||||
|
|
||||||
|
### 🍔 **다른 종류의 데이터 소스와의 호환성**
|
||||||
|
- 워드, 슬라이드, 엑셀, 텍스트 파일, 이미지, 스캔본, 구조화된 데이터, 웹 페이지 등을 지원합니다.
|
||||||
|
|
||||||
|
### 🛀 **자동화되고 손쉬운 RAG 워크플로우**
|
||||||
|
- 개인 및 대규모 비즈니스에 맞춘 효율적인 RAG 오케스트레이션.
|
||||||
|
- 구성 가능한 LLM 및 임베딩 모델.
|
||||||
|
- 다중 검색과 결합된 re-ranking.
|
||||||
|
- 비즈니스와 원활하게 통합할 수 있는 직관적인 API.
|
||||||
|
|
||||||
|
|
||||||
|
## 🔎 시스템 아키텍처
|
||||||
|
|
||||||
|
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
||||||
|
<img src="https://github.com/infiniflow/ragflow/assets/12318111/d6ac5664-c237-4200-a7c2-a4a00691b485" width="1000"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
## 🎬 시작하기
|
||||||
|
### 📝 사전 준비 사항
|
||||||
|
- CPU >= 4 cores
|
||||||
|
- RAM >= 16 GB
|
||||||
|
- Disk >= 50 GB
|
||||||
|
- Docker >= 24.0.0 & Docker Compose >= v2.26.1
|
||||||
|
> 로컬 머신(Windows, Mac, Linux)에 Docker가 설치되지 않은 경우, [Docker 엔진 설치]((https://docs.docker.com/engine/install/))를 참조하세요.
|
||||||
|
|
||||||
|
|
||||||
|
### 🚀 서버 시작하기
|
||||||
|
|
||||||
|
1. `vm.max_map_count`가 262144 이상인지 확인하세요:
|
||||||
|
> `vm.max_map_count`의 값을 아래 명령어를 통해 확인하세요:
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> $ sysctl vm.max_map_count
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> 만약 `vm.max_map_count` 이 262144 보다 작다면 값을 쟈설정하세요.
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> # 이 경우에 262144로 설정했습니다.:
|
||||||
|
> $ sudo sysctl -w vm.max_map_count=262144
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> 이 변경 사항은 시스템 재부팅 후에 초기화됩니다. 변경 사항을 영구적으로 적용하려면 /etc/sysctl.conf 파일에 vm.max_map_count 값을 추가하거나 업데이트하세요:
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> vm.max_map_count=262144
|
||||||
|
> ```
|
||||||
|
|
||||||
|
2. 레포지토리를 클론하세요:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ git clone https://github.com/infiniflow/ragflow.git
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 미리 빌드된 Docker 이미지를 생성하고 서버를 시작하세요:
|
||||||
|
|
||||||
|
> 다음 명령어를 실행하면 *dev* 버전의 RAGFlow Docker 이미지가 자동으로 다운로드됩니다. 특정 Docker 버전을 다운로드하고 실행하려면, **docker/.env** 파일에서 `RAGFLOW_IMAGE`을 원하는 버전으로 업데이트한 후, 예를 들어 `RAGFLOW_IMAGE=infiniflow/ragflow:v0.12.0`로 업데이트 한 뒤, 다음 명령어를 실행하세요.
|
||||||
|
```bash
|
||||||
|
$ cd ragflow/docker
|
||||||
|
$ chmod +x ./entrypoint.sh
|
||||||
|
$ docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
> 기본 이미지는 약 9GB 크기이며 로드하는 데 시간이 걸릴 수 있습니다.
|
||||||
|
|
||||||
|
|
||||||
|
4. 서버가 시작된 후 서버 상태를 확인하세요:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ docker logs -f ragflow-server
|
||||||
|
```
|
||||||
|
|
||||||
|
_다음 출력 결과로 시스템이 성공적으로 시작되었음을 확인합니다:_
|
||||||
|
|
||||||
|
```bash
|
||||||
|
____ ___ ______ ______ __
|
||||||
|
/ __ \ / | / ____// ____// /____ _ __
|
||||||
|
/ /_/ // /| | / / __ / /_ / // __ \| | /| / /
|
||||||
|
/ _, _// ___ |/ /_/ // __/ / // /_/ /| |/ |/ /
|
||||||
|
/_/ |_|/_/ |_|\____//_/ /_/ \____/ |__/|__/
|
||||||
|
|
||||||
|
* Running on all addresses (0.0.0.0)
|
||||||
|
* Running on http://127.0.0.1:9380
|
||||||
|
* Running on http://x.x.x.x:9380
|
||||||
|
INFO:werkzeug:Press CTRL+C to quit
|
||||||
|
```
|
||||||
|
> 만약 확인 단계를 건너뛰고 바로 RAGFlow에 로그인하면, RAGFlow가 완전히 초기화되지 않았기 때문에 브라우저에서 `network abnormal` 오류가 발생할 수 있습니다.
|
||||||
|
|
||||||
|
5. 웹 브라우저에 서버의 IP 주소를 입력하고 RAGFlow에 로그인하세요.
|
||||||
|
> 기본 설정을 사용할 경우, `http://IP_OF_YOUR_MACHINE`만 입력하면 됩니다 (포트 번호는 제외). 기본 HTTP 서비스 포트 `80`은 기본 구성으로 사용할 때 생략할 수 있습니다.
|
||||||
|
6. [service_conf.yaml](./docker/service_conf.yaml) 파일에서 원하는 LLM 팩토리를 `user_default_llm`에 선택하고, `API_KEY` 필드를 해당 API 키로 업데이트하세요.
|
||||||
|
> 자세한 내용은 [llm_api_key_setup](https://ragflow.io/docs/dev/llm_api_key_setup)를 참조하세요.
|
||||||
|
|
||||||
|
_이제 쇼가 시작됩니다!_
|
||||||
|
|
||||||
|
## 🔧 설정
|
||||||
|
|
||||||
|
시스템 설정과 관련하여 다음 파일들을 관리해야 합니다:
|
||||||
|
|
||||||
|
- [.env](./docker/.env): `SVR_HTTP_PORT`, `MYSQL_PASSWORD`, `MINIO_PASSWORD`와 같은 시스템의 기본 설정을 포함합니다.
|
||||||
|
- [service_conf.yaml](./docker/service_conf.yaml): 백엔드 서비스를 구성합니다.
|
||||||
|
- [docker-compose.yml](./docker/docker-compose.yml): 시스템은 [docker-compose.yml](./docker/docker-compose.yml)을 사용하여 시작됩니다.
|
||||||
|
|
||||||
|
[.env](./docker/.env) 파일의 변경 사항이 [service_conf.yaml](./docker/service_conf.yaml) 파일의 내용과 일치하도록 해야 합니다.
|
||||||
|
|
||||||
|
> [./docker/README](./docker/README.md) 파일에는 환경 설정과 서비스 구성에 대한 자세한 설명이 있으며, [./docker/README](./docker/README.md) 파일에 나열된 모든 환경 설정이 [service_conf.yaml](./docker/service_conf.yaml) 파일의 해당 구성과 일치하도록 해야 합니다.
|
||||||
|
|
||||||
|
기본 HTTP 서비스 포트(80)를 업데이트하려면 [docker-compose.yml](./docker/docker-compose.yml) 파일에서 `80:80`을 `<YOUR_SERVING_PORT>:80`으로 변경하세요.
|
||||||
|
|
||||||
|
> 모든 시스템 구성 업데이트는 적용되기 위해 시스템 재부팅이 필요합니다.
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> $ docker-compose up -d
|
||||||
|
> ```
|
||||||
|
|
||||||
|
## 🪛 소스 코드로 Docker 이미지를 컴파일합니다(임베딩 모델 포함하지 않음)
|
||||||
|
|
||||||
|
이 Docker 이미지의 크기는 약 1GB이며, 외부 대형 모델과 임베딩 서비스에 의존합니다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
|
cd ragflow/
|
||||||
|
pip3 install huggingface-hub
|
||||||
|
python3 download_deps.py
|
||||||
|
docker build -f Dockerfile.slim -t infiniflow/ragflow:dev-slim .
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🪚 소스 코드로 Docker 이미지를 컴파일합니다(임베딩 모델 포함)
|
||||||
|
|
||||||
|
이 Docker의 크기는 약 9GB이며, 이미 임베딩 모델을 포함하고 있으므로 외부 대형 모델 서비스에만 의존하면 됩니다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
|
cd ragflow/
|
||||||
|
pip3 install huggingface-hub
|
||||||
|
python3 download_deps.py
|
||||||
|
docker build -f Dockerfile -t infiniflow/ragflow:dev .
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔨 소스 코드로 서비스를 시작합니다.
|
||||||
|
|
||||||
|
1. Poetry를 설치하거나 이미 설치된 경우 이 단계를 건너뜁니다:
|
||||||
|
```bash
|
||||||
|
curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 소스 코드를 클론하고 Python 의존성을 설치합니다:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
|
cd ragflow/
|
||||||
|
export POETRY_VIRTUALENVS_CREATE=true POETRY_VIRTUALENVS_IN_PROJECT=true
|
||||||
|
~/.local/bin/poetry install --sync --no-root # install RAGFlow dependent python modules
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Docker Compose를 사용하여 의존 서비스(MinIO, Elasticsearch, Redis 및 MySQL)를 시작합니다:
|
||||||
|
```bash
|
||||||
|
docker compose -f docker/docker-compose-base.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
`/etc/hosts` 에 다음 줄을 추가하여 **docker/service_conf.yaml** 에 지정된 모든 호스트를 `127.0.0.1` 로 해결합니다:
|
||||||
|
```
|
||||||
|
127.0.0.1 es01 mysql minio redis
|
||||||
|
```
|
||||||
|
**docker/service_conf.yaml** 에서 mysql 포트를 `5455` 로, es 포트를 `1200` 으로 업데이트합니다( **docker/.env** 에 지정된 대로).
|
||||||
|
|
||||||
|
4. HuggingFace에 접근할 수 없는 경우, `HF_ENDPOINT` 환경 변수를 설정하여 미러 사이트를 사용하세요:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export HF_ENDPOINT=https://hf-mirror.com
|
||||||
|
```
|
||||||
|
|
||||||
|
5. 백엔드 서비스를 시작합니다:
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
export PYTHONPATH=$(pwd)
|
||||||
|
bash docker/launch_backend_service.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
6. 프론트엔드 의존성을 설치합니다:
|
||||||
|
```bash
|
||||||
|
cd web
|
||||||
|
npm install --force
|
||||||
|
```
|
||||||
|
7. **.umirc.ts** 에서 `proxy.target` 을 `http://127.0.0.1:9380` 으로 업데이트합니다:
|
||||||
|
8. 프론트엔드 서비스를 시작합니다:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
_다음 인터페이스는 시스템이 성공적으로 시작되었음을 나타냅니다:_
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## 📚 문서
|
||||||
|
|
||||||
|
- [Quickstart](https://ragflow.io/docs/dev/)
|
||||||
|
- [User guide](https://ragflow.io/docs/dev/category/user-guides)
|
||||||
|
- [References](https://ragflow.io/docs/dev/category/references)
|
||||||
|
- [FAQ](https://ragflow.io/docs/dev/faq)
|
||||||
|
|
||||||
|
## 📜 로드맵
|
||||||
|
|
||||||
|
[RAGFlow 로드맵 2024](https://github.com/infiniflow/ragflow/issues/162)을 확인하세요.
|
||||||
|
|
||||||
|
## 🏄 커뮤니티
|
||||||
|
|
||||||
|
- [Discord](https://discord.gg/4XxujFgUN7)
|
||||||
|
- [Twitter](https://twitter.com/infiniflowai)
|
||||||
|
- [GitHub Discussions](https://github.com/orgs/infiniflow/discussions)
|
||||||
|
|
||||||
|
## 🙌 컨트리뷰션
|
||||||
|
|
||||||
|
RAGFlow는 오픈소스 협업을 통해 발전합니다. 이러한 정신을 바탕으로, 우리는 커뮤니티의 다양한 기여를 환영합니다. 참여하고 싶으시다면, 먼저 [가이드라인](./CONTRIBUTING.md)을 검토해 주세요.
|
||||||
203
README_zh.md
203
README_zh.md
@ -7,7 +7,8 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="./README.md">English</a> |
|
<a href="./README.md">English</a> |
|
||||||
<a href="./README_zh.md">简体中文</a> |
|
<a href="./README_zh.md">简体中文</a> |
|
||||||
<a href="./README_ja.md">日本語</a>
|
<a href="./README_ja.md">日本語</a> |
|
||||||
|
<a href="./README_ko.md">한국어</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@ -17,7 +18,7 @@
|
|||||||
<a href="https://demo.ragflow.io" target="_blank">
|
<a href="https://demo.ragflow.io" target="_blank">
|
||||||
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
<img alt="Static Badge" src="https://img.shields.io/badge/Online-Demo-4e6b99"></a>
|
||||||
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
<a href="https://hub.docker.com/r/infiniflow/ragflow" target="_blank">
|
||||||
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.8.0-brightgreen" alt="docker pull infiniflow/ragflow:v0.8.0"></a>
|
<img src="https://img.shields.io/badge/docker_pull-ragflow:v0.12.0-brightgreen" alt="docker pull infiniflow/ragflow:v0.12.0"></a>
|
||||||
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
<a href="https://github.com/infiniflow/ragflow/blob/main/LICENSE">
|
||||||
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
<img height="21" src="https://img.shields.io/badge/License-Apache--2.0-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="license">
|
||||||
</a>
|
</a>
|
||||||
@ -40,20 +41,21 @@
|
|||||||
请登录网址 [https://demo.ragflow.io](https://demo.ragflow.io) 试用 demo。
|
请登录网址 [https://demo.ragflow.io](https://demo.ragflow.io) 试用 demo。
|
||||||
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
<div align="center" style="margin-top:20px;margin-bottom:20px;">
|
||||||
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
<img src="https://github.com/infiniflow/ragflow/assets/7248/2f6baa3e-1092-4f11-866d-36f6a9d075e5" width="1200"/>
|
||||||
|
<img src="https://github.com/infiniflow/ragflow/assets/12318111/b083d173-dadc-4ea9-bdeb-180d7df514eb" width="1200"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
## 📌 近期更新
|
## 🔥 近期更新
|
||||||
|
|
||||||
- 2024-07-08 支持 [Graph](./graph/README.md)。
|
- 2024-09-29 优化多轮对话.
|
||||||
- 2024-06-27 Q&A 解析方式支持 Markdown 文件和 Docx 文件。支持提取出 Docx 文件中的图片。支持提取出 Markdown 文件中的表格。
|
- 2024-09-13 增加知识库问答搜索模式。
|
||||||
- 2024-06-14 Q&A 解析方式支持 PDF 文件。
|
- 2024-09-09 在 Agent 中加入医疗问诊模板。
|
||||||
- 2024-06-06 支持 [Self-RAG](https://huggingface.co/papers/2310.11511) ,在对话设置里面默认勾选。
|
- 2024-08-22 支持用 RAG 技术实现从自然语言到 SQL 语句的转换。
|
||||||
- 2024-05-30 集成 [BCE](https://github.com/netease-youdao/BCEmbedding) 和 [BGE](https://github.com/FlagOpen/FlagEmbedding) 重排序模型。
|
- 2024-08-02 支持 GraphRAG 启发于 [graphrag](https://github.com/microsoft/graphrag) 和思维导图。
|
||||||
- 2024-05-28 集成大模型 Baichuan 和火山方舟。
|
- 2024-07-23 支持解析音频文件。
|
||||||
|
- 2024-07-08 支持 Agentic RAG: 基于 [Graph](./agent/README.md) 的工作流。
|
||||||
|
- 2024-06-27 Q&A 解析方式支持 Markdown 文件和 Docx 文件,支持提取出 Docx 文件中的图片和 Markdown 文件中的表格。
|
||||||
- 2024-05-23 实现 [RAPTOR](https://arxiv.org/html/2401.18059v1) 提供更好的文本检索。
|
- 2024-05-23 实现 [RAPTOR](https://arxiv.org/html/2401.18059v1) 提供更好的文本检索。
|
||||||
- 2024-05-21 支持流式结果输出和文本块获取API。
|
|
||||||
- 2024-05-15 集成大模型 OpenAI GPT-4o。
|
|
||||||
|
|
||||||
## 🌟 主要功能
|
## 🌟 主要功能
|
||||||
|
|
||||||
@ -133,12 +135,12 @@
|
|||||||
```bash
|
```bash
|
||||||
$ cd ragflow/docker
|
$ cd ragflow/docker
|
||||||
$ chmod +x ./entrypoint.sh
|
$ chmod +x ./entrypoint.sh
|
||||||
$ docker compose -f docker-compose-CN.yml up -d
|
$ docker compose -f docker-compose.yml up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
> 请注意,运行上述命令会自动下载 RAGFlow 的开发版本 docker 镜像。如果你想下载并运行特定版本的 docker 镜像,请在 docker/.env 文件中找到 RAGFLOW_VERSION 变量,将其改为对应版本。例如 RAGFLOW_VERSION=v0.8.0,然后运行上述命令。
|
> 请注意,运行上述命令会自动下载 RAGFlow 的开发版本 docker 镜像。如果你想下载并运行特定版本的 docker 镜像,请在 docker/.env 文件中找到 RAGFLOW_IMAGE 变量,将其改为对应版本。例如 `RAGFLOW_IMAGE=infiniflow/ragflow:v0.12.0`,然后运行上述命令。
|
||||||
|
|
||||||
> 核心镜像文件大约 9 GB,可能需要一定时间拉取。请耐心等待。
|
> 核心镜像下载大小为 9 GB,可能需要一定时间拉取。请耐心等待。
|
||||||
|
|
||||||
4. 服务器启动成功后再次确认服务器状态:
|
4. 服务器启动成功后再次确认服务器状态:
|
||||||
|
|
||||||
@ -149,19 +151,18 @@
|
|||||||
_出现以下界面提示说明服务器启动成功:_
|
_出现以下界面提示说明服务器启动成功:_
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
____ ______ __
|
____ ___ ______ ______ __
|
||||||
/ __ \ ____ _ ____ _ / ____// /____ _ __
|
/ __ \ / | / ____// ____// /____ _ __
|
||||||
/ /_/ // __ `// __ `// /_ / // __ \| | /| / /
|
/ /_/ // /| | / / __ / /_ / // __ \| | /| / /
|
||||||
/ _, _// /_/ // /_/ // __/ / // /_/ /| |/ |/ /
|
/ _, _// ___ |/ /_/ // __/ / // /_/ /| |/ |/ /
|
||||||
/_/ |_| \__,_/ \__, //_/ /_/ \____/ |__/|__/
|
/_/ |_|/_/ |_|\____//_/ /_/ \____/ |__/|__/
|
||||||
/____/
|
|
||||||
|
|
||||||
* Running on all addresses (0.0.0.0)
|
* Running on all addresses (0.0.0.0)
|
||||||
* Running on http://127.0.0.1:9380
|
* Running on http://127.0.0.1:9380
|
||||||
* Running on http://x.x.x.x:9380
|
* Running on http://x.x.x.x:9380
|
||||||
INFO:werkzeug:Press CTRL+C to quit
|
INFO:werkzeug:Press CTRL+C to quit
|
||||||
```
|
```
|
||||||
> 如果您跳过这一步系统确认步骤就登录 RAGFlow,你的浏览器有可能会提示 `network anomaly` 或 `网络异常`,因为 RAGFlow 可能并未完全启动成功。
|
> 如果您跳过这一步系统确认步骤就登录 RAGFlow,你的浏览器有可能会提示 `network abnormal` 或 `网络异常`,因为 RAGFlow 可能并未完全启动成功。
|
||||||
|
|
||||||
5. 在你的浏览器中输入你的服务器对应的 IP 地址并登录 RAGFlow。
|
5. 在你的浏览器中输入你的服务器对应的 IP 地址并登录 RAGFlow。
|
||||||
> 上面这个例子中,您只需输入 http://IP_OF_YOUR_MACHINE 即可:未改动过配置则无需输入端口(默认的 HTTP 服务端口 80)。
|
> 上面这个例子中,您只需输入 http://IP_OF_YOUR_MACHINE 即可:未改动过配置则无需输入端口(默认的 HTTP 服务端口 80)。
|
||||||
@ -177,114 +178,100 @@
|
|||||||
|
|
||||||
- [.env](./docker/.env):存放一些基本的系统环境变量,比如 `SVR_HTTP_PORT`、`MYSQL_PASSWORD`、`MINIO_PASSWORD` 等。
|
- [.env](./docker/.env):存放一些基本的系统环境变量,比如 `SVR_HTTP_PORT`、`MYSQL_PASSWORD`、`MINIO_PASSWORD` 等。
|
||||||
- [service_conf.yaml](./docker/service_conf.yaml):配置各类后台服务。
|
- [service_conf.yaml](./docker/service_conf.yaml):配置各类后台服务。
|
||||||
- [docker-compose-CN.yml](./docker/docker-compose-CN.yml): 系统依赖该文件完成启动。
|
- [docker-compose.yml](./docker/docker-compose.yml): 系统依赖该文件完成启动。
|
||||||
|
|
||||||
请务必确保 [.env](./docker/.env) 文件中的变量设置与 [service_conf.yaml](./docker/service_conf.yaml) 文件中的配置保持一致!
|
请务必确保 [.env](./docker/.env) 文件中的变量设置与 [service_conf.yaml](./docker/service_conf.yaml) 文件中的配置保持一致!
|
||||||
|
|
||||||
|
如果不能访问镜像站点hub.docker.com或者模型站点huggingface.co,请按照[.env](./docker/.env)注释修改`RAGFLOW_IMAGE`和`HF_ENDPOINT`。
|
||||||
|
|
||||||
> [./docker/README](./docker/README.md) 文件提供了环境变量设置和服务配置的详细信息。请**一定要**确保 [./docker/README](./docker/README.md) 文件当中列出来的环境变量的值与 [service_conf.yaml](./docker/service_conf.yaml) 文件当中的系统配置保持一致。
|
> [./docker/README](./docker/README.md) 文件提供了环境变量设置和服务配置的详细信息。请**一定要**确保 [./docker/README](./docker/README.md) 文件当中列出来的环境变量的值与 [service_conf.yaml](./docker/service_conf.yaml) 文件当中的系统配置保持一致。
|
||||||
|
|
||||||
如需更新默认的 HTTP 服务端口(80), 可以在 [docker-compose-CN.yml](./docker/docker-compose-CN.yml) 文件中将配置 `80:80` 改为 `<YOUR_SERVING_PORT>:80`。
|
如需更新默认的 HTTP 服务端口(80), 可以在 [docker-compose.yml](./docker/docker-compose.yml) 文件中将配置 `80:80` 改为 `<YOUR_SERVING_PORT>:80`。
|
||||||
|
|
||||||
> 所有系统配置都需要通过系统重启生效:
|
> 所有系统配置都需要通过系统重启生效:
|
||||||
>
|
>
|
||||||
> ```bash
|
> ```bash
|
||||||
> $ docker compose -f docker-compose-CN.yml up -d
|
> $ docker compose -f docker-compose.yml up -d
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
## 🛠️ 源码编译、安装 Docker 镜像
|
## 🪛 源码编译 Docker 镜像(不含 embedding 模型)
|
||||||
|
|
||||||
如需从源码安装 Docker 镜像:
|
本 Docker 镜像大小约 1 GB 左右并且依赖外部的大模型和 embedding 服务。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ git clone https://github.com/infiniflow/ragflow.git
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
$ cd ragflow/
|
cd ragflow/
|
||||||
$ docker build -t infiniflow/ragflow:v0.8.0 .
|
pip3 install huggingface-hub
|
||||||
$ cd ragflow/docker
|
python3 download_deps.py
|
||||||
$ chmod +x ./entrypoint.sh
|
docker build -f Dockerfile.slim -t infiniflow/ragflow:dev-slim .
|
||||||
$ docker compose up -d
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ 源码启动服务
|
## 🪚 源码编译 Docker 镜像(包含 embedding 模型)
|
||||||
|
|
||||||
如需从源码启动服务,请参考以下步骤:
|
本 Docker 大小约 9 GB 左右。由于已包含 embedding 模型,所以只需依赖外部的大模型服务即可。
|
||||||
|
|
||||||
1. 克隆仓库
|
|
||||||
```bash
|
|
||||||
$ git clone https://github.com/infiniflow/ragflow.git
|
|
||||||
$ cd ragflow/
|
|
||||||
```
|
|
||||||
|
|
||||||
2. 创建虚拟环境(确保已安装 Anaconda 或 Miniconda)
|
|
||||||
```bash
|
|
||||||
$ conda create -n ragflow python=3.11.0
|
|
||||||
$ conda activate ragflow
|
|
||||||
$ pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
如果cuda > 12.0,需额外执行以下命令:
|
|
||||||
```bash
|
|
||||||
$ pip uninstall -y onnxruntime-gpu
|
|
||||||
$ pip install onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/
|
|
||||||
```
|
|
||||||
|
|
||||||
3. 拷贝入口脚本并配置环境变量
|
|
||||||
```bash
|
|
||||||
$ cp docker/entrypoint.sh .
|
|
||||||
$ vi entrypoint.sh
|
|
||||||
```
|
|
||||||
使用以下命令获取python路径及ragflow项目路径:
|
|
||||||
```bash
|
|
||||||
$ which python
|
|
||||||
$ pwd
|
|
||||||
```
|
|
||||||
|
|
||||||
将上述`which python`的输出作为`PY`的值,将`pwd`的输出作为`PYTHONPATH`的值。
|
|
||||||
|
|
||||||
`LD_LIBRARY_PATH`如果环境已经配置好,可以注释掉。
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 此处配置需要按照实际情况调整,两个export为新增配置
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
PY=${PY}
|
cd ragflow/
|
||||||
export PYTHONPATH=${PYTHONPATH}
|
pip3 install huggingface-hub
|
||||||
# 可选:添加Hugging Face镜像
|
python3 download_deps.py
|
||||||
export HF_ENDPOINT=https://hf-mirror.com
|
docker build -f Dockerfile -t infiniflow/ragflow:dev .
|
||||||
```
|
```
|
||||||
|
|
||||||
4. 启动基础服务
|
## 🔨 以源代码启动服务
|
||||||
```bash
|
|
||||||
$ cd docker
|
|
||||||
$ docker compose -f docker-compose-base.yml up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
5. 检查配置文件
|
1. 安装 Poetry。如已经安装,可跳过本步骤:
|
||||||
确保**docker/.env**中的配置与**conf/service_conf.yaml**中配置一致, **service_conf.yaml**中相关服务的IP地址与端口应该改成本机IP地址及容器映射出来的端口。
|
```bash
|
||||||
|
curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
```
|
||||||
|
|
||||||
6. 启动服务
|
2. 下载源代码并安装 Python 依赖:
|
||||||
```bash
|
```bash
|
||||||
$ chmod +x ./entrypoint.sh
|
git clone https://github.com/infiniflow/ragflow.git
|
||||||
$ bash ./entrypoint.sh
|
cd ragflow/
|
||||||
```
|
export POETRY_VIRTUALENVS_CREATE=true POETRY_VIRTUALENVS_IN_PROJECT=true
|
||||||
7. 启动WebUI服务
|
~/.local/bin/poetry install --sync --no-root # install RAGFlow dependent python modules
|
||||||
```bash
|
```
|
||||||
$ cd web
|
|
||||||
$ npm install --registry=https://registry.npmmirror.com --force
|
3. 通过 Docker Compose 启动依赖的服务(MinIO, Elasticsearch, Redis, and MySQL):
|
||||||
$ vim .umirc.ts
|
```bash
|
||||||
# 修改proxy.target为http://127.0.0.1:9380
|
docker compose -f docker/docker-compose-base.yml up -d
|
||||||
$ npm run dev
|
```
|
||||||
```
|
|
||||||
|
在 `/etc/hosts` 中添加以下代码,将 **docker/service_conf.yaml** 文件中的所有 host 地址都解析为 `127.0.0.1`:
|
||||||
|
```
|
||||||
|
127.0.0.1 es01 mysql minio redis
|
||||||
|
```
|
||||||
|
在文件 **docker/service_conf.yaml** 中,对照 **docker/.env** 的配置将 mysql 端口更新为 `5455`,es 端口更新为 `1200`。
|
||||||
|
|
||||||
|
4. 如果无法访问 HuggingFace,可以把环境变量 `HF_ENDPOINT` 设成相应的镜像站点:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export HF_ENDPOINT=https://hf-mirror.com
|
||||||
|
```
|
||||||
|
|
||||||
|
5. 启动后端服务:
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
export PYTHONPATH=$(pwd)
|
||||||
|
bash docker/launch_backend_service.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
6. 安装前端依赖:
|
||||||
|
```bash
|
||||||
|
cd web
|
||||||
|
npm install --force
|
||||||
|
```
|
||||||
|
7. 配置前端,将 **.umirc.ts** 的 `proxy.target` 更新为 `http://127.0.0.1:9380`:
|
||||||
|
8. 启动前端服务:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
_以下界面说明系统已经成功启动:_
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
8. 部署WebUI服务
|
|
||||||
```bash
|
|
||||||
$ cd web
|
|
||||||
$ npm install --registry=https://registry.npmmirror.com --force
|
|
||||||
$ umi build
|
|
||||||
$ mkdir -p /ragflow/web
|
|
||||||
$ cp -r dist /ragflow/web
|
|
||||||
$ apt install nginx -y
|
|
||||||
$ cp ../docker/nginx/proxy.conf /etc/nginx
|
|
||||||
$ cp ../docker/nginx/nginx.conf /etc/nginx
|
|
||||||
$ cp ../docker/nginx/ragflow.conf /etc/nginx/conf.d
|
|
||||||
$ systemctl start nginx
|
|
||||||
```
|
|
||||||
## 📚 技术文档
|
## 📚 技术文档
|
||||||
|
|
||||||
- [Quickstart](https://ragflow.io/docs/dev/)
|
- [Quickstart](https://ragflow.io/docs/dev/)
|
||||||
@ -304,7 +291,11 @@ $ systemctl start nginx
|
|||||||
|
|
||||||
## 🙌 贡献指南
|
## 🙌 贡献指南
|
||||||
|
|
||||||
RAGFlow 只有通过开源协作才能蓬勃发展。秉持这一精神,我们欢迎来自社区的各种贡献。如果您有意参与其中,请查阅我们的[贡献者指南](./docs/references/CONTRIBUTING.md) 。
|
RAGFlow 只有通过开源协作才能蓬勃发展。秉持这一精神,我们欢迎来自社区的各种贡献。如果您有意参与其中,请查阅我们的 [贡献者指南](./CONTRIBUTING.md) 。
|
||||||
|
|
||||||
|
## 🤝 商务合作
|
||||||
|
|
||||||
|
- [预约咨询](https://aao615odquw.feishu.cn/share/base/form/shrcnjw7QleretCLqh1nuPo1xxh)
|
||||||
|
|
||||||
## 👥 加入社区
|
## 👥 加入社区
|
||||||
|
|
||||||
|
|||||||
@ -18,7 +18,7 @@ main
|
|||||||
### Actual behavior
|
### Actual behavior
|
||||||
|
|
||||||
The restricted_loads function at [api/utils/__init__.py#L215](https://github.com/infiniflow/ragflow/blob/main/api/utils/__init__.py#L215) is still vulnerable leading via code execution.
|
The restricted_loads function at [api/utils/__init__.py#L215](https://github.com/infiniflow/ragflow/blob/main/api/utils/__init__.py#L215) is still vulnerable leading via code execution.
|
||||||
The main reson is that numpy module has a numpy.f2py.diagnose.run_command function directly execute commands, but the restricted_loads function allows users import functions in module numpy.
|
The main reason is that numpy module has a numpy.f2py.diagnose.run_command function directly execute commands, but the restricted_loads function allows users import functions in module numpy.
|
||||||
|
|
||||||
|
|
||||||
### Steps to reproduce
|
### Steps to reproduce
|
||||||
|
|||||||
@ -22,9 +22,9 @@ from functools import partial
|
|||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from graph.component import component_class
|
from agent.component import component_class
|
||||||
from graph.component.base import ComponentBase
|
from agent.component.base import ComponentBase
|
||||||
from graph.settings import flow_logger, DEBUG
|
from agent.settings import flow_logger, DEBUG
|
||||||
|
|
||||||
|
|
||||||
class Canvas(ABC):
|
class Canvas(ABC):
|
||||||
@ -188,14 +188,19 @@ class Canvas(ABC):
|
|||||||
def prepare2run(cpns):
|
def prepare2run(cpns):
|
||||||
nonlocal ran, ans
|
nonlocal ran, ans
|
||||||
for c in cpns:
|
for c in cpns:
|
||||||
|
if self.path[-1] and c == self.path[-1][-1]: continue
|
||||||
cpn = self.components[c]["obj"]
|
cpn = self.components[c]["obj"]
|
||||||
if cpn.component_name == "Answer":
|
if cpn.component_name == "Answer":
|
||||||
self.answer.append(c)
|
self.answer.append(c)
|
||||||
else:
|
else:
|
||||||
if DEBUG: print("RUN: ", c)
|
if DEBUG: print("RUN: ", c)
|
||||||
|
if cpn.component_name == "Generate":
|
||||||
|
cpids = cpn.get_dependent_components()
|
||||||
|
if any([c not in self.path[-1] for c in cpids]):
|
||||||
|
continue
|
||||||
ans = cpn.run(self.history, **kwargs)
|
ans = cpn.run(self.history, **kwargs)
|
||||||
self.path[-1].append(c)
|
self.path[-1].append(c)
|
||||||
ran += 1
|
ran += 1
|
||||||
|
|
||||||
prepare2run(self.components[self.path[-2][-1]]["downstream"])
|
prepare2run(self.components[self.path[-2][-1]]["downstream"])
|
||||||
while 0 <= ran < len(self.path[-1]):
|
while 0 <= ran < len(self.path[-1]):
|
||||||
@ -220,6 +225,7 @@ class Canvas(ABC):
|
|||||||
prepare2run([p])
|
prepare2run([p])
|
||||||
break
|
break
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
break
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@ -231,6 +237,7 @@ class Canvas(ABC):
|
|||||||
prepare2run([p])
|
prepare2run([p])
|
||||||
break
|
break
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
break
|
||||||
|
|
||||||
if self.answer:
|
if self.answer:
|
||||||
cpn_id = self.answer[0]
|
cpn_id = self.answer[0]
|
||||||
@ -253,7 +260,7 @@ class Canvas(ABC):
|
|||||||
|
|
||||||
def get_history(self, window_size):
|
def get_history(self, window_size):
|
||||||
convs = []
|
convs = []
|
||||||
for role, obj in self.history[window_size * -2:]:
|
for role, obj in self.history[(window_size + 1) * -1:]:
|
||||||
convs.append({"role": role, "content": (obj if role == "user" else
|
convs.append({"role": role, "content": (obj if role == "user" else
|
||||||
'\n'.join(pd.DataFrame(obj)['content']))})
|
'\n'.join(pd.DataFrame(obj)['content']))})
|
||||||
return convs
|
return convs
|
||||||
@ -267,7 +274,7 @@ class Canvas(ABC):
|
|||||||
def get_embedding_model(self):
|
def get_embedding_model(self):
|
||||||
return self._embed_id
|
return self._embed_id
|
||||||
|
|
||||||
def _find_loop(self, max_loops=2):
|
def _find_loop(self, max_loops=6):
|
||||||
path = self.path[-1][::-1]
|
path = self.path[-1][::-1]
|
||||||
if len(path) < 2: return False
|
if len(path) < 2: return False
|
||||||
|
|
||||||
@ -293,3 +300,6 @@ class Canvas(ABC):
|
|||||||
return pat + " => " + pat
|
return pat + " => " + pat
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def get_prologue(self):
|
||||||
|
return self.components["begin"]["obj"]._param.prologue
|
||||||
36
agent/component/__init__.py
Normal file
36
agent/component/__init__.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import importlib
|
||||||
|
from .begin import Begin, BeginParam
|
||||||
|
from .generate import Generate, GenerateParam
|
||||||
|
from .retrieval import Retrieval, RetrievalParam
|
||||||
|
from .answer import Answer, AnswerParam
|
||||||
|
from .categorize import Categorize, CategorizeParam
|
||||||
|
from .switch import Switch, SwitchParam
|
||||||
|
from .relevant import Relevant, RelevantParam
|
||||||
|
from .message import Message, MessageParam
|
||||||
|
from .rewrite import RewriteQuestion, RewriteQuestionParam
|
||||||
|
from .keyword import KeywordExtract, KeywordExtractParam
|
||||||
|
from .concentrator import Concentrator, ConcentratorParam
|
||||||
|
from .baidu import Baidu, BaiduParam
|
||||||
|
from .duckduckgo import DuckDuckGo, DuckDuckGoParam
|
||||||
|
from .wikipedia import Wikipedia, WikipediaParam
|
||||||
|
from .pubmed import PubMed, PubMedParam
|
||||||
|
from .arxiv import ArXiv, ArXivParam
|
||||||
|
from .google import Google, GoogleParam
|
||||||
|
from .bing import Bing, BingParam
|
||||||
|
from .googlescholar import GoogleScholar, GoogleScholarParam
|
||||||
|
from .deepl import DeepL, DeepLParam
|
||||||
|
from .github import GitHub, GitHubParam
|
||||||
|
from .baidufanyi import BaiduFanyi, BaiduFanyiParam
|
||||||
|
from .qweather import QWeather, QWeatherParam
|
||||||
|
from .exesql import ExeSQL, ExeSQLParam
|
||||||
|
from .yahoofinance import YahooFinance, YahooFinanceParam
|
||||||
|
from .wencai import WenCai, WenCaiParam
|
||||||
|
from .jin10 import Jin10, Jin10Param
|
||||||
|
from .tushare import TuShare, TuShareParam
|
||||||
|
from .akshare import AkShare, AkShareParam
|
||||||
|
|
||||||
|
|
||||||
|
def component_class(class_name):
|
||||||
|
m = importlib.import_module("agent.component")
|
||||||
|
c = getattr(m, class_name)
|
||||||
|
return c
|
||||||
56
agent/component/akshare.py
Normal file
56
agent/component/akshare.py
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
import akshare as ak
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class AkShareParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the AkShare component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
|
||||||
|
|
||||||
|
class AkShare(ComponentBase, ABC):
|
||||||
|
component_name = "AkShare"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = ",".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return AkShare.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
ak_res = []
|
||||||
|
stock_news_em_df = ak.stock_news_em(symbol=ans)
|
||||||
|
stock_news_em_df = stock_news_em_df.head(self._param.top_n)
|
||||||
|
ak_res = [{"content": '<a href="' + i["新闻链接"] + '">' + i["新闻标题"] + '</a>\n 新闻内容: ' + i[
|
||||||
|
"新闻内容"] + " \n发布时间:" + i["发布时间"] + " \n文章来源: " + i["文章来源"]} for index, i in stock_news_em_df.iterrows()]
|
||||||
|
except Exception as e:
|
||||||
|
return AkShare.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not ak_res:
|
||||||
|
return AkShare.be_output("")
|
||||||
|
|
||||||
|
return pd.DataFrame(ak_res)
|
||||||
@ -19,7 +19,7 @@ from functools import partial
|
|||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from graph.component.base import ComponentBase, ComponentParamBase
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
class AnswerParam(ComponentParamBase):
|
class AnswerParam(ComponentParamBase):
|
||||||
@ -59,8 +59,10 @@ class Answer(ComponentBase, ABC):
|
|||||||
stream = self.get_stream_input()
|
stream = self.get_stream_input()
|
||||||
if isinstance(stream, pd.DataFrame):
|
if isinstance(stream, pd.DataFrame):
|
||||||
res = stream
|
res = stream
|
||||||
|
answer = ""
|
||||||
for ii, row in stream.iterrows():
|
for ii, row in stream.iterrows():
|
||||||
yield row.to_dict()
|
answer += row.to_dict()["content"]
|
||||||
|
yield {"content": answer}
|
||||||
else:
|
else:
|
||||||
for st in stream():
|
for st in stream():
|
||||||
res = st
|
res = st
|
||||||
69
agent/component/arxiv.py
Normal file
69
agent/component/arxiv.py
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import arxiv
|
||||||
|
import pandas as pd
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class ArXivParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the ArXiv component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 6
|
||||||
|
self.sort_by = 'submittedDate'
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.sort_by, "ArXiv Search Sort_by",
|
||||||
|
['submittedDate', 'lastUpdatedDate', 'relevance'])
|
||||||
|
|
||||||
|
|
||||||
|
class ArXiv(ComponentBase, ABC):
|
||||||
|
component_name = "ArXiv"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return ArXiv.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
sort_choices = {"relevance": arxiv.SortCriterion.Relevance,
|
||||||
|
"lastUpdatedDate": arxiv.SortCriterion.LastUpdatedDate,
|
||||||
|
'submittedDate': arxiv.SortCriterion.SubmittedDate}
|
||||||
|
arxiv_client = arxiv.Client()
|
||||||
|
search = arxiv.Search(
|
||||||
|
query=ans,
|
||||||
|
max_results=self._param.top_n,
|
||||||
|
sort_by=sort_choices[self._param.sort_by]
|
||||||
|
)
|
||||||
|
arxiv_res = [
|
||||||
|
{"content": 'Title: ' + i.title + '\nPdf_Url: <a href="' + i.pdf_url + '"></a> \nSummary: ' + i.summary} for
|
||||||
|
i in list(arxiv_client.results(search))]
|
||||||
|
except Exception as e:
|
||||||
|
return ArXiv.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not arxiv_res:
|
||||||
|
return ArXiv.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(arxiv_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
69
agent/component/baidu.py
Normal file
69
agent/component/baidu.py
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
import random
|
||||||
|
from abc import ABC
|
||||||
|
from functools import partial
|
||||||
|
import pandas as pd
|
||||||
|
import requests
|
||||||
|
import re
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class BaiduParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Baidu component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
|
||||||
|
|
||||||
|
class Baidu(ComponentBase, ABC):
|
||||||
|
component_name = "Baidu"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return Baidu.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
url = 'https://www.baidu.com/s?wd=' + ans + '&rn=' + str(self._param.top_n)
|
||||||
|
headers = {
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'}
|
||||||
|
response = requests.get(url=url, headers=headers)
|
||||||
|
|
||||||
|
url_res = re.findall(r"'url': \\\"(.*?)\\\"}", response.text)
|
||||||
|
title_res = re.findall(r"'title': \\\"(.*?)\\\",\\n", response.text)
|
||||||
|
body_res = re.findall(r"\"contentText\":\"(.*?)\"", response.text)
|
||||||
|
baidu_res = [{"content": re.sub('<em>|</em>', '', '<a href="' + url + '">' + title + '</a> ' + body)} for
|
||||||
|
url, title, body in zip(url_res, title_res, body_res)]
|
||||||
|
del body_res, url_res, title_res
|
||||||
|
except Exception as e:
|
||||||
|
return Baidu.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not baidu_res:
|
||||||
|
return Baidu.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(baidu_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
|
|
||||||
99
agent/component/baidufanyi.py
Normal file
99
agent/component/baidufanyi.py
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
import random
|
||||||
|
from abc import ABC
|
||||||
|
import requests
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
from hashlib import md5
|
||||||
|
|
||||||
|
|
||||||
|
class BaiduFanyiParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the BaiduFanyi component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.appid = "xxx"
|
||||||
|
self.secret_key = "xxx"
|
||||||
|
self.trans_type = 'translate'
|
||||||
|
self.parameters = []
|
||||||
|
self.source_lang = 'auto'
|
||||||
|
self.target_lang = 'auto'
|
||||||
|
self.domain = 'finance'
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_empty(self.appid, "BaiduFanyi APPID")
|
||||||
|
self.check_empty(self.secret_key, "BaiduFanyi Secret Key")
|
||||||
|
self.check_valid_value(self.trans_type, "Translate type", ['translate', 'fieldtranslate'])
|
||||||
|
self.check_valid_value(self.trans_type, "Translate domain",
|
||||||
|
['it', 'finance', 'machinery', 'senimed', 'novel', 'academic', 'aerospace', 'wiki',
|
||||||
|
'news', 'law', 'contract'])
|
||||||
|
self.check_valid_value(self.source_lang, "Source language",
|
||||||
|
['auto', 'zh', 'en', 'yue', 'wyw', 'jp', 'kor', 'fra', 'spa', 'th', 'ara', 'ru', 'pt',
|
||||||
|
'de', 'it', 'el', 'nl', 'pl', 'bul', 'est', 'dan', 'fin', 'cs', 'rom', 'slo', 'swe',
|
||||||
|
'hu', 'cht', 'vie'])
|
||||||
|
self.check_valid_value(self.target_lang, "Target language",
|
||||||
|
['auto', 'zh', 'en', 'yue', 'wyw', 'jp', 'kor', 'fra', 'spa', 'th', 'ara', 'ru', 'pt',
|
||||||
|
'de', 'it', 'el', 'nl', 'pl', 'bul', 'est', 'dan', 'fin', 'cs', 'rom', 'slo', 'swe',
|
||||||
|
'hu', 'cht', 'vie'])
|
||||||
|
self.check_valid_value(self.domain, "Translate field",
|
||||||
|
['it', 'finance', 'machinery', 'senimed', 'novel', 'academic', 'aerospace', 'wiki',
|
||||||
|
'news', 'law', 'contract'])
|
||||||
|
|
||||||
|
|
||||||
|
class BaiduFanyi(ComponentBase, ABC):
|
||||||
|
component_name = "BaiduFanyi"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return BaiduFanyi.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
source_lang = self._param.source_lang
|
||||||
|
target_lang = self._param.target_lang
|
||||||
|
appid = self._param.appid
|
||||||
|
salt = random.randint(32768, 65536)
|
||||||
|
secret_key = self._param.secret_key
|
||||||
|
|
||||||
|
if self._param.trans_type == 'translate':
|
||||||
|
sign = md5((appid + ans + salt + secret_key).encode('utf-8')).hexdigest()
|
||||||
|
url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?' + 'q=' + ans + '&from=' + source_lang + '&to=' + target_lang + '&appid=' + appid + '&salt=' + salt + '&sign=' + sign
|
||||||
|
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
||||||
|
response = requests.post(url=url, headers=headers).json()
|
||||||
|
|
||||||
|
if response.get('error_code'):
|
||||||
|
BaiduFanyi.be_output("**Error**:" + response['error_msg'])
|
||||||
|
|
||||||
|
return BaiduFanyi.be_output(response['trans_result'][0]['dst'])
|
||||||
|
elif self._param.trans_type == 'fieldtranslate':
|
||||||
|
domain = self._param.domain
|
||||||
|
sign = md5((appid + ans + salt + domain + secret_key).encode('utf-8')).hexdigest()
|
||||||
|
url = 'http://api.fanyi.baidu.com/api/trans/vip/fieldtranslate?' + 'q=' + ans + '&from=' + source_lang + '&to=' + target_lang + '&appid=' + appid + '&salt=' + salt + '&domain=' + domain + '&sign=' + sign
|
||||||
|
headers = {"Content-Type": "application/x-www-form-urlencoded"}
|
||||||
|
response = requests.post(url=url, headers=headers).json()
|
||||||
|
|
||||||
|
if response.get('error_code'):
|
||||||
|
BaiduFanyi.be_output("**Error**:" + response['error_msg'])
|
||||||
|
|
||||||
|
return BaiduFanyi.be_output(response['trans_result'][0]['dst'])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
BaiduFanyi.be_output("**Error**:" + str(e))
|
||||||
@ -23,8 +23,8 @@ from typing import List, Dict, Tuple, Union
|
|||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from graph import settings
|
from agent import settings
|
||||||
from graph.settings import flow_logger, DEBUG
|
from agent.settings import flow_logger, DEBUG
|
||||||
|
|
||||||
_FEEDED_DEPRECATED_PARAMS = "_feeded_deprecated_params"
|
_FEEDED_DEPRECATED_PARAMS = "_feeded_deprecated_params"
|
||||||
_DEPRECATED_PARAMS = "_deprecated_params"
|
_DEPRECATED_PARAMS = "_deprecated_params"
|
||||||
@ -35,7 +35,7 @@ _IS_RAW_CONF = "_is_raw_conf"
|
|||||||
class ComponentParamBase(ABC):
|
class ComponentParamBase(ABC):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.output_var_name = "output"
|
self.output_var_name = "output"
|
||||||
self.message_history_window_size = 4
|
self.message_history_window_size = 22
|
||||||
|
|
||||||
def set_name(self, name: str):
|
def set_name(self, name: str):
|
||||||
self._name = name
|
self._name = name
|
||||||
@ -444,7 +444,13 @@ class ComponentBase(ABC):
|
|||||||
|
|
||||||
if DEBUG: print(self.component_name, reversed_cpnts[::-1])
|
if DEBUG: print(self.component_name, reversed_cpnts[::-1])
|
||||||
for u in reversed_cpnts[::-1]:
|
for u in reversed_cpnts[::-1]:
|
||||||
if self.get_component_name(u) in ["switch"]: continue
|
if self.get_component_name(u) in ["switch", "concentrator"]: continue
|
||||||
|
if self.component_name.lower() == "generate" and self.get_component_name(u) == "retrieval":
|
||||||
|
o = self._canvas.get_component(u)["obj"].output(allow_partial=False)[1]
|
||||||
|
if o is not None:
|
||||||
|
upstream_outs.append(o)
|
||||||
|
continue
|
||||||
|
if u not in self._canvas.get_component(self._id)["upstream"]: continue
|
||||||
if self.component_name.lower().find("switch") < 0 \
|
if self.component_name.lower().find("switch") < 0 \
|
||||||
and self.get_component_name(u) in ["relevant", "categorize"]:
|
and self.get_component_name(u) in ["relevant", "categorize"]:
|
||||||
continue
|
continue
|
||||||
@ -454,13 +460,19 @@ class ComponentBase(ABC):
|
|||||||
upstream_outs.append(pd.DataFrame([{"content": c}]))
|
upstream_outs.append(pd.DataFrame([{"content": c}]))
|
||||||
break
|
break
|
||||||
break
|
break
|
||||||
if self.component_name.lower().find("answer") >= 0:
|
if self.component_name.lower().find("answer") >= 0 and self.get_component_name(u) in ["relevant"]:
|
||||||
if self.get_component_name(u) in ["relevant"]: continue
|
continue
|
||||||
|
o = self._canvas.get_component(u)["obj"].output(allow_partial=False)[1]
|
||||||
else: upstream_outs.append(self._canvas.get_component(u)["obj"].output(allow_partial=False)[1])
|
if o is not None:
|
||||||
|
upstream_outs.append(o)
|
||||||
break
|
break
|
||||||
|
|
||||||
return pd.concat(upstream_outs, ignore_index=False)
|
if upstream_outs:
|
||||||
|
df = pd.concat(upstream_outs, ignore_index=True)
|
||||||
|
if "content" in df:
|
||||||
|
df = df.drop_duplicates(subset=['content']).reset_index(drop=True)
|
||||||
|
return df
|
||||||
|
return pd.DataFrame(self._canvas.get_history(3)[-1:])
|
||||||
|
|
||||||
def get_stream_input(self):
|
def get_stream_input(self):
|
||||||
reversed_cpnts = []
|
reversed_cpnts = []
|
||||||
@ -13,11 +13,10 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
import json
|
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from graph.component.base import ComponentBase, ComponentParamBase
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
class BeginParam(ComponentParamBase):
|
class BeginParam(ComponentParamBase):
|
||||||
|
|
||||||
85
agent/component/bing.py
Normal file
85
agent/component/bing.py
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import requests
|
||||||
|
import pandas as pd
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class BingParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Bing component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
self.channel = "Webpages"
|
||||||
|
self.api_key = "YOUR_ACCESS_KEY"
|
||||||
|
self.country = "CN"
|
||||||
|
self.language = "en"
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.channel, "Bing Web Search or Bing News", ["Webpages", "News"])
|
||||||
|
self.check_empty(self.api_key, "Bing subscription key")
|
||||||
|
self.check_valid_value(self.country, "Bing Country",
|
||||||
|
['AR', 'AU', 'AT', 'BE', 'BR', 'CA', 'CL', 'DK', 'FI', 'FR', 'DE', 'HK', 'IN', 'ID',
|
||||||
|
'IT', 'JP', 'KR', 'MY', 'MX', 'NL', 'NZ', 'NO', 'CN', 'PL', 'PT', 'PH', 'RU', 'SA',
|
||||||
|
'ZA', 'ES', 'SE', 'CH', 'TW', 'TR', 'GB', 'US'])
|
||||||
|
self.check_valid_value(self.language, "Bing Languages",
|
||||||
|
['ar', 'eu', 'bn', 'bg', 'ca', 'ns', 'nt', 'hr', 'cs', 'da', 'nl', 'en', 'gb', 'et',
|
||||||
|
'fi', 'fr', 'gl', 'de', 'gu', 'he', 'hi', 'hu', 'is', 'it', 'jp', 'kn', 'ko', 'lv',
|
||||||
|
'lt', 'ms', 'ml', 'mr', 'nb', 'pl', 'br', 'pt', 'pa', 'ro', 'ru', 'sr', 'sk', 'sl',
|
||||||
|
'es', 'sv', 'ta', 'te', 'th', 'tr', 'uk', 'vi'])
|
||||||
|
|
||||||
|
|
||||||
|
class Bing(ComponentBase, ABC):
|
||||||
|
component_name = "Bing"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return Bing.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
headers = {"Ocp-Apim-Subscription-Key": self._param.api_key, 'Accept-Language': self._param.language}
|
||||||
|
params = {"q": ans, "textDecorations": True, "textFormat": "HTML", "cc": self._param.country,
|
||||||
|
"answerCount": 1, "promote": self._param.channel}
|
||||||
|
if self._param.channel == "Webpages":
|
||||||
|
response = requests.get("https://api.bing.microsoft.com/v7.0/search", headers=headers, params=params)
|
||||||
|
response.raise_for_status()
|
||||||
|
search_results = response.json()
|
||||||
|
bing_res = [{"content": '<a href="' + i["url"] + '">' + i["name"] + '</a> ' + i["snippet"]} for i in
|
||||||
|
search_results["webPages"]["value"]]
|
||||||
|
elif self._param.channel == "News":
|
||||||
|
response = requests.get("https://api.bing.microsoft.com/v7.0/news/search", headers=headers,
|
||||||
|
params=params)
|
||||||
|
response.raise_for_status()
|
||||||
|
search_results = response.json()
|
||||||
|
bing_res = [{"content": '<a href="' + i["url"] + '">' + i["name"] + '</a> ' + i["description"]} for i
|
||||||
|
in search_results['news']['value']]
|
||||||
|
except Exception as e:
|
||||||
|
return Bing.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not bing_res:
|
||||||
|
return Bing.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(bing_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
@ -14,13 +14,10 @@
|
|||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
from abc import ABC
|
from abc import ABC
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
from api.db import LLMType
|
from api.db import LLMType
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from graph.component import GenerateParam, Generate
|
from agent.component import GenerateParam, Generate
|
||||||
from graph.settings import DEBUG
|
from agent.settings import DEBUG
|
||||||
|
|
||||||
|
|
||||||
class CategorizeParam(GenerateParam):
|
class CategorizeParam(GenerateParam):
|
||||||
@ -85,6 +82,6 @@ class Categorize(Generate, ABC):
|
|||||||
if ans.lower().find(c.lower()) >= 0:
|
if ans.lower().find(c.lower()) >= 0:
|
||||||
return Categorize.be_output(self._param.category_description[c]["to"])
|
return Categorize.be_output(self._param.category_description[c]["to"])
|
||||||
|
|
||||||
return Categorize.be_output(self._param.category_description.items()[-1][1]["to"])
|
return Categorize.be_output(list(self._param.category_description.items())[-1][1]["to"])
|
||||||
|
|
||||||
|
|
||||||
@ -21,7 +21,7 @@ from api.db import LLMType
|
|||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from api.settings import retrievaler
|
from api.settings import retrievaler
|
||||||
from graph.component.base import ComponentBase, ComponentParamBase
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
class CiteParam(ComponentParamBase):
|
class CiteParam(ComponentParamBase):
|
||||||
36
agent/component/concentrator.py
Normal file
36
agent/component/concentrator.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class ConcentratorParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Concentrator component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class Concentrator(ComponentBase, ABC):
|
||||||
|
component_name = "Concentrator"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
return Concentrator.be_output("")
|
||||||
62
agent/component/deepl.py
Normal file
62
agent/component/deepl.py
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import re
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
import deepl
|
||||||
|
|
||||||
|
|
||||||
|
class DeepLParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the DeepL component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.auth_key = "xxx"
|
||||||
|
self.parameters = []
|
||||||
|
self.source_lang = 'ZH'
|
||||||
|
self.target_lang = 'EN-GB'
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.source_lang, "Source language",
|
||||||
|
['AR', 'BG', 'CS', 'DA', 'DE', 'EL', 'EN', 'ES', 'ET', 'FI', 'FR', 'HU', 'ID', 'IT',
|
||||||
|
'JA', 'KO', 'LT', 'LV', 'NB', 'NL', 'PL', 'PT', 'RO', 'RU', 'SK', 'SL', 'SV', 'TR',
|
||||||
|
'UK', 'ZH'])
|
||||||
|
self.check_valid_value(self.target_lang, "Target language",
|
||||||
|
['AR', 'BG', 'CS', 'DA', 'DE', 'EL', 'EN-GB', 'EN-US', 'ES', 'ET', 'FI', 'FR', 'HU',
|
||||||
|
'ID', 'IT', 'JA', 'KO', 'LT', 'LV', 'NB', 'NL', 'PL', 'PT-BR', 'PT-PT', 'RO', 'RU',
|
||||||
|
'SK', 'SL', 'SV', 'TR', 'UK', 'ZH'])
|
||||||
|
|
||||||
|
|
||||||
|
class DeepL(ComponentBase, ABC):
|
||||||
|
component_name = "GitHub"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return DeepL.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
translator = deepl.Translator(self._param.auth_key)
|
||||||
|
result = translator.translate_text(ans, source_lang=self._param.source_lang,
|
||||||
|
target_lang=self._param.target_lang)
|
||||||
|
|
||||||
|
return DeepL.be_output(result.text)
|
||||||
|
except Exception as e:
|
||||||
|
DeepL.be_output("**Error**:" + str(e))
|
||||||
66
agent/component/duckduckgo.py
Normal file
66
agent/component/duckduckgo.py
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
from duckduckgo_search import DDGS
|
||||||
|
import pandas as pd
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class DuckDuckGoParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the DuckDuckGo component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
self.channel = "text"
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.channel, "Web Search or News", ["text", "news"])
|
||||||
|
|
||||||
|
|
||||||
|
class DuckDuckGo(ComponentBase, ABC):
|
||||||
|
component_name = "DuckDuckGo"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return DuckDuckGo.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
if self._param.channel == "text":
|
||||||
|
with DDGS() as ddgs:
|
||||||
|
# {'title': '', 'href': '', 'body': ''}
|
||||||
|
duck_res = [{"content": '<a href="' + i["href"] + '">' + i["title"] + '</a> ' + i["body"]} for i
|
||||||
|
in ddgs.text(ans, max_results=self._param.top_n)]
|
||||||
|
elif self._param.channel == "news":
|
||||||
|
with DDGS() as ddgs:
|
||||||
|
# {'date': '', 'title': '', 'body': '', 'url': '', 'image': '', 'source': ''}
|
||||||
|
duck_res = [{"content": '<a href="' + i["url"] + '">' + i["title"] + '</a> ' + i["body"]} for i
|
||||||
|
in ddgs.news(ans, max_results=self._param.top_n)]
|
||||||
|
except Exception as e:
|
||||||
|
return DuckDuckGo.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not duck_res:
|
||||||
|
return DuckDuckGo.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(duck_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
99
agent/component/exesql.py
Normal file
99
agent/component/exesql.py
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import re
|
||||||
|
import pandas as pd
|
||||||
|
from peewee import MySQLDatabase, PostgresqlDatabase
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class ExeSQLParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the ExeSQL component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.db_type = "mysql"
|
||||||
|
self.database = ""
|
||||||
|
self.username = ""
|
||||||
|
self.host = ""
|
||||||
|
self.port = 3306
|
||||||
|
self.password = ""
|
||||||
|
self.loop = 3
|
||||||
|
self.top_n = 30
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_valid_value(self.db_type, "Choose DB type", ['mysql', 'postgresql', 'mariadb'])
|
||||||
|
self.check_empty(self.database, "Database name")
|
||||||
|
self.check_empty(self.username, "database username")
|
||||||
|
self.check_empty(self.host, "IP Address")
|
||||||
|
self.check_positive_integer(self.port, "IP Port")
|
||||||
|
self.check_empty(self.password, "Database password")
|
||||||
|
self.check_positive_integer(self.top_n, "Number of records")
|
||||||
|
|
||||||
|
|
||||||
|
class ExeSQL(ComponentBase, ABC):
|
||||||
|
component_name = "ExeSQL"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
if not hasattr(self, "_loop"):
|
||||||
|
setattr(self, "_loop", 0)
|
||||||
|
if self._loop >= self._param.loop:
|
||||||
|
self._loop = 0
|
||||||
|
raise Exception("Maximum loop time exceeds. Can't query the correct data via SQL statement.")
|
||||||
|
self._loop += 1
|
||||||
|
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = "".join(ans["content"]) if "content" in ans else ""
|
||||||
|
ans = re.sub(r'^.*?SELECT ', 'SELECT ', repr(ans), flags=re.IGNORECASE)
|
||||||
|
ans = re.sub(r';.*?SELECT ', '; SELECT ', ans, flags=re.IGNORECASE)
|
||||||
|
ans = re.sub(r';[^;]*$', r';', ans)
|
||||||
|
if not ans:
|
||||||
|
raise Exception("SQL statement not found!")
|
||||||
|
|
||||||
|
if self._param.db_type in ["mysql", "mariadb"]:
|
||||||
|
db = MySQLDatabase(self._param.database, user=self._param.username, host=self._param.host,
|
||||||
|
port=self._param.port, password=self._param.password)
|
||||||
|
elif self._param.db_type == 'postgresql':
|
||||||
|
db = PostgresqlDatabase(self._param.database, user=self._param.username, host=self._param.host,
|
||||||
|
port=self._param.port, password=self._param.password)
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.connect()
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception("Database Connection Failed! \n" + str(e))
|
||||||
|
sql_res = []
|
||||||
|
for single_sql in re.split(r';', ans.replace(r"\n", " ")):
|
||||||
|
if not single_sql:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
query = db.execute_sql(single_sql)
|
||||||
|
if query.rowcount == 0:
|
||||||
|
sql_res.append({"content": "\nTotal: " + str(query.rowcount) + "\n No record in the database!"})
|
||||||
|
continue
|
||||||
|
single_res = pd.DataFrame([i for i in query.fetchmany(size=self._param.top_n)])
|
||||||
|
single_res.columns = [i[0] for i in query.description]
|
||||||
|
sql_res.append({"content": "\nTotal: " + str(query.rowcount) + "\n" + single_res.to_markdown()})
|
||||||
|
except Exception as e:
|
||||||
|
sql_res.append({"content": "**Error**:" + str(e) + "\nError SQL Statement:" + single_sql})
|
||||||
|
pass
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
if not sql_res:
|
||||||
|
return ExeSQL.be_output("")
|
||||||
|
|
||||||
|
return pd.DataFrame(sql_res)
|
||||||
@ -15,13 +15,11 @@
|
|||||||
#
|
#
|
||||||
import re
|
import re
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from api.db import LLMType
|
from api.db import LLMType
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from api.settings import retrievaler
|
from api.settings import retrievaler
|
||||||
from graph.component.base import ComponentBase, ComponentParamBase
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
class GenerateParam(ComponentParamBase):
|
class GenerateParam(ComponentParamBase):
|
||||||
@ -63,62 +61,82 @@ class GenerateParam(ComponentParamBase):
|
|||||||
class Generate(ComponentBase):
|
class Generate(ComponentBase):
|
||||||
component_name = "Generate"
|
component_name = "Generate"
|
||||||
|
|
||||||
|
def get_dependent_components(self):
|
||||||
|
cpnts = [para["component_id"] for para in self._param.parameters]
|
||||||
|
return cpnts
|
||||||
|
|
||||||
|
def set_cite(self, retrieval_res, answer):
|
||||||
|
retrieval_res = retrieval_res.dropna(subset=["vector", "content_ltks"]).reset_index(drop=True)
|
||||||
|
if "empty_response" in retrieval_res.columns:
|
||||||
|
retrieval_res["empty_response"].fillna("", inplace=True)
|
||||||
|
answer, idx = retrievaler.insert_citations(answer, [ck["content_ltks"] for _, ck in retrieval_res.iterrows()],
|
||||||
|
[ck["vector"] for _, ck in retrieval_res.iterrows()],
|
||||||
|
LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
|
||||||
|
self._canvas.get_embedding_model()), tkweight=0.7,
|
||||||
|
vtweight=0.3)
|
||||||
|
doc_ids = set([])
|
||||||
|
recall_docs = []
|
||||||
|
for i in idx:
|
||||||
|
did = retrieval_res.loc[int(i), "doc_id"]
|
||||||
|
if did in doc_ids: continue
|
||||||
|
doc_ids.add(did)
|
||||||
|
recall_docs.append({"doc_id": did, "doc_name": retrieval_res.loc[int(i), "docnm_kwd"]})
|
||||||
|
|
||||||
|
del retrieval_res["vector"]
|
||||||
|
del retrieval_res["content_ltks"]
|
||||||
|
|
||||||
|
reference = {
|
||||||
|
"chunks": [ck.to_dict() for _, ck in retrieval_res.iterrows()],
|
||||||
|
"doc_aggs": recall_docs
|
||||||
|
}
|
||||||
|
|
||||||
|
if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
|
||||||
|
answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
|
||||||
|
res = {"content": answer, "reference": reference}
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
def _run(self, history, **kwargs):
|
def _run(self, history, **kwargs):
|
||||||
chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
|
chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
|
||||||
prompt = self._param.prompt
|
prompt = self._param.prompt
|
||||||
|
|
||||||
retrieval_res = self.get_input()
|
retrieval_res = self.get_input()
|
||||||
input = "\n- ".join(retrieval_res["content"])
|
input = (" - " + "\n - ".join(retrieval_res["content"])) if "content" in retrieval_res else ""
|
||||||
for para in self._param.parameters:
|
for para in self._param.parameters:
|
||||||
cpn = self._canvas.get_component(para["component_id"])["obj"]
|
cpn = self._canvas.get_component(para["component_id"])["obj"]
|
||||||
_, out = cpn.output(allow_partial=False)
|
_, out = cpn.output(allow_partial=False)
|
||||||
if "content" not in out.columns:
|
if "content" not in out.columns:
|
||||||
kwargs[para["key"]] = "Nothing"
|
kwargs[para["key"]] = "Nothing"
|
||||||
else:
|
else:
|
||||||
kwargs[para["key"]] = "\n - ".join(out["content"])
|
kwargs[para["key"]] = " - " + "\n - ".join(out["content"])
|
||||||
|
|
||||||
kwargs["input"] = input
|
kwargs["input"] = input
|
||||||
for n, v in kwargs.items():
|
for n, v in kwargs.items():
|
||||||
# prompt = re.sub(r"\{%s\}"%n, re.escape(str(v)), prompt)
|
prompt = re.sub(r"\{%s\}" % n, re.escape(str(v)), prompt)
|
||||||
prompt = re.sub(r"\{%s\}" % n, str(v), prompt)
|
|
||||||
|
|
||||||
if kwargs.get("stream"):
|
downstreams = self._canvas.get_component(self._id)["downstream"]
|
||||||
|
if kwargs.get("stream") and len(downstreams) == 1 and self._canvas.get_component(downstreams[0])[
|
||||||
|
"obj"].component_name.lower() == "answer":
|
||||||
return partial(self.stream_output, chat_mdl, prompt, retrieval_res)
|
return partial(self.stream_output, chat_mdl, prompt, retrieval_res)
|
||||||
|
|
||||||
if "empty_response" in retrieval_res.columns:
|
if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
|
||||||
return Generate.be_output(input)
|
res = {"content": "\n- ".join(retrieval_res["empty_response"]) if "\n- ".join(
|
||||||
|
retrieval_res["empty_response"]) else "Nothing found in knowledgebase!", "reference": []}
|
||||||
|
return pd.DataFrame([res])
|
||||||
|
|
||||||
ans = chat_mdl.chat(prompt, self._canvas.get_history(self._param.message_history_window_size),
|
ans = chat_mdl.chat(prompt, self._canvas.get_history(self._param.message_history_window_size),
|
||||||
self._param.gen_conf())
|
self._param.gen_conf())
|
||||||
|
|
||||||
if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
|
if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
|
||||||
ans, idx = retrievaler.insert_citations(ans,
|
res = self.set_cite(retrieval_res, ans)
|
||||||
[ck["content_ltks"]
|
return pd.DataFrame([res])
|
||||||
for _, ck in retrieval_res.iterrows()],
|
|
||||||
[ck["vector"]
|
|
||||||
for _, ck in retrieval_res.iterrows()],
|
|
||||||
LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
|
|
||||||
self._canvas.get_embedding_model()),
|
|
||||||
tkweight=0.7,
|
|
||||||
vtweight=0.3)
|
|
||||||
del retrieval_res["vector"]
|
|
||||||
retrieval_res = retrieval_res.to_dict("records")
|
|
||||||
df = []
|
|
||||||
for i in idx:
|
|
||||||
df.append(retrieval_res[int(i)])
|
|
||||||
r = re.search(r"^((.|[\r\n])*? ##%s\$\$)" % str(i), ans)
|
|
||||||
assert r, f"{i} => {ans}"
|
|
||||||
df[-1]["content"] = r.group(1)
|
|
||||||
ans = re.sub(r"^((.|[\r\n])*? ##%s\$\$)" % str(i), "", ans)
|
|
||||||
if ans: df.append({"content": ans})
|
|
||||||
return pd.DataFrame(df)
|
|
||||||
|
|
||||||
return Generate.be_output(ans)
|
return Generate.be_output(ans)
|
||||||
|
|
||||||
def stream_output(self, chat_mdl, prompt, retrieval_res):
|
def stream_output(self, chat_mdl, prompt, retrieval_res):
|
||||||
res = None
|
res = None
|
||||||
if "empty_response" in retrieval_res.columns and "\n- ".join(retrieval_res["content"]):
|
if "empty_response" in retrieval_res.columns and not "".join(retrieval_res["content"]):
|
||||||
res = {"content": "\n- ".join(retrieval_res["content"]), "reference": []}
|
res = {"content": "\n- ".join(retrieval_res["empty_response"]) if "\n- ".join(
|
||||||
|
retrieval_res["empty_response"]) else "Nothing found in knowledgebase!", "reference": []}
|
||||||
yield res
|
yield res
|
||||||
self.set_output(res)
|
self.set_output(res)
|
||||||
return
|
return
|
||||||
@ -131,34 +149,7 @@ class Generate(ComponentBase):
|
|||||||
yield res
|
yield res
|
||||||
|
|
||||||
if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
|
if self._param.cite and "content_ltks" in retrieval_res.columns and "vector" in retrieval_res.columns:
|
||||||
answer, idx = retrievaler.insert_citations(answer,
|
res = self.set_cite(retrieval_res, answer)
|
||||||
[ck["content_ltks"]
|
|
||||||
for _, ck in retrieval_res.iterrows()],
|
|
||||||
[ck["vector"]
|
|
||||||
for _, ck in retrieval_res.iterrows()],
|
|
||||||
LLMBundle(self._canvas.get_tenant_id(), LLMType.EMBEDDING,
|
|
||||||
self._canvas.get_embedding_model()),
|
|
||||||
tkweight=0.7,
|
|
||||||
vtweight=0.3)
|
|
||||||
doc_ids = set([])
|
|
||||||
recall_docs = []
|
|
||||||
for i in idx:
|
|
||||||
did = retrieval_res.loc[int(i), "doc_id"]
|
|
||||||
if did in doc_ids: continue
|
|
||||||
doc_ids.add(did)
|
|
||||||
recall_docs.append({"doc_id": did, "doc_name": retrieval_res.loc[int(i), "docnm_kwd"]})
|
|
||||||
|
|
||||||
del retrieval_res["vector"]
|
|
||||||
del retrieval_res["content_ltks"]
|
|
||||||
|
|
||||||
reference = {
|
|
||||||
"chunks": [ck.to_dict() for _, ck in retrieval_res.iterrows()],
|
|
||||||
"doc_aggs": recall_docs
|
|
||||||
}
|
|
||||||
|
|
||||||
if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
|
|
||||||
answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
|
|
||||||
res = {"content": answer, "reference": reference}
|
|
||||||
yield res
|
yield res
|
||||||
|
|
||||||
self.set_output(res)
|
self.set_output(res)
|
||||||
61
agent/component/github.py
Normal file
61
agent/component/github.py
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
import requests
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class GitHubParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the GitHub component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
|
||||||
|
|
||||||
|
class GitHub(ComponentBase, ABC):
|
||||||
|
component_name = "GitHub"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return GitHub.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
url = 'https://api.github.com/search/repositories?q=' + ans + '&sort=stars&order=desc&per_page=' + str(
|
||||||
|
self._param.top_n)
|
||||||
|
headers = {"Content-Type": "application/vnd.github+json", "X-GitHub-Api-Version": '2022-11-28'}
|
||||||
|
response = requests.get(url=url, headers=headers).json()
|
||||||
|
|
||||||
|
github_res = [{"content": '<a href="' + i["html_url"] + '">' + i["name"] + '</a>' + str(
|
||||||
|
i["description"]) + '\n stars:' + str(i['watchers'])} for i in response['items']]
|
||||||
|
except Exception as e:
|
||||||
|
return GitHub.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not github_res:
|
||||||
|
return GitHub.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(github_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
96
agent/component/google.py
Normal file
96
agent/component/google.py
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
from serpapi import GoogleSearch
|
||||||
|
import pandas as pd
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Google component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
self.api_key = "xxx"
|
||||||
|
self.country = "cn"
|
||||||
|
self.language = "en"
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_empty(self.api_key, "SerpApi API key")
|
||||||
|
self.check_valid_value(self.country, "Google Country",
|
||||||
|
['af', 'al', 'dz', 'as', 'ad', 'ao', 'ai', 'aq', 'ag', 'ar', 'am', 'aw', 'au', 'at',
|
||||||
|
'az', 'bs', 'bh', 'bd', 'bb', 'by', 'be', 'bz', 'bj', 'bm', 'bt', 'bo', 'ba', 'bw',
|
||||||
|
'bv', 'br', 'io', 'bn', 'bg', 'bf', 'bi', 'kh', 'cm', 'ca', 'cv', 'ky', 'cf', 'td',
|
||||||
|
'cl', 'cn', 'cx', 'cc', 'co', 'km', 'cg', 'cd', 'ck', 'cr', 'ci', 'hr', 'cu', 'cy',
|
||||||
|
'cz', 'dk', 'dj', 'dm', 'do', 'ec', 'eg', 'sv', 'gq', 'er', 'ee', 'et', 'fk', 'fo',
|
||||||
|
'fj', 'fi', 'fr', 'gf', 'pf', 'tf', 'ga', 'gm', 'ge', 'de', 'gh', 'gi', 'gr', 'gl',
|
||||||
|
'gd', 'gp', 'gu', 'gt', 'gn', 'gw', 'gy', 'ht', 'hm', 'va', 'hn', 'hk', 'hu', 'is',
|
||||||
|
'in', 'id', 'ir', 'iq', 'ie', 'il', 'it', 'jm', 'jp', 'jo', 'kz', 'ke', 'ki', 'kp',
|
||||||
|
'kr', 'kw', 'kg', 'la', 'lv', 'lb', 'ls', 'lr', 'ly', 'li', 'lt', 'lu', 'mo', 'mk',
|
||||||
|
'mg', 'mw', 'my', 'mv', 'ml', 'mt', 'mh', 'mq', 'mr', 'mu', 'yt', 'mx', 'fm', 'md',
|
||||||
|
'mc', 'mn', 'ms', 'ma', 'mz', 'mm', 'na', 'nr', 'np', 'nl', 'an', 'nc', 'nz', 'ni',
|
||||||
|
'ne', 'ng', 'nu', 'nf', 'mp', 'no', 'om', 'pk', 'pw', 'ps', 'pa', 'pg', 'py', 'pe',
|
||||||
|
'ph', 'pn', 'pl', 'pt', 'pr', 'qa', 're', 'ro', 'ru', 'rw', 'sh', 'kn', 'lc', 'pm',
|
||||||
|
'vc', 'ws', 'sm', 'st', 'sa', 'sn', 'rs', 'sc', 'sl', 'sg', 'sk', 'si', 'sb', 'so',
|
||||||
|
'za', 'gs', 'es', 'lk', 'sd', 'sr', 'sj', 'sz', 'se', 'ch', 'sy', 'tw', 'tj', 'tz',
|
||||||
|
'th', 'tl', 'tg', 'tk', 'to', 'tt', 'tn', 'tr', 'tm', 'tc', 'tv', 'ug', 'ua', 'ae',
|
||||||
|
'uk', 'gb', 'us', 'um', 'uy', 'uz', 'vu', 've', 'vn', 'vg', 'vi', 'wf', 'eh', 'ye',
|
||||||
|
'zm', 'zw'])
|
||||||
|
self.check_valid_value(self.language, "Google languages",
|
||||||
|
['af', 'ak', 'sq', 'ws', 'am', 'ar', 'hy', 'az', 'eu', 'be', 'bem', 'bn', 'bh',
|
||||||
|
'xx-bork', 'bs', 'br', 'bg', 'bt', 'km', 'ca', 'chr', 'ny', 'zh-cn', 'zh-tw', 'co',
|
||||||
|
'hr', 'cs', 'da', 'nl', 'xx-elmer', 'en', 'eo', 'et', 'ee', 'fo', 'tl', 'fi', 'fr',
|
||||||
|
'fy', 'gaa', 'gl', 'ka', 'de', 'el', 'kl', 'gn', 'gu', 'xx-hacker', 'ht', 'ha', 'haw',
|
||||||
|
'iw', 'hi', 'hu', 'is', 'ig', 'id', 'ia', 'ga', 'it', 'ja', 'jw', 'kn', 'kk', 'rw',
|
||||||
|
'rn', 'xx-klingon', 'kg', 'ko', 'kri', 'ku', 'ckb', 'ky', 'lo', 'la', 'lv', 'ln', 'lt',
|
||||||
|
'loz', 'lg', 'ach', 'mk', 'mg', 'ms', 'ml', 'mt', 'mv', 'mi', 'mr', 'mfe', 'mo', 'mn',
|
||||||
|
'sr-me', 'my', 'ne', 'pcm', 'nso', 'no', 'nn', 'oc', 'or', 'om', 'ps', 'fa',
|
||||||
|
'xx-pirate', 'pl', 'pt', 'pt-br', 'pt-pt', 'pa', 'qu', 'ro', 'rm', 'nyn', 'ru', 'gd',
|
||||||
|
'sr', 'sh', 'st', 'tn', 'crs', 'sn', 'sd', 'si', 'sk', 'sl', 'so', 'es', 'es-419', 'su',
|
||||||
|
'sw', 'sv', 'tg', 'ta', 'tt', 'te', 'th', 'ti', 'to', 'lua', 'tum', 'tr', 'tk', 'tw',
|
||||||
|
'ug', 'uk', 'ur', 'uz', 'vu', 'vi', 'cy', 'wo', 'xh', 'yi', 'yo', 'zu']
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Google(ComponentBase, ABC):
|
||||||
|
component_name = "Google"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return Google.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
client = GoogleSearch(
|
||||||
|
{"engine": "google", "q": ans, "api_key": self._param.api_key, "gl": self._param.country,
|
||||||
|
"hl": self._param.language, "num": self._param.top_n})
|
||||||
|
google_res = [{"content": '<a href="' + i["link"] + '">' + i["title"] + '</a> ' + i["snippet"]} for i in
|
||||||
|
client.get_dict()["organic_results"]]
|
||||||
|
except Exception as e:
|
||||||
|
return Google.be_output("**ERROR**: Existing Unavailable Parameters!")
|
||||||
|
|
||||||
|
if not google_res:
|
||||||
|
return Google.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(google_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
70
agent/component/googlescholar.py
Normal file
70
agent/component/googlescholar.py
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
from scholarly import scholarly
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleScholarParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the GoogleScholar component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 6
|
||||||
|
self.sort_by = 'relevance'
|
||||||
|
self.year_low = None
|
||||||
|
self.year_high = None
|
||||||
|
self.patents = True
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.sort_by, "GoogleScholar Sort_by", ['date', 'relevance'])
|
||||||
|
self.check_boolean(self.patents, "Whether or not to include patents, defaults to True")
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleScholar(ComponentBase, ABC):
|
||||||
|
component_name = "GoogleScholar"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return GoogleScholar.be_output("")
|
||||||
|
|
||||||
|
scholar_client = scholarly.search_pubs(ans, patents=self._param.patents, year_low=self._param.year_low,
|
||||||
|
year_high=self._param.year_high, sort_by=self._param.sort_by)
|
||||||
|
scholar_res = []
|
||||||
|
for i in range(self._param.top_n):
|
||||||
|
try:
|
||||||
|
pub = next(scholar_client)
|
||||||
|
scholar_res.append({"content": 'Title: ' + pub['bib']['title'] + '\n_Url: <a href="' + pub[
|
||||||
|
'pub_url'] + '"></a> ' + "\n author: " + ",".join(pub['bib']['author']) + '\n Abstract: ' + pub[
|
||||||
|
'bib'].get('abstract', 'no abstract')})
|
||||||
|
|
||||||
|
except StopIteration or Exception as e:
|
||||||
|
print("**ERROR** " + str(e))
|
||||||
|
break
|
||||||
|
|
||||||
|
if not scholar_res:
|
||||||
|
return GoogleScholar.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(scholar_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
130
agent/component/jin10.py
Normal file
130
agent/component/jin10.py
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
import json
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
import requests
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class Jin10Param(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Jin10 component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.type = "flash"
|
||||||
|
self.secret_key = "xxx"
|
||||||
|
self.flash_type = '1'
|
||||||
|
self.calendar_type = 'cj'
|
||||||
|
self.calendar_datatype = 'data'
|
||||||
|
self.symbols_type = 'GOODS'
|
||||||
|
self.symbols_datatype = 'symbols'
|
||||||
|
self.contain = ""
|
||||||
|
self.filter = ""
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_valid_value(self.type, "Type", ['flash', 'calendar', 'symbols', 'news'])
|
||||||
|
self.check_valid_value(self.flash_type, "Flash Type", ['1', '2', '3', '4', '5'])
|
||||||
|
self.check_valid_value(self.calendar_type, "Calendar Type", ['cj', 'qh', 'hk', 'us'])
|
||||||
|
self.check_valid_value(self.calendar_datatype, "Calendar DataType", ['data', 'event', 'holiday'])
|
||||||
|
self.check_valid_value(self.symbols_type, "Symbols Type", ['GOODS', 'FOREX', 'FUTURE', 'CRYPTO'])
|
||||||
|
self.check_valid_value(self.symbols_datatype, 'Symbols DataType', ['symbols', 'quotes'])
|
||||||
|
|
||||||
|
|
||||||
|
class Jin10(ComponentBase, ABC):
|
||||||
|
component_name = "Jin10"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return Jin10.be_output("")
|
||||||
|
|
||||||
|
jin10_res = []
|
||||||
|
headers = {'secret-key': self._param.secret_key}
|
||||||
|
try:
|
||||||
|
if self._param.type == "flash":
|
||||||
|
params = {
|
||||||
|
'category': self._param.flash_type,
|
||||||
|
'contain': self._param.contain,
|
||||||
|
'filter': self._param.filter
|
||||||
|
}
|
||||||
|
response = requests.get(
|
||||||
|
url='https://open-data-api.jin10.com/data-api/flash?category=' + self._param.flash_type,
|
||||||
|
headers=headers, data=json.dumps(params))
|
||||||
|
response = response.json()
|
||||||
|
for i in response['data']:
|
||||||
|
jin10_res.append({"content": i['data']['content']})
|
||||||
|
if self._param.type == "calendar":
|
||||||
|
params = {
|
||||||
|
'category': self._param.calendar_type
|
||||||
|
}
|
||||||
|
response = requests.get(
|
||||||
|
url='https://open-data-api.jin10.com/data-api/calendar/' + self._param.calendar_datatype + '?category=' + self._param.calendar_type,
|
||||||
|
headers=headers, data=json.dumps(params))
|
||||||
|
|
||||||
|
response = response.json()
|
||||||
|
jin10_res.append({"content": pd.DataFrame(response['data']).to_markdown()})
|
||||||
|
if self._param.type == "symbols":
|
||||||
|
params = {
|
||||||
|
'type': self._param.symbols_type
|
||||||
|
}
|
||||||
|
if self._param.symbols_datatype == "quotes":
|
||||||
|
params['codes'] = 'BTCUSD'
|
||||||
|
response = requests.get(
|
||||||
|
url='https://open-data-api.jin10.com/data-api/' + self._param.symbols_datatype + '?type=' + self._param.symbols_type,
|
||||||
|
headers=headers, data=json.dumps(params))
|
||||||
|
response = response.json()
|
||||||
|
if self._param.symbols_datatype == "symbols":
|
||||||
|
for i in response['data']:
|
||||||
|
i['Commodity Code'] = i['c']
|
||||||
|
i['Stock Exchange'] = i['e']
|
||||||
|
i['Commodity Name'] = i['n']
|
||||||
|
i['Commodity Type'] = i['t']
|
||||||
|
del i['c'], i['e'], i['n'], i['t']
|
||||||
|
if self._param.symbols_datatype == "quotes":
|
||||||
|
for i in response['data']:
|
||||||
|
i['Selling Price'] = i['a']
|
||||||
|
i['Buying Price'] = i['b']
|
||||||
|
i['Commodity Code'] = i['c']
|
||||||
|
i['Stock Exchange'] = i['e']
|
||||||
|
i['Highest Price'] = i['h']
|
||||||
|
i['Yesterday’s Closing Price'] = i['hc']
|
||||||
|
i['Lowest Price'] = i['l']
|
||||||
|
i['Opening Price'] = i['o']
|
||||||
|
i['Latest Price'] = i['p']
|
||||||
|
i['Market Quote Time'] = i['t']
|
||||||
|
del i['a'], i['b'], i['c'], i['e'], i['h'], i['hc'], i['l'], i['o'], i['p'], i['t']
|
||||||
|
jin10_res.append({"content": pd.DataFrame(response['data']).to_markdown()})
|
||||||
|
if self._param.type == "news":
|
||||||
|
params = {
|
||||||
|
'contain': self._param.contain,
|
||||||
|
'filter': self._param.filter
|
||||||
|
}
|
||||||
|
response = requests.get(
|
||||||
|
url='https://open-data-api.jin10.com/data-api/news',
|
||||||
|
headers=headers, data=json.dumps(params))
|
||||||
|
response = response.json()
|
||||||
|
jin10_res.append({"content": pd.DataFrame(response['data']).to_markdown()})
|
||||||
|
except Exception as e:
|
||||||
|
return Jin10.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not jin10_res:
|
||||||
|
return Jin10.be_output("")
|
||||||
|
|
||||||
|
return pd.DataFrame(jin10_res)
|
||||||
@ -17,8 +17,8 @@ import re
|
|||||||
from abc import ABC
|
from abc import ABC
|
||||||
from api.db import LLMType
|
from api.db import LLMType
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from graph.component import GenerateParam, Generate
|
from agent.component import GenerateParam, Generate
|
||||||
from graph.settings import DEBUG
|
from agent.settings import DEBUG
|
||||||
|
|
||||||
|
|
||||||
class KeywordExtractParam(GenerateParam):
|
class KeywordExtractParam(GenerateParam):
|
||||||
@ -16,10 +16,7 @@
|
|||||||
import random
|
import random
|
||||||
from abc import ABC
|
from abc import ABC
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
from graph.component.base import ComponentBase, ComponentParamBase
|
|
||||||
|
|
||||||
|
|
||||||
class MessageParam(ComponentParamBase):
|
class MessageParam(ComponentParamBase):
|
||||||
@ -46,7 +43,11 @@ class Message(ComponentBase, ABC):
|
|||||||
return Message.be_output(random.choice(self._param.messages))
|
return Message.be_output(random.choice(self._param.messages))
|
||||||
|
|
||||||
def stream_output(self):
|
def stream_output(self):
|
||||||
|
res = None
|
||||||
if self._param.messages:
|
if self._param.messages:
|
||||||
yield {"content": random.choice(self._param.messages)}
|
res = {"content": random.choice(self._param.messages)}
|
||||||
|
yield res
|
||||||
|
|
||||||
|
self.set_output(res)
|
||||||
|
|
||||||
|
|
||||||
69
agent/component/pubmed.py
Normal file
69
agent/component/pubmed.py
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
from Bio import Entrez
|
||||||
|
import re
|
||||||
|
import pandas as pd
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class PubMedParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the PubMed component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 5
|
||||||
|
self.email = "A.N.Other@example.com"
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
|
||||||
|
|
||||||
|
class PubMed(ComponentBase, ABC):
|
||||||
|
component_name = "PubMed"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return PubMed.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
Entrez.email = self._param.email
|
||||||
|
pubmedids = Entrez.read(Entrez.esearch(db='pubmed', retmax=self._param.top_n, term=ans))['IdList']
|
||||||
|
pubmedcnt = ET.fromstring(re.sub(r'<(/?)b>|<(/?)i>', '', Entrez.efetch(db='pubmed', id=",".join(pubmedids),
|
||||||
|
retmode="xml").read().decode(
|
||||||
|
"utf-8")))
|
||||||
|
pubmed_res = [{"content": 'Title:' + child.find("MedlineCitation").find("Article").find(
|
||||||
|
"ArticleTitle").text + '\nUrl:<a href=" https://pubmed.ncbi.nlm.nih.gov/' + child.find(
|
||||||
|
"MedlineCitation").find("PMID").text + '">' + '</a>\n' + 'Abstract:' + (
|
||||||
|
child.find("MedlineCitation").find("Article").find("Abstract").find(
|
||||||
|
"AbstractText").text if child.find("MedlineCitation").find(
|
||||||
|
"Article").find("Abstract") else "No abstract available")} for child in
|
||||||
|
pubmedcnt.findall("PubmedArticle")]
|
||||||
|
except Exception as e:
|
||||||
|
return PubMed.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not pubmed_res:
|
||||||
|
return PubMed.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(pubmed_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
111
agent/component/qweather.py
Normal file
111
agent/component/qweather.py
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
import requests
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class QWeatherParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the QWeather component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.web_apikey = "xxx"
|
||||||
|
self.lang = "zh"
|
||||||
|
self.type = "weather"
|
||||||
|
self.user_type = 'free'
|
||||||
|
self.error_code = {
|
||||||
|
"204": "The request was successful, but the region you are querying does not have the data you need at this time.",
|
||||||
|
"400": "Request error, may contain incorrect request parameters or missing mandatory request parameters.",
|
||||||
|
"401": "Authentication fails, possibly using the wrong KEY, wrong digital signature, wrong type of KEY (e.g. using the SDK's KEY to access the Web API).",
|
||||||
|
"402": "Exceeded the number of accesses or the balance is not enough to support continued access to the service, you can recharge, upgrade the accesses or wait for the accesses to be reset.",
|
||||||
|
"403": "No access, may be the binding PackageName, BundleID, domain IP address is inconsistent, or the data that requires additional payment.",
|
||||||
|
"404": "The queried data or region does not exist.",
|
||||||
|
"429": "Exceeded the limited QPM (number of accesses per minute), please refer to the QPM description",
|
||||||
|
"500": "No response or timeout, interface service abnormality please contact us"
|
||||||
|
}
|
||||||
|
# Weather
|
||||||
|
self.time_period = 'now'
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_empty(self.web_apikey, "BaiduFanyi APPID")
|
||||||
|
self.check_valid_value(self.type, "Type", ["weather", "indices", "airquality"])
|
||||||
|
self.check_valid_value(self.user_type, "Free subscription or paid subscription", ["free", "paid"])
|
||||||
|
self.check_valid_value(self.lang, "Use language",
|
||||||
|
['zh', 'zh-hant', 'en', 'de', 'es', 'fr', 'it', 'ja', 'ko', 'ru', 'hi', 'th', 'ar', 'pt',
|
||||||
|
'bn', 'ms', 'nl', 'el', 'la', 'sv', 'id', 'pl', 'tr', 'cs', 'et', 'vi', 'fil', 'fi',
|
||||||
|
'he', 'is', 'nb'])
|
||||||
|
self.check_valid_value(self.time_period, "Time period", ['now', '3d', '7d', '10d', '15d', '30d'])
|
||||||
|
|
||||||
|
|
||||||
|
class QWeather(ComponentBase, ABC):
|
||||||
|
component_name = "QWeather"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = "".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return QWeather.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.get(
|
||||||
|
url="https://geoapi.qweather.com/v2/city/lookup?location=" + ans + "&key=" + self._param.web_apikey).json()
|
||||||
|
if response["code"] == "200":
|
||||||
|
location_id = response["location"][0]["id"]
|
||||||
|
else:
|
||||||
|
return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
|
||||||
|
|
||||||
|
base_url = "https://api.qweather.com/v7/" if self._param.user_type == 'paid' else "https://devapi.qweather.com/v7/"
|
||||||
|
|
||||||
|
if self._param.type == "weather":
|
||||||
|
url = base_url + "weather/" + self._param.time_period + "?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang
|
||||||
|
response = requests.get(url=url).json()
|
||||||
|
if response["code"] == "200":
|
||||||
|
if self._param.time_period == "now":
|
||||||
|
return QWeather.be_output(str(response["now"]))
|
||||||
|
else:
|
||||||
|
qweather_res = [{"content": str(i) + "\n"} for i in response["daily"]]
|
||||||
|
if not qweather_res:
|
||||||
|
return QWeather.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(qweather_res)
|
||||||
|
return df
|
||||||
|
else:
|
||||||
|
return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
|
||||||
|
|
||||||
|
elif self._param.type == "indices":
|
||||||
|
url = base_url + "indices/1d?type=0&location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang
|
||||||
|
response = requests.get(url=url).json()
|
||||||
|
if response["code"] == "200":
|
||||||
|
indices_res = response["daily"][0]["date"] + "\n" + "\n".join(
|
||||||
|
[i["name"] + ": " + i["category"] + ", " + i["text"] for i in response["daily"]])
|
||||||
|
return QWeather.be_output(indices_res)
|
||||||
|
|
||||||
|
else:
|
||||||
|
return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
|
||||||
|
|
||||||
|
elif self._param.type == "airquality":
|
||||||
|
url = base_url + "air/now?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang
|
||||||
|
response = requests.get(url=url).json()
|
||||||
|
if response["code"] == "200":
|
||||||
|
return QWeather.be_output(str(response["now"]))
|
||||||
|
else:
|
||||||
|
return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
|
||||||
|
except Exception as e:
|
||||||
|
return QWeather.be_output("**Error**" + str(e))
|
||||||
@ -16,7 +16,7 @@
|
|||||||
from abc import ABC
|
from abc import ABC
|
||||||
from api.db import LLMType
|
from api.db import LLMType
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from graph.component import GenerateParam, Generate
|
from agent.component import GenerateParam, Generate
|
||||||
from rag.utils import num_tokens_from_string, encoder
|
from rag.utils import num_tokens_from_string, encoder
|
||||||
|
|
||||||
|
|
||||||
@ -21,7 +21,7 @@ from api.db import LLMType
|
|||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from api.settings import retrievaler
|
from api.settings import retrievaler
|
||||||
from graph.component.base import ComponentBase, ComponentParamBase
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
class RetrievalParam(ComponentParamBase):
|
class RetrievalParam(ComponentParamBase):
|
||||||
@ -54,8 +54,8 @@ class Retrieval(ComponentBase, ABC):
|
|||||||
for role, cnt in history[::-1][:self._param.message_history_window_size]:
|
for role, cnt in history[::-1][:self._param.message_history_window_size]:
|
||||||
if role != "user":continue
|
if role != "user":continue
|
||||||
query.append(cnt)
|
query.append(cnt)
|
||||||
query = "\n".join(query)
|
# query = "\n".join(query)
|
||||||
|
query = query[0]
|
||||||
kbs = KnowledgebaseService.get_by_ids(self._param.kb_ids)
|
kbs = KnowledgebaseService.get_by_ids(self._param.kb_ids)
|
||||||
if not kbs:
|
if not kbs:
|
||||||
raise ValueError("Can't find knowledgebases by {}".format(self._param.kb_ids))
|
raise ValueError("Can't find knowledgebases by {}".format(self._param.kb_ids))
|
||||||
@ -75,8 +75,9 @@ class Retrieval(ComponentBase, ABC):
|
|||||||
aggs=False, rerank_mdl=rerank_mdl)
|
aggs=False, rerank_mdl=rerank_mdl)
|
||||||
|
|
||||||
if not kbinfos["chunks"]:
|
if not kbinfos["chunks"]:
|
||||||
df = Retrieval.be_output(self._param.empty_response)
|
df = Retrieval.be_output("")
|
||||||
df["empty_response"] = True
|
if self._param.empty_response and self._param.empty_response.strip():
|
||||||
|
df["empty_response"] = self._param.empty_response
|
||||||
return df
|
return df
|
||||||
|
|
||||||
df = pd.DataFrame(kbinfos["chunks"])
|
df = pd.DataFrame(kbinfos["chunks"])
|
||||||
@ -16,7 +16,7 @@
|
|||||||
from abc import ABC
|
from abc import ABC
|
||||||
from api.db import LLMType
|
from api.db import LLMType
|
||||||
from api.db.services.llm_service import LLMBundle
|
from api.db.services.llm_service import LLMBundle
|
||||||
from graph.component import GenerateParam, Generate
|
from agent.component import GenerateParam, Generate
|
||||||
|
|
||||||
|
|
||||||
class RewriteQuestionParam(GenerateParam):
|
class RewriteQuestionParam(GenerateParam):
|
||||||
@ -54,7 +54,7 @@ class RewriteQuestion(Generate, ABC):
|
|||||||
setattr(self, "_loop", 0)
|
setattr(self, "_loop", 0)
|
||||||
if self._loop >= self._param.loop:
|
if self._loop >= self._param.loop:
|
||||||
self._loop = 0
|
self._loop = 0
|
||||||
raise Exception("Maximum loop time exceeds. Can't find relevant information.")
|
raise Exception("Sorry! Nothing relevant found.")
|
||||||
self._loop += 1
|
self._loop += 1
|
||||||
q = "Question: "
|
q = "Question: "
|
||||||
for r, c in self._canvas.history[::-1]:
|
for r, c in self._canvas.history[::-1]:
|
||||||
@ -65,6 +65,8 @@ class RewriteQuestion(Generate, ABC):
|
|||||||
chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
|
chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.CHAT, self._param.llm_id)
|
||||||
ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": q}],
|
ans = chat_mdl.chat(self._param.get_prompt(), [{"role": "user", "content": q}],
|
||||||
self._param.gen_conf())
|
self._param.gen_conf())
|
||||||
|
self._canvas.history.pop()
|
||||||
|
self._canvas.history.append(("user", ans))
|
||||||
|
|
||||||
print(ans, ":::::::::::::::::::::::::::::::::")
|
print(ans, ":::::::::::::::::::::::::::::::::")
|
||||||
return RewriteQuestion.be_output(ans)
|
return RewriteQuestion.be_output(ans)
|
||||||
106
agent/component/switch.py
Normal file
106
agent/component/switch.py
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class SwitchParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Switch component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"logical_operator" : "and | or"
|
||||||
|
"items" : [
|
||||||
|
{"cpn_id": "categorize:0", "operator": "contains", "value": ""},
|
||||||
|
{"cpn_id": "categorize:0", "operator": "contains", "value": ""},...],
|
||||||
|
"to": ""
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
self.conditions = []
|
||||||
|
self.end_cpn_id = "answer:0"
|
||||||
|
self.operators = ['contains', 'not contains', 'start with', 'end with', 'empty', 'not empty', '=', '≠', '>',
|
||||||
|
'<', '≥', '≤']
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_empty(self.conditions, "[Switch] conditions")
|
||||||
|
for cond in self.conditions:
|
||||||
|
if not cond["to"]: raise ValueError(f"[Switch] 'To' can not be empty!")
|
||||||
|
|
||||||
|
|
||||||
|
class Switch(ComponentBase, ABC):
|
||||||
|
component_name = "Switch"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
for cond in self._param.conditions:
|
||||||
|
res = []
|
||||||
|
for item in cond["items"]:
|
||||||
|
out = self._canvas.get_component(item["cpn_id"])["obj"].output()[1]
|
||||||
|
cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
|
||||||
|
res.append(self.process_operator(cpn_input, item["operator"], item["value"]))
|
||||||
|
if cond["logical_operator"] != "and" and any(res):
|
||||||
|
return Switch.be_output(cond["to"])
|
||||||
|
|
||||||
|
if all(res):
|
||||||
|
return Switch.be_output(cond["to"])
|
||||||
|
|
||||||
|
return Switch.be_output(self._param.end_cpn_id)
|
||||||
|
|
||||||
|
def process_operator(self, input: str, operator: str, value: str) -> bool:
|
||||||
|
if not isinstance(input, str) or not isinstance(value, str):
|
||||||
|
raise ValueError('Invalid input or value type: string')
|
||||||
|
|
||||||
|
if operator == "contains":
|
||||||
|
return True if value.lower() in input.lower() else False
|
||||||
|
elif operator == "not contains":
|
||||||
|
return True if value.lower() not in input.lower() else False
|
||||||
|
elif operator == "start with":
|
||||||
|
return True if input.lower().startswith(value.lower()) else False
|
||||||
|
elif operator == "end with":
|
||||||
|
return True if input.lower().endswith(value.lower()) else False
|
||||||
|
elif operator == "empty":
|
||||||
|
return True if not input else False
|
||||||
|
elif operator == "not empty":
|
||||||
|
return True if input else False
|
||||||
|
elif operator == "=":
|
||||||
|
return True if input == value else False
|
||||||
|
elif operator == "≠":
|
||||||
|
return True if input != value else False
|
||||||
|
elif operator == ">":
|
||||||
|
try:
|
||||||
|
return True if float(input) > float(value) else False
|
||||||
|
except Exception as e:
|
||||||
|
return True if input > value else False
|
||||||
|
elif operator == "<":
|
||||||
|
try:
|
||||||
|
return True if float(input) < float(value) else False
|
||||||
|
except Exception as e:
|
||||||
|
return True if input < value else False
|
||||||
|
elif operator == "≥":
|
||||||
|
try:
|
||||||
|
return True if float(input) >= float(value) else False
|
||||||
|
except Exception as e:
|
||||||
|
return True if input >= value else False
|
||||||
|
elif operator == "≤":
|
||||||
|
try:
|
||||||
|
return True if float(input) <= float(value) else False
|
||||||
|
except Exception as e:
|
||||||
|
return True if input <= value else False
|
||||||
|
|
||||||
|
raise ValueError('Not supported operator' + operator)
|
||||||
72
agent/component/tushare.py
Normal file
72
agent/component/tushare.py
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
import json
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
import time
|
||||||
|
import requests
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class TuShareParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the TuShare component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.token = "xxx"
|
||||||
|
self.src = "eastmoney"
|
||||||
|
self.start_date = "2024-01-01 09:00:00"
|
||||||
|
self.end_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||||||
|
self.keyword = ""
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_valid_value(self.src, "Quick News Source",
|
||||||
|
["sina", "wallstreetcn", "10jqka", "eastmoney", "yuncaijing", "fenghuang", "jinrongjie"])
|
||||||
|
|
||||||
|
|
||||||
|
class TuShare(ComponentBase, ABC):
|
||||||
|
component_name = "TuShare"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = ",".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return TuShare.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
tus_res = []
|
||||||
|
params = {
|
||||||
|
"api_name": "news",
|
||||||
|
"token": self._param.token,
|
||||||
|
"params": {"src": self._param.src, "start_date": self._param.start_date,
|
||||||
|
"end_date": self._param.end_date}
|
||||||
|
}
|
||||||
|
response = requests.post(url="http://api.tushare.pro", data=json.dumps(params).encode('utf-8'))
|
||||||
|
response = response.json()
|
||||||
|
if response['code'] != 0:
|
||||||
|
return TuShare.be_output(response['msg'])
|
||||||
|
df = pd.DataFrame(response['data']['items'])
|
||||||
|
df.columns = response['data']['fields']
|
||||||
|
tus_res.append({"content": (df[df['content'].str.contains(self._param.keyword, case=False)]).to_markdown()})
|
||||||
|
except Exception as e:
|
||||||
|
return TuShare.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not tus_res:
|
||||||
|
return TuShare.be_output("")
|
||||||
|
|
||||||
|
return pd.DataFrame(tus_res)
|
||||||
80
agent/component/wencai.py
Normal file
80
agent/component/wencai.py
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
import pywencai
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class WenCaiParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the WenCai component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
self.query_type = "stock"
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.query_type, "Query type",
|
||||||
|
['stock', 'zhishu', 'fund', 'hkstock', 'usstock', 'threeboard', 'conbond', 'insurance',
|
||||||
|
'futures', 'lccp',
|
||||||
|
'foreign_exchange'])
|
||||||
|
|
||||||
|
|
||||||
|
class WenCai(ComponentBase, ABC):
|
||||||
|
component_name = "WenCai"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = ",".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return WenCai.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
wencai_res = []
|
||||||
|
res = pywencai.get(query=ans, query_type=self._param.query_type, perpage=self._param.top_n)
|
||||||
|
if isinstance(res, pd.DataFrame):
|
||||||
|
wencai_res.append({"content": res.to_markdown()})
|
||||||
|
if isinstance(res, dict):
|
||||||
|
for item in res.items():
|
||||||
|
if isinstance(item[1], list):
|
||||||
|
wencai_res.append({"content": item[0] + "\n" + pd.DataFrame(item[1]).to_markdown()})
|
||||||
|
continue
|
||||||
|
if isinstance(item[1], str):
|
||||||
|
wencai_res.append({"content": item[0] + "\n" + item[1]})
|
||||||
|
continue
|
||||||
|
if isinstance(item[1], dict):
|
||||||
|
if "meta" in item[1].keys():
|
||||||
|
continue
|
||||||
|
wencai_res.append({"content": pd.DataFrame.from_dict(item[1], orient='index').to_markdown()})
|
||||||
|
continue
|
||||||
|
if isinstance(item[1], pd.DataFrame):
|
||||||
|
if "image_url" in item[1].columns:
|
||||||
|
continue
|
||||||
|
wencai_res.append({"content": item[1].to_markdown()})
|
||||||
|
continue
|
||||||
|
|
||||||
|
wencai_res.append({"content": item[0] + "\n" + str(item[1])})
|
||||||
|
except Exception as e:
|
||||||
|
return WenCai.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not wencai_res:
|
||||||
|
return WenCai.be_output("")
|
||||||
|
|
||||||
|
return pd.DataFrame(wencai_res)
|
||||||
69
agent/component/wikipedia.py
Normal file
69
agent/component/wikipedia.py
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
import random
|
||||||
|
from abc import ABC
|
||||||
|
from functools import partial
|
||||||
|
import wikipedia
|
||||||
|
import pandas as pd
|
||||||
|
from agent.settings import DEBUG
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
|
||||||
|
|
||||||
|
class WikipediaParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the Wikipedia component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.top_n = 10
|
||||||
|
self.language = "en"
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_positive_integer(self.top_n, "Top N")
|
||||||
|
self.check_valid_value(self.language, "Wikipedia languages",
|
||||||
|
['af', 'pl', 'ar', 'ast', 'az', 'bg', 'nan', 'bn', 'be', 'ca', 'cs', 'cy', 'da', 'de',
|
||||||
|
'et', 'el', 'en', 'es', 'eo', 'eu', 'fa', 'fr', 'gl', 'ko', 'hy', 'hi', 'hr', 'id',
|
||||||
|
'it', 'he', 'ka', 'lld', 'la', 'lv', 'lt', 'hu', 'mk', 'arz', 'ms', 'min', 'my', 'nl',
|
||||||
|
'ja', 'nb', 'nn', 'ce', 'uz', 'pt', 'kk', 'ro', 'ru', 'ceb', 'sk', 'sl', 'sr', 'sh',
|
||||||
|
'fi', 'sv', 'ta', 'tt', 'th', 'tg', 'azb', 'tr', 'uk', 'ur', 'vi', 'war', 'zh', 'yue'])
|
||||||
|
|
||||||
|
|
||||||
|
class Wikipedia(ComponentBase, ABC):
|
||||||
|
component_name = "Wikipedia"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = " - ".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return Wikipedia.be_output("")
|
||||||
|
|
||||||
|
try:
|
||||||
|
wiki_res = []
|
||||||
|
wikipedia.set_lang(self._param.language)
|
||||||
|
wiki_engine = wikipedia
|
||||||
|
for wiki_key in wiki_engine.search(ans, results=self._param.top_n):
|
||||||
|
page = wiki_engine.page(title=wiki_key, auto_suggest=False)
|
||||||
|
wiki_res.append({"content": '<a href="' + page.url + '">' + page.title + '</a> ' + page.summary})
|
||||||
|
except Exception as e:
|
||||||
|
return Wikipedia.be_output("**ERROR**: " + str(e))
|
||||||
|
|
||||||
|
if not wiki_res:
|
||||||
|
return Wikipedia.be_output("")
|
||||||
|
|
||||||
|
df = pd.DataFrame(wiki_res)
|
||||||
|
if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
|
||||||
|
return df
|
||||||
83
agent/component/yahoofinance.py
Normal file
83
agent/component/yahoofinance.py
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from abc import ABC
|
||||||
|
import pandas as pd
|
||||||
|
from agent.component.base import ComponentBase, ComponentParamBase
|
||||||
|
import yfinance as yf
|
||||||
|
|
||||||
|
|
||||||
|
class YahooFinanceParam(ComponentParamBase):
|
||||||
|
"""
|
||||||
|
Define the YahooFinance component parameters.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.info = True
|
||||||
|
self.history = False
|
||||||
|
self.count = False
|
||||||
|
self.financials = False
|
||||||
|
self.income_stmt = False
|
||||||
|
self.balance_sheet = False
|
||||||
|
self.cash_flow_statement = False
|
||||||
|
self.news = True
|
||||||
|
|
||||||
|
def check(self):
|
||||||
|
self.check_boolean(self.info, "get all stock info")
|
||||||
|
self.check_boolean(self.history, "get historical market data")
|
||||||
|
self.check_boolean(self.count, "show share count")
|
||||||
|
self.check_boolean(self.financials, "show financials")
|
||||||
|
self.check_boolean(self.income_stmt, "income statement")
|
||||||
|
self.check_boolean(self.balance_sheet, "balance sheet")
|
||||||
|
self.check_boolean(self.cash_flow_statement, "cash flow statement")
|
||||||
|
self.check_boolean(self.news, "show news")
|
||||||
|
|
||||||
|
|
||||||
|
class YahooFinance(ComponentBase, ABC):
|
||||||
|
component_name = "YahooFinance"
|
||||||
|
|
||||||
|
def _run(self, history, **kwargs):
|
||||||
|
ans = self.get_input()
|
||||||
|
ans = "".join(ans["content"]) if "content" in ans else ""
|
||||||
|
if not ans:
|
||||||
|
return YahooFinance.be_output("")
|
||||||
|
|
||||||
|
yohoo_res = []
|
||||||
|
try:
|
||||||
|
msft = yf.Ticker(ans)
|
||||||
|
if self._param.info:
|
||||||
|
yohoo_res.append({"content": "info:\n" + pd.Series(msft.info).to_markdown() + "\n"})
|
||||||
|
if self._param.history:
|
||||||
|
yohoo_res.append({"content": "history:\n" + msft.history().to_markdown() + "\n"})
|
||||||
|
if self._param.financials:
|
||||||
|
yohoo_res.append({"content": "calendar:\n" + pd.DataFrame(msft.calendar).to_markdown() + "\n"})
|
||||||
|
if self._param.balance_sheet:
|
||||||
|
yohoo_res.append({"content": "balance sheet:\n" + msft.balance_sheet.to_markdown() + "\n"})
|
||||||
|
yohoo_res.append(
|
||||||
|
{"content": "quarterly balance sheet:\n" + msft.quarterly_balance_sheet.to_markdown() + "\n"})
|
||||||
|
if self._param.cash_flow_statement:
|
||||||
|
yohoo_res.append({"content": "cash flow statement:\n" + msft.cashflow.to_markdown() + "\n"})
|
||||||
|
yohoo_res.append(
|
||||||
|
{"content": "quarterly cash flow statement:\n" + msft.quarterly_cashflow.to_markdown() + "\n"})
|
||||||
|
if self._param.news:
|
||||||
|
yohoo_res.append({"content": "news:\n" + pd.DataFrame(msft.news).to_markdown() + "\n"})
|
||||||
|
except Exception as e:
|
||||||
|
print("**ERROR** " + str(e))
|
||||||
|
|
||||||
|
if not yohoo_res:
|
||||||
|
return YahooFinance.be_output("")
|
||||||
|
|
||||||
|
return pd.DataFrame(yohoo_res)
|
||||||
687
agent/templates/DB Assistant.json
Normal file
687
agent/templates/DB Assistant.json
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
1782
agent/templates/general_chat_bot.json
Normal file
1782
agent/templates/general_chat_bot.json
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
406
agent/templates/investment_advisor.json
Normal file
406
agent/templates/investment_advisor.json
Normal file
File diff suppressed because one or more lines are too long
492
agent/templates/medical_consultation.json
Normal file
492
agent/templates/medical_consultation.json
Normal file
File diff suppressed because one or more lines are too long
445
agent/templates/text2sql.json
Normal file
445
agent/templates/text2sql.json
Normal file
File diff suppressed because one or more lines are too long
547
agent/templates/websearch_assistant.json
Normal file
547
agent/templates/websearch_assistant.json
Normal file
File diff suppressed because one or more lines are too long
@ -16,9 +16,8 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import os
|
import os
|
||||||
from functools import partial
|
from functools import partial
|
||||||
import readline
|
from agent.canvas import Canvas
|
||||||
from graph.canvas import Canvas
|
from agent.settings import DEBUG
|
||||||
from graph.settings import DEBUG
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
129
agent/test/dsl_examples/baidu_generate_and_switch.json
Normal file
129
agent/test/dsl_examples/baidu_generate_and_switch.json
Normal file
@ -0,0 +1,129 @@
|
|||||||
|
{
|
||||||
|
"components": {
|
||||||
|
"begin": {
|
||||||
|
"obj":{
|
||||||
|
"component_name": "Begin",
|
||||||
|
"params": {
|
||||||
|
"prologue": "Hi there!"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": []
|
||||||
|
},
|
||||||
|
"answer:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Answer",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["baidu:0"],
|
||||||
|
"upstream": ["begin", "message:0","message:1"]
|
||||||
|
},
|
||||||
|
"baidu:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Baidu",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["generate:0"],
|
||||||
|
"upstream": ["answer:0"]
|
||||||
|
},
|
||||||
|
"generate:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Generate",
|
||||||
|
"params": {
|
||||||
|
"llm_id": "deepseek-chat",
|
||||||
|
"prompt": "You are an intelligent assistant. Please answer the user's question based on what Baidu searched. First, please output the user's question and the content searched by Baidu, and then answer yes, no, or i don't know.Here is the user's question:{user_input}The above is the user's question.Here is what Baidu searched for:{baidu}The above is the content searched by Baidu.",
|
||||||
|
"temperature": 0.2
|
||||||
|
},
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"component_id": "answer:0",
|
||||||
|
"id": "69415446-49bf-4d4b-8ec9-ac86066f7709",
|
||||||
|
"key": "user_input"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_id": "baidu:0",
|
||||||
|
"id": "83363c2a-00a8-402f-a45c-ddc4097d7d8b",
|
||||||
|
"key": "baidu"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"downstream": ["switch:0"],
|
||||||
|
"upstream": ["baidu:0"]
|
||||||
|
},
|
||||||
|
"switch:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Switch",
|
||||||
|
"params": {
|
||||||
|
"conditions": [
|
||||||
|
{
|
||||||
|
"logical_operator" : "or",
|
||||||
|
"items" : [
|
||||||
|
{"cpn_id": "generate:0", "operator": "contains", "value": "yes"},
|
||||||
|
{"cpn_id": "generate:0", "operator": "contains", "value": "yeah"}
|
||||||
|
],
|
||||||
|
"to": "message:0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"logical_operator" : "and",
|
||||||
|
"items" : [
|
||||||
|
{"cpn_id": "generate:0", "operator": "contains", "value": "no"},
|
||||||
|
{"cpn_id": "generate:0", "operator": "not contains", "value": "yes"},
|
||||||
|
{"cpn_id": "generate:0", "operator": "not contains", "value": "know"}
|
||||||
|
],
|
||||||
|
"to": "message:1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"logical_operator" : "",
|
||||||
|
"items" : [
|
||||||
|
{"cpn_id": "generate:0", "operator": "contains", "value": "know"}
|
||||||
|
],
|
||||||
|
"to": "message:2"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"end_cpn_id": "answer:0"
|
||||||
|
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["message:0","message:1"],
|
||||||
|
"upstream": ["generate:0"]
|
||||||
|
},
|
||||||
|
"message:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": ["YES YES YES YES YES YES YES YES YES YES YES YES"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
"upstream": ["switch:0"],
|
||||||
|
"downstream": ["answer:0"]
|
||||||
|
},
|
||||||
|
"message:1": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": ["NO NO NO NO NO NO NO NO NO NO NO NO NO NO"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
"upstream": ["switch:0"],
|
||||||
|
"downstream": ["answer:0"]
|
||||||
|
},
|
||||||
|
"message:2": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": ["I DON'T KNOW---------------------------"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
"upstream": ["switch:0"],
|
||||||
|
"downstream": ["answer:0"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"history": [],
|
||||||
|
"messages": [],
|
||||||
|
"reference": {},
|
||||||
|
"path": [],
|
||||||
|
"answer": []
|
||||||
|
}
|
||||||
@ -26,20 +26,48 @@
|
|||||||
"category_description": {
|
"category_description": {
|
||||||
"product_related": {
|
"product_related": {
|
||||||
"description": "The question is about the product usage, appearance and how it works.",
|
"description": "The question is about the product usage, appearance and how it works.",
|
||||||
"examples": "Why it always beaming?\nHow to install it onto the wall?\nIt leaks, what to do?"
|
"examples": "Why it always beaming?\nHow to install it onto the wall?\nIt leaks, what to do?",
|
||||||
|
"to": "message:0"
|
||||||
},
|
},
|
||||||
"others": {
|
"others": {
|
||||||
"description": "The question is not about the product usage, appearance and how it works.",
|
"description": "The question is not about the product usage, appearance and how it works.",
|
||||||
"examples": "How are you doing?\nWhat is your name?\nAre you a robot?\nWhat's the weather?\nWill it rain?"
|
"examples": "How are you doing?\nWhat is your name?\nAre you a robot?\nWhat's the weather?\nWill it rain?",
|
||||||
|
"to": "message:1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"downstream": [],
|
"downstream": ["message:0","message:1"],
|
||||||
"upstream": ["answer:0"]
|
"upstream": ["answer:0"]
|
||||||
|
},
|
||||||
|
"message:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": [
|
||||||
|
"Message 0!!!!!!!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["categorize:0"]
|
||||||
|
},
|
||||||
|
"message:1": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": [
|
||||||
|
"Message 1!!!!!!!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["categorize:0"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"history": [],
|
"history": [],
|
||||||
|
"messages": [],
|
||||||
"path": [],
|
"path": [],
|
||||||
|
"reference": [],
|
||||||
"answer": []
|
"answer": []
|
||||||
}
|
}
|
||||||
113
agent/test/dsl_examples/concentrator_message.json
Normal file
113
agent/test/dsl_examples/concentrator_message.json
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
{
|
||||||
|
"components": {
|
||||||
|
"begin": {
|
||||||
|
"obj":{
|
||||||
|
"component_name": "Begin",
|
||||||
|
"params": {
|
||||||
|
"prologue": "Hi there!"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": []
|
||||||
|
},
|
||||||
|
"answer:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Answer",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["categorize:0"],
|
||||||
|
"upstream": ["begin"]
|
||||||
|
},
|
||||||
|
"categorize:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Categorize",
|
||||||
|
"params": {
|
||||||
|
"llm_id": "deepseek-chat",
|
||||||
|
"category_description": {
|
||||||
|
"product_related": {
|
||||||
|
"description": "The question is about the product usage, appearance and how it works.",
|
||||||
|
"examples": "Why it always beaming?\nHow to install it onto the wall?\nIt leaks, what to do?",
|
||||||
|
"to": "concentrator:0"
|
||||||
|
},
|
||||||
|
"others": {
|
||||||
|
"description": "The question is not about the product usage, appearance and how it works.",
|
||||||
|
"examples": "How are you doing?\nWhat is your name?\nAre you a robot?\nWhat's the weather?\nWill it rain?",
|
||||||
|
"to": "concentrator:1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["concentrator:0","concentrator:1"],
|
||||||
|
"upstream": ["answer:0"]
|
||||||
|
},
|
||||||
|
"concentrator:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Concentrator",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["message:0"],
|
||||||
|
"upstream": ["categorize:0"]
|
||||||
|
},
|
||||||
|
"concentrator:1": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Concentrator",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["message:1_0","message:1_1","message:1_2"],
|
||||||
|
"upstream": ["categorize:0"]
|
||||||
|
},
|
||||||
|
"message:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": [
|
||||||
|
"Message 0_0!!!!!!!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["concentrator:0"]
|
||||||
|
},
|
||||||
|
"message:1_0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": [
|
||||||
|
"Message 1_0!!!!!!!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["concentrator:1"]
|
||||||
|
},
|
||||||
|
"message:1_1": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": [
|
||||||
|
"Message 1_1!!!!!!!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["concentrator:1"]
|
||||||
|
},
|
||||||
|
"message:1_2": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Message",
|
||||||
|
"params": {
|
||||||
|
"messages": [
|
||||||
|
"Message 1_2!!!!!!!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["concentrator:1"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"history": [],
|
||||||
|
"messages": [],
|
||||||
|
"path": [],
|
||||||
|
"reference": [],
|
||||||
|
"answer": []
|
||||||
|
}
|
||||||
43
agent/test/dsl_examples/exesql.json
Normal file
43
agent/test/dsl_examples/exesql.json
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"components": {
|
||||||
|
"begin": {
|
||||||
|
"obj":{
|
||||||
|
"component_name": "Begin",
|
||||||
|
"params": {
|
||||||
|
"prologue": "Hi there!"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": []
|
||||||
|
},
|
||||||
|
"answer:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Answer",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["exesql:0"],
|
||||||
|
"upstream": ["begin", "exesql:0"]
|
||||||
|
},
|
||||||
|
"exesql:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "ExeSQL",
|
||||||
|
"params": {
|
||||||
|
"database": "rag_flow",
|
||||||
|
"username": "root",
|
||||||
|
"host": "mysql",
|
||||||
|
"port": 3306,
|
||||||
|
"password": "infini_rag_flow",
|
||||||
|
"top_n": 3
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["answer:0"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"history": [],
|
||||||
|
"messages": [],
|
||||||
|
"reference": {},
|
||||||
|
"path": [],
|
||||||
|
"answer": []
|
||||||
|
}
|
||||||
|
|
||||||
62
agent/test/dsl_examples/keyword_wikipedia_and_generate.json
Normal file
62
agent/test/dsl_examples/keyword_wikipedia_and_generate.json
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"components": {
|
||||||
|
"begin": {
|
||||||
|
"obj":{
|
||||||
|
"component_name": "Begin",
|
||||||
|
"params": {
|
||||||
|
"prologue": "Hi there!"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": []
|
||||||
|
},
|
||||||
|
"answer:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Answer",
|
||||||
|
"params": {}
|
||||||
|
},
|
||||||
|
"downstream": ["keyword:0"],
|
||||||
|
"upstream": ["begin"]
|
||||||
|
},
|
||||||
|
"keyword:0": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "KeywordExtract",
|
||||||
|
"params": {
|
||||||
|
"llm_id": "deepseek-chat",
|
||||||
|
"prompt": "- Role: You're a question analyzer.\n - Requirements:\n - Summarize user's question, and give top %s important keyword/phrase.\n - Use comma as a delimiter to separate keywords/phrases.\n - Answer format: (in language of user's question)\n - keyword: ",
|
||||||
|
"temperature": 0.2,
|
||||||
|
"top_n": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["wikipedia:0"],
|
||||||
|
"upstream": ["answer:0"]
|
||||||
|
},
|
||||||
|
"wikipedia:0": {
|
||||||
|
"obj":{
|
||||||
|
"component_name": "Wikipedia",
|
||||||
|
"params": {
|
||||||
|
"top_n": 10
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["generate:0"],
|
||||||
|
"upstream": ["keyword:0"]
|
||||||
|
},
|
||||||
|
"generate:1": {
|
||||||
|
"obj": {
|
||||||
|
"component_name": "Generate",
|
||||||
|
"params": {
|
||||||
|
"llm_id": "deepseek-chat",
|
||||||
|
"prompt": "You are an intelligent assistant. Please answer the question based on content from Wikipedia. When the answer from Wikipedia is incomplete, you need to output the URL link of the corresponding content as well. When all the content searched from Wikipedia is irrelevant to the question, your answer must include the sentence, \"The answer you are looking for is not found in the Wikipedia!\". Answers need to consider chat history.\n The content of Wikipedia is as follows:\n {input}\n The above is the content of Wikipedia.",
|
||||||
|
"temperature": 0.2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"downstream": ["answer:0"],
|
||||||
|
"upstream": ["wikipedia:0"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"history": [],
|
||||||
|
"path": [],
|
||||||
|
"messages": [],
|
||||||
|
"reference": {},
|
||||||
|
"answer": []
|
||||||
|
}
|
||||||
@ -25,7 +25,7 @@ from flask_cors import CORS
|
|||||||
from api.db import StatusEnum
|
from api.db import StatusEnum
|
||||||
from api.db.db_models import close_connection
|
from api.db.db_models import close_connection
|
||||||
from api.db.services import UserService
|
from api.db.services import UserService
|
||||||
from api.utils import CustomJSONEncoder
|
from api.utils import CustomJSONEncoder, commands
|
||||||
|
|
||||||
from flask_session import Session
|
from flask_session import Session
|
||||||
from flask_login import LoginManager
|
from flask_login import LoginManager
|
||||||
@ -60,11 +60,12 @@ Session(app)
|
|||||||
login_manager = LoginManager()
|
login_manager = LoginManager()
|
||||||
login_manager.init_app(app)
|
login_manager.init_app(app)
|
||||||
|
|
||||||
|
commands.register_commands(app)
|
||||||
|
|
||||||
|
|
||||||
def search_pages_path(pages_dir):
|
def search_pages_path(pages_dir):
|
||||||
app_path_list = [path for path in pages_dir.glob('*_app.py') if not path.name.startswith('.')]
|
app_path_list = [path for path in pages_dir.glob('*_app.py') if not path.name.startswith('.')]
|
||||||
api_path_list = [path for path in pages_dir.glob('*_api.py') if not path.name.startswith('.')]
|
api_path_list = [path for path in pages_dir.glob('*sdk/*.py') if not path.name.startswith('.')]
|
||||||
app_path_list.extend(api_path_list)
|
app_path_list.extend(api_path_list)
|
||||||
return app_path_list
|
return app_path_list
|
||||||
|
|
||||||
@ -72,7 +73,7 @@ def search_pages_path(pages_dir):
|
|||||||
def register_page(page_path):
|
def register_page(page_path):
|
||||||
path = f'{page_path}'
|
path = f'{page_path}'
|
||||||
|
|
||||||
page_name = page_path.stem.rstrip('_api') if "_api" in path else page_path.stem.rstrip('_app')
|
page_name = page_path.stem.rstrip('_app')
|
||||||
module_name = '.'.join(page_path.parts[page_path.parts.index('api'):-1] + (page_name,))
|
module_name = '.'.join(page_path.parts[page_path.parts.index('api'):-1] + (page_name,))
|
||||||
|
|
||||||
spec = spec_from_file_location(module_name, page_path)
|
spec = spec_from_file_location(module_name, page_path)
|
||||||
@ -82,7 +83,7 @@ def register_page(page_path):
|
|||||||
sys.modules[module_name] = page
|
sys.modules[module_name] = page
|
||||||
spec.loader.exec_module(page)
|
spec.loader.exec_module(page)
|
||||||
page_name = getattr(page, 'page_name', page_name)
|
page_name = getattr(page, 'page_name', page_name)
|
||||||
url_prefix = f'/api/{API_VERSION}/{page_name}' if "_api" in path else f'/{API_VERSION}/{page_name}'
|
url_prefix = f'/api/{API_VERSION}/{page_name}' if "/sdk/" in path else f'/{API_VERSION}/{page_name}'
|
||||||
|
|
||||||
app.register_blueprint(page.manager, url_prefix=url_prefix)
|
app.register_blueprint(page.manager, url_prefix=url_prefix)
|
||||||
return url_prefix
|
return url_prefix
|
||||||
@ -90,7 +91,8 @@ def register_page(page_path):
|
|||||||
|
|
||||||
pages_dir = [
|
pages_dir = [
|
||||||
Path(__file__).parent,
|
Path(__file__).parent,
|
||||||
Path(__file__).parent.parent / 'api' / 'apps', # FIXME: ragflow/api/api/apps, can be remove?
|
Path(__file__).parent.parent / 'api' / 'apps',
|
||||||
|
Path(__file__).parent.parent / 'api' / 'apps' / 'sdk',
|
||||||
]
|
]
|
||||||
|
|
||||||
client_urls_prefix = [
|
client_urls_prefix = [
|
||||||
|
|||||||
@ -18,14 +18,15 @@ import os
|
|||||||
import re
|
import re
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from flask import request, Response
|
from flask import request, Response
|
||||||
|
from api.db.services.llm_service import TenantLLMService
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
|
|
||||||
from api.db import FileType, ParserType, FileSource
|
from api.db import FileType, LLMType, ParserType, FileSource
|
||||||
from api.db.db_models import APIToken, API4Conversation, Task, File
|
from api.db.db_models import APIToken, API4Conversation, Task, File
|
||||||
from api.db.services import duplicate_name
|
from api.db.services import duplicate_name
|
||||||
from api.db.services.api_service import APITokenService, API4ConversationService
|
from api.db.services.api_service import APITokenService, API4ConversationService
|
||||||
from api.db.services.dialog_service import DialogService, chat
|
from api.db.services.dialog_service import DialogService, chat
|
||||||
from api.db.services.document_service import DocumentService
|
from api.db.services.document_service import DocumentService, doc_upload_and_parse
|
||||||
from api.db.services.file2document_service import File2DocumentService
|
from api.db.services.file2document_service import File2DocumentService
|
||||||
from api.db.services.file_service import FileService
|
from api.db.services.file_service import FileService
|
||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
@ -37,7 +38,12 @@ from api.utils.api_utils import server_error_response, get_data_error_result, ge
|
|||||||
from itsdangerous import URLSafeTimedSerializer
|
from itsdangerous import URLSafeTimedSerializer
|
||||||
|
|
||||||
from api.utils.file_utils import filename_type, thumbnail
|
from api.utils.file_utils import filename_type, thumbnail
|
||||||
from rag.utils.minio_conn import MINIO
|
from rag.nlp import keyword_extraction
|
||||||
|
from rag.utils.storage_factory import STORAGE_IMPL
|
||||||
|
|
||||||
|
from api.db.services.canvas_service import CanvasTemplateService, UserCanvasService
|
||||||
|
from agent.canvas import Canvas
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
|
||||||
def generate_confirmation_token(tenent_id):
|
def generate_confirmation_token(tenent_id):
|
||||||
@ -46,7 +52,6 @@ def generate_confirmation_token(tenent_id):
|
|||||||
|
|
||||||
|
|
||||||
@manager.route('/new_token', methods=['POST'])
|
@manager.route('/new_token', methods=['POST'])
|
||||||
@validate_request("dialog_id")
|
|
||||||
@login_required
|
@login_required
|
||||||
def new_token():
|
def new_token():
|
||||||
req = request.json
|
req = request.json
|
||||||
@ -57,12 +62,17 @@ def new_token():
|
|||||||
|
|
||||||
tenant_id = tenants[0].tenant_id
|
tenant_id = tenants[0].tenant_id
|
||||||
obj = {"tenant_id": tenant_id, "token": generate_confirmation_token(tenant_id),
|
obj = {"tenant_id": tenant_id, "token": generate_confirmation_token(tenant_id),
|
||||||
"dialog_id": req["dialog_id"],
|
|
||||||
"create_time": current_timestamp(),
|
"create_time": current_timestamp(),
|
||||||
"create_date": datetime_format(datetime.now()),
|
"create_date": datetime_format(datetime.now()),
|
||||||
"update_time": None,
|
"update_time": None,
|
||||||
"update_date": None
|
"update_date": None
|
||||||
}
|
}
|
||||||
|
if req.get("canvas_id"):
|
||||||
|
obj["dialog_id"] = req["canvas_id"]
|
||||||
|
obj["source"] = "agent"
|
||||||
|
else:
|
||||||
|
obj["dialog_id"] = req["dialog_id"]
|
||||||
|
|
||||||
if not APITokenService.save(**obj):
|
if not APITokenService.save(**obj):
|
||||||
return get_data_error_result(retmsg="Fail to new a dialog!")
|
return get_data_error_result(retmsg="Fail to new a dialog!")
|
||||||
|
|
||||||
@ -79,7 +89,8 @@ def token_list():
|
|||||||
if not tenants:
|
if not tenants:
|
||||||
return get_data_error_result(retmsg="Tenant not found!")
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
objs = APITokenService.query(tenant_id=tenants[0].tenant_id, dialog_id=request.args["dialog_id"])
|
id = request.args["dialog_id"] if "dialog_id" in request.args else request.args["canvas_id"]
|
||||||
|
objs = APITokenService.query(tenant_id=tenants[0].tenant_id, dialog_id=id)
|
||||||
return get_json_result(data=[o.to_dict() for o in objs])
|
return get_json_result(data=[o.to_dict() for o in objs])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
@ -112,15 +123,16 @@ def stats():
|
|||||||
"from_date",
|
"from_date",
|
||||||
(datetime.now() -
|
(datetime.now() -
|
||||||
timedelta(
|
timedelta(
|
||||||
days=7)).strftime("%Y-%m-%d 24:00:00")),
|
days=7)).strftime("%Y-%m-%d 00:00:00")),
|
||||||
request.args.get(
|
request.args.get(
|
||||||
"to_date",
|
"to_date",
|
||||||
datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
|
datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
|
||||||
|
"agent" if "canvas_id" in request.args else None)
|
||||||
res = {
|
res = {
|
||||||
"pv": [(o["dt"], o["pv"]) for o in objs],
|
"pv": [(o["dt"], o["pv"]) for o in objs],
|
||||||
"uv": [(o["dt"], o["uv"]) for o in objs],
|
"uv": [(o["dt"], o["uv"]) for o in objs],
|
||||||
"speed": [(o["dt"], float(o["tokens"])/(float(o["duration"]+0.1))) for o in objs],
|
"speed": [(o["dt"], float(o["tokens"]) / (float(o["duration"] + 0.1))) for o in objs],
|
||||||
"tokens": [(o["dt"], float(o["tokens"])/1000.) for o in objs],
|
"tokens": [(o["dt"], float(o["tokens"]) / 1000.) for o in objs],
|
||||||
"round": [(o["dt"], o["round"]) for o in objs],
|
"round": [(o["dt"], o["round"]) for o in objs],
|
||||||
"thumb_up": [(o["dt"], o["thumb_up"]) for o in objs]
|
"thumb_up": [(o["dt"], o["thumb_up"]) for o in objs]
|
||||||
}
|
}
|
||||||
@ -138,21 +150,34 @@ def set_conversation():
|
|||||||
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
req = request.json
|
req = request.json
|
||||||
try:
|
try:
|
||||||
e, dia = DialogService.get_by_id(objs[0].dialog_id)
|
if objs[0].source == "agent":
|
||||||
if not e:
|
e, cvs = UserCanvasService.get_by_id(objs[0].dialog_id)
|
||||||
return get_data_error_result(retmsg="Dialog not found")
|
if not e:
|
||||||
conv = {
|
return server_error_response("canvas not found.")
|
||||||
"id": get_uuid(),
|
if not isinstance(cvs.dsl, str):
|
||||||
"dialog_id": dia.id,
|
cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
|
||||||
"user_id": request.args.get("user_id", ""),
|
canvas = Canvas(cvs.dsl, objs[0].tenant_id)
|
||||||
"message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
|
conv = {
|
||||||
}
|
"id": get_uuid(),
|
||||||
API4ConversationService.save(**conv)
|
"dialog_id": cvs.id,
|
||||||
e, conv = API4ConversationService.get_by_id(conv["id"])
|
"user_id": request.args.get("user_id", ""),
|
||||||
if not e:
|
"message": [{"role": "assistant", "content": canvas.get_prologue()}],
|
||||||
return get_data_error_result(retmsg="Fail to new a conversation!")
|
"source": "agent"
|
||||||
conv = conv.to_dict()
|
}
|
||||||
return get_json_result(data=conv)
|
API4ConversationService.save(**conv)
|
||||||
|
return get_json_result(data=conv)
|
||||||
|
else:
|
||||||
|
e, dia = DialogService.get_by_id(objs[0].dialog_id)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Dialog not found")
|
||||||
|
conv = {
|
||||||
|
"id": get_uuid(),
|
||||||
|
"dialog_id": dia.id,
|
||||||
|
"user_id": request.args.get("user_id", ""),
|
||||||
|
"message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
|
||||||
|
}
|
||||||
|
API4ConversationService.save(**conv)
|
||||||
|
return get_json_result(data=conv)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
@ -161,7 +186,8 @@ def set_conversation():
|
|||||||
@validate_request("conversation_id", "messages")
|
@validate_request("conversation_id", "messages")
|
||||||
def completion():
|
def completion():
|
||||||
token = request.headers.get('Authorization').split()[1]
|
token = request.headers.get('Authorization').split()[1]
|
||||||
if not APIToken.query(token=token):
|
objs = APIToken.query(token=token)
|
||||||
|
if not objs:
|
||||||
return get_json_result(
|
return get_json_result(
|
||||||
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
req = request.json
|
req = request.json
|
||||||
@ -176,9 +202,101 @@ def completion():
|
|||||||
continue
|
continue
|
||||||
if m["role"] == "assistant" and not msg:
|
if m["role"] == "assistant" and not msg:
|
||||||
continue
|
continue
|
||||||
msg.append({"role": m["role"], "content": m["content"]})
|
msg.append(m)
|
||||||
|
if not msg[-1].get("id"): msg[-1]["id"] = get_uuid()
|
||||||
|
message_id = msg[-1]["id"]
|
||||||
|
|
||||||
|
def fillin_conv(ans):
|
||||||
|
nonlocal conv, message_id
|
||||||
|
if not conv.reference:
|
||||||
|
conv.reference.append(ans["reference"])
|
||||||
|
else:
|
||||||
|
conv.reference[-1] = ans["reference"]
|
||||||
|
conv.message[-1] = {"role": "assistant", "content": ans["answer"], "id": message_id}
|
||||||
|
ans["id"] = message_id
|
||||||
|
|
||||||
|
def rename_field(ans):
|
||||||
|
reference = ans['reference']
|
||||||
|
if not isinstance(reference, dict):
|
||||||
|
return
|
||||||
|
for chunk_i in reference.get('chunks', []):
|
||||||
|
if 'docnm_kwd' in chunk_i:
|
||||||
|
chunk_i['doc_name'] = chunk_i['docnm_kwd']
|
||||||
|
chunk_i.pop('docnm_kwd')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if conv.source == "agent":
|
||||||
|
stream = req.get("stream", True)
|
||||||
|
conv.message.append(msg[-1])
|
||||||
|
e, cvs = UserCanvasService.get_by_id(conv.dialog_id)
|
||||||
|
if not e:
|
||||||
|
return server_error_response("canvas not found.")
|
||||||
|
del req["conversation_id"]
|
||||||
|
del req["messages"]
|
||||||
|
|
||||||
|
if not isinstance(cvs.dsl, str):
|
||||||
|
cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
|
||||||
|
|
||||||
|
if not conv.reference:
|
||||||
|
conv.reference = []
|
||||||
|
conv.message.append({"role": "assistant", "content": "", "id": message_id})
|
||||||
|
conv.reference.append({"chunks": [], "doc_aggs": []})
|
||||||
|
|
||||||
|
final_ans = {"reference": [], "content": ""}
|
||||||
|
canvas = Canvas(cvs.dsl, objs[0].tenant_id)
|
||||||
|
|
||||||
|
canvas.messages.append(msg[-1])
|
||||||
|
canvas.add_user_input(msg[-1]["content"])
|
||||||
|
answer = canvas.run(stream=stream)
|
||||||
|
|
||||||
|
assert answer is not None, "Nothing. Is it over?"
|
||||||
|
|
||||||
|
if stream:
|
||||||
|
assert isinstance(answer, partial), "Nothing. Is it over?"
|
||||||
|
|
||||||
|
def sse():
|
||||||
|
nonlocal answer, cvs, conv
|
||||||
|
try:
|
||||||
|
for ans in answer():
|
||||||
|
for k in ans.keys():
|
||||||
|
final_ans[k] = ans[k]
|
||||||
|
ans = {"answer": ans["content"], "reference": ans.get("reference", [])}
|
||||||
|
fillin_conv(ans)
|
||||||
|
rename_field(ans)
|
||||||
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans},
|
||||||
|
ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
|
canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
|
||||||
|
if final_ans.get("reference"):
|
||||||
|
canvas.reference.append(final_ans["reference"])
|
||||||
|
cvs.dsl = json.loads(str(canvas))
|
||||||
|
API4ConversationService.append_message(conv.id, conv.to_dict())
|
||||||
|
except Exception as e:
|
||||||
|
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
||||||
|
"data": {"answer": "**ERROR**: " + str(e), "reference": []}},
|
||||||
|
ensure_ascii=False) + "\n\n"
|
||||||
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
|
resp = Response(sse(), mimetype="text/event-stream")
|
||||||
|
resp.headers.add_header("Cache-control", "no-cache")
|
||||||
|
resp.headers.add_header("Connection", "keep-alive")
|
||||||
|
resp.headers.add_header("X-Accel-Buffering", "no")
|
||||||
|
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
||||||
|
return resp
|
||||||
|
|
||||||
|
final_ans["content"] = "\n".join(answer["content"]) if "content" in answer else ""
|
||||||
|
canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
|
||||||
|
if final_ans.get("reference"):
|
||||||
|
canvas.reference.append(final_ans["reference"])
|
||||||
|
cvs.dsl = json.loads(str(canvas))
|
||||||
|
|
||||||
|
result = {"answer": final_ans["content"], "reference": final_ans.get("reference", [])}
|
||||||
|
fillin_conv(result)
|
||||||
|
API4ConversationService.append_message(conv.id, conv.to_dict())
|
||||||
|
rename_field(result)
|
||||||
|
return get_json_result(data=result)
|
||||||
|
|
||||||
|
#******************For dialog******************
|
||||||
conv.message.append(msg[-1])
|
conv.message.append(msg[-1])
|
||||||
e, dia = DialogService.get_by_id(conv.dialog_id)
|
e, dia = DialogService.get_by_id(conv.dialog_id)
|
||||||
if not e:
|
if not e:
|
||||||
@ -188,34 +306,23 @@ def completion():
|
|||||||
|
|
||||||
if not conv.reference:
|
if not conv.reference:
|
||||||
conv.reference = []
|
conv.reference = []
|
||||||
conv.message.append({"role": "assistant", "content": ""})
|
conv.message.append({"role": "assistant", "content": "", "id": message_id})
|
||||||
conv.reference.append({"chunks": [], "doc_aggs": []})
|
conv.reference.append({"chunks": [], "doc_aggs": []})
|
||||||
|
|
||||||
def fillin_conv(ans):
|
|
||||||
nonlocal conv
|
|
||||||
if not conv.reference:
|
|
||||||
conv.reference.append(ans["reference"])
|
|
||||||
else: conv.reference[-1] = ans["reference"]
|
|
||||||
conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
|
|
||||||
|
|
||||||
def rename_field(ans):
|
|
||||||
for chunk_i in ans['reference'].get('chunks', []):
|
|
||||||
chunk_i['doc_name'] = chunk_i['docnm_kwd']
|
|
||||||
chunk_i.pop('docnm_kwd')
|
|
||||||
|
|
||||||
def stream():
|
def stream():
|
||||||
nonlocal dia, msg, req, conv
|
nonlocal dia, msg, req, conv
|
||||||
try:
|
try:
|
||||||
for ans in chat(dia, msg, True, **req):
|
for ans in chat(dia, msg, True, **req):
|
||||||
fillin_conv(ans)
|
fillin_conv(ans)
|
||||||
rename_field(ans)
|
rename_field(ans)
|
||||||
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans},
|
||||||
|
ensure_ascii=False) + "\n\n"
|
||||||
API4ConversationService.append_message(conv.id, conv.to_dict())
|
API4ConversationService.append_message(conv.id, conv.to_dict())
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
||||||
"data": {"answer": "**ERROR**: "+str(e), "reference": []}},
|
"data": {"answer": "**ERROR**: " + str(e), "reference": []}},
|
||||||
ensure_ascii=False) + "\n\n"
|
ensure_ascii=False) + "\n\n"
|
||||||
yield "data:"+json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
if req.get("stream", True):
|
if req.get("stream", True):
|
||||||
resp = Response(stream(), mimetype="text/event-stream")
|
resp = Response(stream(), mimetype="text/event-stream")
|
||||||
@ -224,19 +331,15 @@ def completion():
|
|||||||
resp.headers.add_header("X-Accel-Buffering", "no")
|
resp.headers.add_header("X-Accel-Buffering", "no")
|
||||||
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
||||||
return resp
|
return resp
|
||||||
else:
|
|
||||||
answer = None
|
|
||||||
for ans in chat(dia, msg, **req):
|
|
||||||
answer = ans
|
|
||||||
fillin_conv(ans)
|
|
||||||
API4ConversationService.append_message(conv.id, conv.to_dict())
|
|
||||||
break
|
|
||||||
|
|
||||||
for chunk_i in answer['reference'].get('chunks',[]):
|
answer = None
|
||||||
chunk_i['doc_name'] = chunk_i['docnm_kwd']
|
for ans in chat(dia, msg, **req):
|
||||||
chunk_i.pop('docnm_kwd')
|
answer = ans
|
||||||
|
fillin_conv(ans)
|
||||||
return get_json_result(data=answer)
|
API4ConversationService.append_message(conv.id, conv.to_dict())
|
||||||
|
break
|
||||||
|
rename_field(answer)
|
||||||
|
return get_json_result(data=answer)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
@ -245,13 +348,25 @@ def completion():
|
|||||||
@manager.route('/conversation/<conversation_id>', methods=['GET'])
|
@manager.route('/conversation/<conversation_id>', methods=['GET'])
|
||||||
# @login_required
|
# @login_required
|
||||||
def get(conversation_id):
|
def get(conversation_id):
|
||||||
|
token = request.headers.get('Authorization').split()[1]
|
||||||
|
objs = APIToken.query(token=token)
|
||||||
|
if not objs:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
e, conv = API4ConversationService.get_by_id(conversation_id)
|
e, conv = API4ConversationService.get_by_id(conversation_id)
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Conversation not found!")
|
return get_data_error_result(retmsg="Conversation not found!")
|
||||||
|
|
||||||
conv = conv.to_dict()
|
conv = conv.to_dict()
|
||||||
|
if token != APIToken.query(dialog_id=conv['dialog_id'])[0].token:
|
||||||
|
return get_json_result(data=False, retmsg='Token is not valid for this conversation_id!"',
|
||||||
|
retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
for referenct_i in conv['reference']:
|
for referenct_i in conv['reference']:
|
||||||
|
if referenct_i is None or len(referenct_i) == 0:
|
||||||
|
continue
|
||||||
for chunk_i in referenct_i['chunks']:
|
for chunk_i in referenct_i['chunks']:
|
||||||
if 'docnm_kwd' in chunk_i.keys():
|
if 'docnm_kwd' in chunk_i.keys():
|
||||||
chunk_i['doc_name'] = chunk_i['docnm_kwd']
|
chunk_i['doc_name'] = chunk_i['docnm_kwd']
|
||||||
@ -312,10 +427,10 @@ def upload():
|
|||||||
retmsg="This type of file has not been supported yet!")
|
retmsg="This type of file has not been supported yet!")
|
||||||
|
|
||||||
location = filename
|
location = filename
|
||||||
while MINIO.obj_exist(kb_id, location):
|
while STORAGE_IMPL.obj_exist(kb_id, location):
|
||||||
location += "_"
|
location += "_"
|
||||||
blob = request.files['file'].read()
|
blob = request.files['file'].read()
|
||||||
MINIO.put(kb_id, location, blob)
|
STORAGE_IMPL.put(kb_id, location, blob)
|
||||||
doc = {
|
doc = {
|
||||||
"id": get_uuid(),
|
"id": get_uuid(),
|
||||||
"kb_id": kb.id,
|
"kb_id": kb.id,
|
||||||
@ -329,14 +444,18 @@ def upload():
|
|||||||
"thumbnail": thumbnail(filename, blob)
|
"thumbnail": thumbnail(filename, blob)
|
||||||
}
|
}
|
||||||
|
|
||||||
form_data=request.form
|
form_data = request.form
|
||||||
if "parser_id" in form_data.keys():
|
if "parser_id" in form_data.keys():
|
||||||
if request.form.get("parser_id").strip() in list(vars(ParserType).values())[1:-3]:
|
if request.form.get("parser_id").strip() in list(vars(ParserType).values())[1:-3]:
|
||||||
doc["parser_id"] = request.form.get("parser_id").strip()
|
doc["parser_id"] = request.form.get("parser_id").strip()
|
||||||
if doc["type"] == FileType.VISUAL:
|
if doc["type"] == FileType.VISUAL:
|
||||||
doc["parser_id"] = ParserType.PICTURE.value
|
doc["parser_id"] = ParserType.PICTURE.value
|
||||||
|
if doc["type"] == FileType.AURAL:
|
||||||
|
doc["parser_id"] = ParserType.AUDIO.value
|
||||||
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
||||||
doc["parser_id"] = ParserType.PRESENTATION.value
|
doc["parser_id"] = ParserType.PRESENTATION.value
|
||||||
|
if re.search(r"\.(eml)$", filename):
|
||||||
|
doc["parser_id"] = ParserType.EMAIL.value
|
||||||
|
|
||||||
doc_result = DocumentService.insert(doc)
|
doc_result = DocumentService.insert(doc)
|
||||||
FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id)
|
FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id)
|
||||||
@ -356,19 +475,42 @@ def upload():
|
|||||||
if not tenant_id:
|
if not tenant_id:
|
||||||
return get_data_error_result(retmsg="Tenant not found!")
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
#e, doc = DocumentService.get_by_id(doc["id"])
|
# e, doc = DocumentService.get_by_id(doc["id"])
|
||||||
TaskService.filter_delete([Task.doc_id == doc["id"]])
|
TaskService.filter_delete([Task.doc_id == doc["id"]])
|
||||||
e, doc = DocumentService.get_by_id(doc["id"])
|
e, doc = DocumentService.get_by_id(doc["id"])
|
||||||
doc = doc.to_dict()
|
doc = doc.to_dict()
|
||||||
doc["tenant_id"] = tenant_id
|
doc["tenant_id"] = tenant_id
|
||||||
bucket, name = File2DocumentService.get_minio_address(doc_id=doc["id"])
|
bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
|
||||||
queue_tasks(doc, bucket, name)
|
queue_tasks(doc, bucket, name)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
return get_json_result(data=doc_result.to_json())
|
return get_json_result(data=doc_result.to_json())
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/document/upload_and_parse', methods=['POST'])
|
||||||
|
@validate_request("conversation_id")
|
||||||
|
def upload_parse():
|
||||||
|
token = request.headers.get('Authorization').split()[1]
|
||||||
|
objs = APIToken.query(token=token)
|
||||||
|
if not objs:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
|
if 'file' not in request.files:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='No file part!', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
file_objs = request.files.getlist('file')
|
||||||
|
for file_obj in file_objs:
|
||||||
|
if file_obj.filename == '':
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='No file selected!', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
doc_ids = doc_upload_and_parse(request.form.get("conversation_id"), file_objs, objs[0].tenant_id)
|
||||||
|
return get_json_result(data=doc_ids)
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/list_chunks', methods=['POST'])
|
@manager.route('/list_chunks', methods=['POST'])
|
||||||
# @login_required
|
# @login_required
|
||||||
def list_chunks():
|
def list_chunks():
|
||||||
@ -447,6 +589,19 @@ def list_kb_docs():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
@manager.route('/document/infos', methods=['POST'])
|
||||||
|
@validate_request("doc_ids")
|
||||||
|
def docinfos():
|
||||||
|
token = request.headers.get('Authorization').split()[1]
|
||||||
|
objs = APIToken.query(token=token)
|
||||||
|
if not objs:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
req = request.json
|
||||||
|
doc_ids = req["doc_ids"]
|
||||||
|
docs = DocumentService.get_by_ids(doc_ids)
|
||||||
|
return get_json_result(data=list(docs.dicts()))
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/document', methods=['DELETE'])
|
@manager.route('/document', methods=['DELETE'])
|
||||||
# @login_required
|
# @login_required
|
||||||
@ -459,7 +614,6 @@ def document_rm():
|
|||||||
|
|
||||||
tenant_id = objs[0].tenant_id
|
tenant_id = objs[0].tenant_id
|
||||||
req = request.json
|
req = request.json
|
||||||
doc_ids = []
|
|
||||||
try:
|
try:
|
||||||
doc_ids = [DocumentService.get_doc_id_by_doc_name(doc_name) for doc_name in req.get("doc_names", [])]
|
doc_ids = [DocumentService.get_doc_id_by_doc_name(doc_name) for doc_name in req.get("doc_names", [])]
|
||||||
for doc_id in req.get("doc_ids", []):
|
for doc_id in req.get("doc_ids", []):
|
||||||
@ -488,7 +642,7 @@ def document_rm():
|
|||||||
if not tenant_id:
|
if not tenant_id:
|
||||||
return get_data_error_result(retmsg="Tenant not found!")
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
b, n = File2DocumentService.get_minio_address(doc_id=doc_id)
|
b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
|
||||||
|
|
||||||
if not DocumentService.remove_document(doc, tenant_id):
|
if not DocumentService.remove_document(doc, tenant_id):
|
||||||
return get_data_error_result(
|
return get_data_error_result(
|
||||||
@ -498,7 +652,7 @@ def document_rm():
|
|||||||
FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
|
FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
|
||||||
File2DocumentService.delete_by_document_id(doc_id)
|
File2DocumentService.delete_by_document_id(doc_id)
|
||||||
|
|
||||||
MINIO.rm(b, n)
|
STORAGE_IMPL.rm(b, n)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
errors += str(e)
|
errors += str(e)
|
||||||
|
|
||||||
@ -527,8 +681,79 @@ def completion_faq():
|
|||||||
|
|
||||||
msg = []
|
msg = []
|
||||||
msg.append({"role": "user", "content": req["word"]})
|
msg.append({"role": "user", "content": req["word"]})
|
||||||
|
if not msg[-1].get("id"): msg[-1]["id"] = get_uuid()
|
||||||
|
message_id = msg[-1]["id"]
|
||||||
|
|
||||||
|
def fillin_conv(ans):
|
||||||
|
nonlocal conv, message_id
|
||||||
|
if not conv.reference:
|
||||||
|
conv.reference.append(ans["reference"])
|
||||||
|
else:
|
||||||
|
conv.reference[-1] = ans["reference"]
|
||||||
|
conv.message[-1] = {"role": "assistant", "content": ans["answer"], "id": message_id}
|
||||||
|
ans["id"] = message_id
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if conv.source == "agent":
|
||||||
|
conv.message.append(msg[-1])
|
||||||
|
e, cvs = UserCanvasService.get_by_id(conv.dialog_id)
|
||||||
|
if not e:
|
||||||
|
return server_error_response("canvas not found.")
|
||||||
|
|
||||||
|
if not isinstance(cvs.dsl, str):
|
||||||
|
cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
|
||||||
|
|
||||||
|
if not conv.reference:
|
||||||
|
conv.reference = []
|
||||||
|
conv.message.append({"role": "assistant", "content": "", "id": message_id})
|
||||||
|
conv.reference.append({"chunks": [], "doc_aggs": []})
|
||||||
|
|
||||||
|
final_ans = {"reference": [], "doc_aggs": []}
|
||||||
|
canvas = Canvas(cvs.dsl, objs[0].tenant_id)
|
||||||
|
|
||||||
|
canvas.messages.append(msg[-1])
|
||||||
|
canvas.add_user_input(msg[-1]["content"])
|
||||||
|
answer = canvas.run(stream=False)
|
||||||
|
|
||||||
|
assert answer is not None, "Nothing. Is it over?"
|
||||||
|
|
||||||
|
data_type_picture = {
|
||||||
|
"type": 3,
|
||||||
|
"url": "base64 content"
|
||||||
|
}
|
||||||
|
data = [
|
||||||
|
{
|
||||||
|
"type": 1,
|
||||||
|
"content": ""
|
||||||
|
}
|
||||||
|
]
|
||||||
|
final_ans["content"] = "\n".join(answer["content"]) if "content" in answer else ""
|
||||||
|
canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
|
||||||
|
if final_ans.get("reference"):
|
||||||
|
canvas.reference.append(final_ans["reference"])
|
||||||
|
cvs.dsl = json.loads(str(canvas))
|
||||||
|
|
||||||
|
ans = {"answer": final_ans["content"], "reference": final_ans.get("reference", [])}
|
||||||
|
data[0]["content"] += re.sub(r'##\d\$\$', '', ans["answer"])
|
||||||
|
fillin_conv(ans)
|
||||||
|
API4ConversationService.append_message(conv.id, conv.to_dict())
|
||||||
|
|
||||||
|
chunk_idxs = [int(match[2]) for match in re.findall(r'##\d\$\$', ans["answer"])]
|
||||||
|
for chunk_idx in chunk_idxs[:1]:
|
||||||
|
if ans["reference"]["chunks"][chunk_idx]["img_id"]:
|
||||||
|
try:
|
||||||
|
bkt, nm = ans["reference"]["chunks"][chunk_idx]["img_id"].split("-")
|
||||||
|
response = STORAGE_IMPL.get(bkt, nm)
|
||||||
|
data_type_picture["url"] = base64.b64encode(response).decode('utf-8')
|
||||||
|
data.append(data_type_picture)
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
response = {"code": 200, "msg": "success", "data": data}
|
||||||
|
return response
|
||||||
|
|
||||||
|
# ******************For dialog******************
|
||||||
conv.message.append(msg[-1])
|
conv.message.append(msg[-1])
|
||||||
e, dia = DialogService.get_by_id(conv.dialog_id)
|
e, dia = DialogService.get_by_id(conv.dialog_id)
|
||||||
if not e:
|
if not e:
|
||||||
@ -537,16 +762,9 @@ def completion_faq():
|
|||||||
|
|
||||||
if not conv.reference:
|
if not conv.reference:
|
||||||
conv.reference = []
|
conv.reference = []
|
||||||
conv.message.append({"role": "assistant", "content": ""})
|
conv.message.append({"role": "assistant", "content": "", "id": message_id})
|
||||||
conv.reference.append({"chunks": [], "doc_aggs": []})
|
conv.reference.append({"chunks": [], "doc_aggs": []})
|
||||||
|
|
||||||
def fillin_conv(ans):
|
|
||||||
nonlocal conv
|
|
||||||
if not conv.reference:
|
|
||||||
conv.reference.append(ans["reference"])
|
|
||||||
else: conv.reference[-1] = ans["reference"]
|
|
||||||
conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
|
|
||||||
|
|
||||||
data_type_picture = {
|
data_type_picture = {
|
||||||
"type": 3,
|
"type": 3,
|
||||||
"url": "base64 content"
|
"url": "base64 content"
|
||||||
@ -570,9 +788,10 @@ def completion_faq():
|
|||||||
if ans["reference"]["chunks"][chunk_idx]["img_id"]:
|
if ans["reference"]["chunks"][chunk_idx]["img_id"]:
|
||||||
try:
|
try:
|
||||||
bkt, nm = ans["reference"]["chunks"][chunk_idx]["img_id"].split("-")
|
bkt, nm = ans["reference"]["chunks"][chunk_idx]["img_id"].split("-")
|
||||||
response = MINIO.get(bkt, nm)
|
response = STORAGE_IMPL.get(bkt, nm)
|
||||||
data_type_picture["url"] = base64.b64encode(response).decode('utf-8')
|
data_type_picture["url"] = base64.b64encode(response).decode('utf-8')
|
||||||
data.append(data_type_picture)
|
data.append(data_type_picture)
|
||||||
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
@ -581,3 +800,52 @@ def completion_faq():
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/retrieval', methods=['POST'])
|
||||||
|
@validate_request("kb_id", "question")
|
||||||
|
def retrieval():
|
||||||
|
token = request.headers.get('Authorization').split()[1]
|
||||||
|
objs = APIToken.query(token=token)
|
||||||
|
if not objs:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Token is not valid!"', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
|
req = request.json
|
||||||
|
kb_ids = req.get("kb_id",[])
|
||||||
|
doc_ids = req.get("doc_ids", [])
|
||||||
|
question = req.get("question")
|
||||||
|
page = int(req.get("page", 1))
|
||||||
|
size = int(req.get("size", 30))
|
||||||
|
similarity_threshold = float(req.get("similarity_threshold", 0.2))
|
||||||
|
vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
|
||||||
|
top = int(req.get("top_k", 1024))
|
||||||
|
|
||||||
|
try:
|
||||||
|
kbs = KnowledgebaseService.get_by_ids(kb_ids)
|
||||||
|
embd_nms = list(set([kb.embd_id for kb in kbs]))
|
||||||
|
if len(embd_nms) != 1:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Knowledge bases use different embedding models or does not exist."', retcode=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
|
embd_mdl = TenantLLMService.model_instance(
|
||||||
|
kbs[0].tenant_id, LLMType.EMBEDDING.value, llm_name=kbs[0].embd_id)
|
||||||
|
rerank_mdl = None
|
||||||
|
if req.get("rerank_id"):
|
||||||
|
rerank_mdl = TenantLLMService.model_instance(
|
||||||
|
kbs[0].tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
|
||||||
|
if req.get("keyword", False):
|
||||||
|
chat_mdl = TenantLLMService.model_instance(kbs[0].tenant_id, LLMType.CHAT)
|
||||||
|
question += keyword_extraction(chat_mdl, question)
|
||||||
|
ranks = retrievaler.retrieval(question, embd_mdl, kbs[0].tenant_id, kb_ids, page, size,
|
||||||
|
similarity_threshold, vector_similarity_weight, top,
|
||||||
|
doc_ids, rerank_mdl=rerank_mdl)
|
||||||
|
for c in ranks["chunks"]:
|
||||||
|
if "vector" in c:
|
||||||
|
del c["vector"]
|
||||||
|
return get_json_result(data=ranks)
|
||||||
|
except Exception as e:
|
||||||
|
if str(e).find("not_found") > 0:
|
||||||
|
return get_json_result(data=False, retmsg=f'No chunk found! Check the chunk status please!',
|
||||||
|
retcode=RetCode.DATA_ERROR)
|
||||||
|
return server_error_response(e)
|
||||||
|
|||||||
@ -15,15 +15,16 @@
|
|||||||
#
|
#
|
||||||
import json
|
import json
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
|
||||||
from flask import request, Response
|
from flask import request, Response
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
|
|
||||||
from api.db.db_models import UserCanvas
|
|
||||||
from api.db.services.canvas_service import CanvasTemplateService, UserCanvasService
|
from api.db.services.canvas_service import CanvasTemplateService, UserCanvasService
|
||||||
|
from api.db.services.dialog_service import full_question
|
||||||
|
from api.db.services.user_service import TenantService
|
||||||
|
from api.settings import RetCode
|
||||||
from api.utils import get_uuid
|
from api.utils import get_uuid
|
||||||
from api.utils.api_utils import get_json_result, server_error_response, validate_request
|
from api.utils.api_utils import get_json_result, server_error_response, validate_request, get_data_error_result
|
||||||
from graph.canvas import Canvas
|
from agent.canvas import Canvas
|
||||||
|
from peewee import MySQLDatabase, PostgresqlDatabase
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/templates', methods=['GET'])
|
@manager.route('/templates', methods=['GET'])
|
||||||
@ -45,6 +46,10 @@ def canvas_list():
|
|||||||
@login_required
|
@login_required
|
||||||
def rm():
|
def rm():
|
||||||
for i in request.json["canvas_ids"]:
|
for i in request.json["canvas_ids"]:
|
||||||
|
if not UserCanvasService.query(user_id=current_user.id,id=i):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of canvas authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
UserCanvasService.delete_by_id(i)
|
UserCanvasService.delete_by_id(i)
|
||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
|
|
||||||
@ -63,10 +68,13 @@ def save():
|
|||||||
return server_error_response(ValueError("Duplicated title."))
|
return server_error_response(ValueError("Duplicated title."))
|
||||||
req["id"] = get_uuid()
|
req["id"] = get_uuid()
|
||||||
if not UserCanvasService.save(**req):
|
if not UserCanvasService.save(**req):
|
||||||
return server_error_response("Fail to save canvas.")
|
return get_data_error_result(retmsg="Fail to save canvas.")
|
||||||
else:
|
else:
|
||||||
|
if not UserCanvasService.query(user_id=current_user.id, id=req["id"]):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of canvas authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
UserCanvasService.update_by_id(req["id"], req)
|
UserCanvasService.update_by_id(req["id"], req)
|
||||||
|
|
||||||
return get_json_result(data=req)
|
return get_json_result(data=req)
|
||||||
|
|
||||||
|
|
||||||
@ -75,7 +83,7 @@ def save():
|
|||||||
def get(canvas_id):
|
def get(canvas_id):
|
||||||
e, c = UserCanvasService.get_by_id(canvas_id)
|
e, c = UserCanvasService.get_by_id(canvas_id)
|
||||||
if not e:
|
if not e:
|
||||||
return server_error_response("canvas not found.")
|
return get_data_error_result(retmsg="canvas not found.")
|
||||||
return get_json_result(data=c.to_dict())
|
return get_json_result(data=c.to_dict())
|
||||||
|
|
||||||
|
|
||||||
@ -87,26 +95,34 @@ def run():
|
|||||||
stream = req.get("stream", True)
|
stream = req.get("stream", True)
|
||||||
e, cvs = UserCanvasService.get_by_id(req["id"])
|
e, cvs = UserCanvasService.get_by_id(req["id"])
|
||||||
if not e:
|
if not e:
|
||||||
return server_error_response("canvas not found.")
|
return get_data_error_result(retmsg="canvas not found.")
|
||||||
|
if not UserCanvasService.query(user_id=current_user.id, id=req["id"]):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of canvas authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
if not isinstance(cvs.dsl, str):
|
if not isinstance(cvs.dsl, str):
|
||||||
cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
|
cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
|
||||||
|
|
||||||
final_ans = {"reference": [], "content": ""}
|
final_ans = {"reference": [], "content": ""}
|
||||||
|
message_id = req.get("message_id", get_uuid())
|
||||||
try:
|
try:
|
||||||
canvas = Canvas(cvs.dsl, current_user.id)
|
canvas = Canvas(cvs.dsl, current_user.id)
|
||||||
if "message" in req:
|
if "message" in req:
|
||||||
canvas.messages.append({"role": "user", "content": req["message"]})
|
canvas.messages.append({"role": "user", "content": req["message"], "id": message_id})
|
||||||
|
if len([m for m in canvas.messages if m["role"] == "user"]) > 1:
|
||||||
|
ten = TenantService.get_by_user_id(current_user.id)[0]
|
||||||
|
req["message"] = full_question(ten["tenant_id"], ten["llm_id"], canvas.messages)
|
||||||
canvas.add_user_input(req["message"])
|
canvas.add_user_input(req["message"])
|
||||||
answer = canvas.run(stream=stream)
|
answer = canvas.run(stream=stream)
|
||||||
print(canvas)
|
print(canvas)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
assert answer, "Nothing. Is it over?"
|
assert answer is not None, "Nothing. Is it over?"
|
||||||
|
|
||||||
if stream:
|
if stream:
|
||||||
assert isinstance(answer, partial)
|
assert isinstance(answer, partial), "Nothing. Is it over?"
|
||||||
|
|
||||||
def sse():
|
def sse():
|
||||||
nonlocal answer, cvs
|
nonlocal answer, cvs
|
||||||
@ -117,7 +133,7 @@ def run():
|
|||||||
ans = {"answer": ans["content"], "reference": ans.get("reference", [])}
|
ans = {"answer": ans["content"], "reference": ans.get("reference", [])}
|
||||||
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
canvas.messages.append({"role": "assistant", "content": final_ans["content"]})
|
canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
|
||||||
if final_ans.get("reference"):
|
if final_ans.get("reference"):
|
||||||
canvas.reference.append(final_ans["reference"])
|
canvas.reference.append(final_ans["reference"])
|
||||||
cvs.dsl = json.loads(str(canvas))
|
cvs.dsl = json.loads(str(canvas))
|
||||||
@ -135,12 +151,13 @@ def run():
|
|||||||
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
canvas.messages.append({"role": "assistant", "content": final_ans["content"]})
|
final_ans["content"] = "\n".join(answer["content"]) if "content" in answer else ""
|
||||||
|
canvas.messages.append({"role": "assistant", "content": final_ans["content"], "id": message_id})
|
||||||
if final_ans.get("reference"):
|
if final_ans.get("reference"):
|
||||||
canvas.reference.append(final_ans["reference"])
|
canvas.reference.append(final_ans["reference"])
|
||||||
cvs.dsl = json.loads(str(canvas))
|
cvs.dsl = json.loads(str(canvas))
|
||||||
UserCanvasService.update_by_id(req["id"], cvs.to_dict())
|
UserCanvasService.update_by_id(req["id"], cvs.to_dict())
|
||||||
return get_json_result(data=req["dsl"])
|
return get_json_result(data={"answer": final_ans["content"], "reference": final_ans.get("reference", [])})
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/reset', methods=['POST'])
|
@manager.route('/reset', methods=['POST'])
|
||||||
@ -151,7 +168,11 @@ def reset():
|
|||||||
try:
|
try:
|
||||||
e, user_canvas = UserCanvasService.get_by_id(req["id"])
|
e, user_canvas = UserCanvasService.get_by_id(req["id"])
|
||||||
if not e:
|
if not e:
|
||||||
return server_error_response("canvas not found.")
|
return get_data_error_result(retmsg="canvas not found.")
|
||||||
|
if not UserCanvasService.query(user_id=current_user.id, id=req["id"]):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of canvas authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
canvas = Canvas(json.dumps(user_canvas.dsl), current_user.id)
|
canvas = Canvas(json.dumps(user_canvas.dsl), current_user.id)
|
||||||
canvas.reset()
|
canvas.reset()
|
||||||
@ -160,3 +181,22 @@ def reset():
|
|||||||
return get_json_result(data=req["dsl"])
|
return get_json_result(data=req["dsl"])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/test_db_connect', methods=['POST'])
|
||||||
|
@validate_request("db_type", "database", "username", "host", "port", "password")
|
||||||
|
@login_required
|
||||||
|
def test_db_connect():
|
||||||
|
req = request.json
|
||||||
|
try:
|
||||||
|
if req["db_type"] in ["mysql", "mariadb"]:
|
||||||
|
db = MySQLDatabase(req["database"], user=req["username"], host=req["host"], port=req["port"],
|
||||||
|
password=req["password"])
|
||||||
|
elif req["db_type"] == 'postgresql':
|
||||||
|
db = PostgresqlDatabase(req["database"], user=req["username"], host=req["host"], port=req["port"],
|
||||||
|
password=req["password"])
|
||||||
|
db.connect()
|
||||||
|
db.close()
|
||||||
|
return get_json_result(data="Database Connection Successful!")
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|||||||
@ -14,6 +14,8 @@
|
|||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
import datetime
|
import datetime
|
||||||
|
import json
|
||||||
|
import traceback
|
||||||
|
|
||||||
from flask import request
|
from flask import request
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
@ -25,11 +27,11 @@ from rag.utils.es_conn import ELASTICSEARCH
|
|||||||
from rag.utils import rmSpace
|
from rag.utils import rmSpace
|
||||||
from api.db import LLMType, ParserType
|
from api.db import LLMType, ParserType
|
||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
from api.db.services.llm_service import TenantLLMService
|
from api.db.services.llm_service import LLMBundle
|
||||||
from api.db.services.user_service import UserTenantService
|
from api.db.services.user_service import UserTenantService
|
||||||
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
from api.db.services.document_service import DocumentService
|
from api.db.services.document_service import DocumentService
|
||||||
from api.settings import RetCode, retrievaler
|
from api.settings import RetCode, retrievaler, kg_retrievaler
|
||||||
from api.utils.api_utils import get_json_result
|
from api.utils.api_utils import get_json_result
|
||||||
import hashlib
|
import hashlib
|
||||||
import re
|
import re
|
||||||
@ -56,12 +58,13 @@ def list_chunk():
|
|||||||
}
|
}
|
||||||
if "available_int" in req:
|
if "available_int" in req:
|
||||||
query["available_int"] = int(req["available_int"])
|
query["available_int"] = int(req["available_int"])
|
||||||
sres = retrievaler.search(query, search.index_name(tenant_id))
|
sres = retrievaler.search(query, search.index_name(tenant_id), highlight=True)
|
||||||
res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
|
res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
|
||||||
for id in sres.ids:
|
for id in sres.ids:
|
||||||
d = {
|
d = {
|
||||||
"chunk_id": id,
|
"chunk_id": id,
|
||||||
"content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[id].get(
|
"content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[
|
||||||
|
id].get(
|
||||||
"content_with_weight", ""),
|
"content_with_weight", ""),
|
||||||
"doc_id": sres.field[id]["doc_id"],
|
"doc_id": sres.field[id]["doc_id"],
|
||||||
"docnm_kwd": sres.field[id]["docnm_kwd"],
|
"docnm_kwd": sres.field[id]["docnm_kwd"],
|
||||||
@ -138,8 +141,7 @@ def set():
|
|||||||
return get_data_error_result(retmsg="Tenant not found!")
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
embd_id = DocumentService.get_embd_id(req["doc_id"])
|
embd_id = DocumentService.get_embd_id(req["doc_id"])
|
||||||
embd_mdl = TenantLLMService.model_instance(
|
embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embd_id)
|
||||||
tenant_id, LLMType.EMBEDDING.value, embd_id)
|
|
||||||
|
|
||||||
e, doc = DocumentService.get_by_id(req["doc_id"])
|
e, doc = DocumentService.get_by_id(req["doc_id"])
|
||||||
if not e:
|
if not e:
|
||||||
@ -185,13 +187,19 @@ def switch():
|
|||||||
|
|
||||||
@manager.route('/rm', methods=['POST'])
|
@manager.route('/rm', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
@validate_request("chunk_ids")
|
@validate_request("chunk_ids", "doc_id")
|
||||||
def rm():
|
def rm():
|
||||||
req = request.json
|
req = request.json
|
||||||
try:
|
try:
|
||||||
if not ELASTICSEARCH.deleteByQuery(
|
if not ELASTICSEARCH.deleteByQuery(
|
||||||
Q("ids", values=req["chunk_ids"]), search.index_name(current_user.id)):
|
Q("ids", values=req["chunk_ids"]), search.index_name(current_user.id)):
|
||||||
return get_data_error_result(retmsg="Index updating failure")
|
return get_data_error_result(retmsg="Index updating failure")
|
||||||
|
e, doc = DocumentService.get_by_id(req["doc_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
deleted_chunk_ids = req["chunk_ids"]
|
||||||
|
chunk_number = len(deleted_chunk_ids)
|
||||||
|
DocumentService.decrement_chunk_num(doc.id, doc.kb_id, 1, chunk_number, 0)
|
||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
@ -226,11 +234,9 @@ def create():
|
|||||||
return get_data_error_result(retmsg="Tenant not found!")
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
embd_id = DocumentService.get_embd_id(req["doc_id"])
|
embd_id = DocumentService.get_embd_id(req["doc_id"])
|
||||||
embd_mdl = TenantLLMService.model_instance(
|
embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING.value, embd_id)
|
||||||
tenant_id, LLMType.EMBEDDING.value, embd_id)
|
|
||||||
|
|
||||||
v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
|
v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
|
||||||
DocumentService.increment_chunk_num(req["doc_id"], doc.kb_id, c, 1, 0)
|
|
||||||
v = 0.1 * v[0] + 0.9 * v[1]
|
v = 0.1 * v[0] + 0.9 * v[1]
|
||||||
d["q_%d_vec" % len(v)] = v.tolist()
|
d["q_%d_vec" % len(v)] = v.tolist()
|
||||||
ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
|
ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
|
||||||
@ -251,30 +257,42 @@ def retrieval_test():
|
|||||||
size = int(req.get("size", 30))
|
size = int(req.get("size", 30))
|
||||||
question = req["question"]
|
question = req["question"]
|
||||||
kb_id = req["kb_id"]
|
kb_id = req["kb_id"]
|
||||||
|
if isinstance(kb_id, str): kb_id = [kb_id]
|
||||||
doc_ids = req.get("doc_ids", [])
|
doc_ids = req.get("doc_ids", [])
|
||||||
similarity_threshold = float(req.get("similarity_threshold", 0.2))
|
similarity_threshold = float(req.get("similarity_threshold", 0.0))
|
||||||
vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
|
vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
|
||||||
top = int(req.get("top_k", 1024))
|
top = int(req.get("top_k", 1024))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
e, kb = KnowledgebaseService.get_by_id(kb_id)
|
tenants = UserTenantService.query(user_id=current_user.id)
|
||||||
|
for kid in kb_id:
|
||||||
|
for tenant in tenants:
|
||||||
|
if KnowledgebaseService.query(
|
||||||
|
tenant_id=tenant.tenant_id, id=kid):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of knowledgebase authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
e, kb = KnowledgebaseService.get_by_id(kb_id[0])
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Knowledgebase not found!")
|
return get_data_error_result(retmsg="Knowledgebase not found!")
|
||||||
|
|
||||||
embd_mdl = TenantLLMService.model_instance(
|
embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
|
||||||
kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
|
|
||||||
|
|
||||||
rerank_mdl = None
|
rerank_mdl = None
|
||||||
if req.get("rerank_id"):
|
if req.get("rerank_id"):
|
||||||
rerank_mdl = TenantLLMService.model_instance(
|
rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
|
||||||
kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
|
|
||||||
|
|
||||||
if req.get("keyword", False):
|
if req.get("keyword", False):
|
||||||
chat_mdl = TenantLLMService.model_instance(kb.tenant_id, LLMType.CHAT)
|
chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
|
||||||
question += keyword_extraction(chat_mdl, question)
|
question += keyword_extraction(chat_mdl, question)
|
||||||
|
|
||||||
ranks = retrievaler.retrieval(question, embd_mdl, kb.tenant_id, [kb_id], page, size,
|
retr = retrievaler if kb.parser_id != ParserType.KG else kg_retrievaler
|
||||||
similarity_threshold, vector_similarity_weight, top,
|
ranks = retr.retrieval(question, embd_mdl, kb.tenant_id, kb_id, page, size,
|
||||||
doc_ids, rerank_mdl=rerank_mdl)
|
similarity_threshold, vector_similarity_weight, top,
|
||||||
|
doc_ids, rerank_mdl=rerank_mdl, highlight=req.get("highlight"))
|
||||||
for c in ranks["chunks"]:
|
for c in ranks["chunks"]:
|
||||||
if "vector" in c:
|
if "vector" in c:
|
||||||
del c["vector"]
|
del c["vector"]
|
||||||
@ -285,3 +303,25 @@ def retrieval_test():
|
|||||||
return get_json_result(data=False, retmsg=f'No chunk found! Check the chunk status please!',
|
return get_json_result(data=False, retmsg=f'No chunk found! Check the chunk status please!',
|
||||||
retcode=RetCode.DATA_ERROR)
|
retcode=RetCode.DATA_ERROR)
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/knowledge_graph', methods=['GET'])
|
||||||
|
@login_required
|
||||||
|
def knowledge_graph():
|
||||||
|
doc_id = request.args["doc_id"]
|
||||||
|
req = {
|
||||||
|
"doc_ids":[doc_id],
|
||||||
|
"knowledge_graph_kwd": ["graph", "mind_map"]
|
||||||
|
}
|
||||||
|
tenant_id = DocumentService.get_tenant_id(doc_id)
|
||||||
|
sres = retrievaler.search(req, search.index_name(tenant_id))
|
||||||
|
obj = {"graph": {}, "mind_map": {}}
|
||||||
|
for id in sres.ids[:2]:
|
||||||
|
ty = sres.field[id]["knowledge_graph_kwd"]
|
||||||
|
try:
|
||||||
|
obj[ty] = json.loads(sres.field[id]["content_with_weight"])
|
||||||
|
except Exception as e:
|
||||||
|
print(traceback.format_exc(), flush=True)
|
||||||
|
|
||||||
|
return get_json_result(data=obj)
|
||||||
|
|
||||||
|
|||||||
@ -13,14 +13,23 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import traceback
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
from api.db.services.user_service import UserTenantService
|
||||||
from flask import request, Response
|
from flask import request, Response
|
||||||
from flask_login import login_required
|
from flask_login import login_required, current_user
|
||||||
from api.db.services.dialog_service import DialogService, ConversationService, chat
|
|
||||||
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
from api.db import LLMType
|
||||||
|
from api.db.services.dialog_service import DialogService, ConversationService, chat, ask
|
||||||
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
|
from api.db.services.llm_service import LLMBundle, TenantService, TenantLLMService
|
||||||
|
from api.settings import RetCode, retrievaler
|
||||||
from api.utils import get_uuid
|
from api.utils import get_uuid
|
||||||
from api.utils.api_utils import get_json_result
|
from api.utils.api_utils import get_json_result
|
||||||
import json
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
|
from graphrag.mind_map_extractor import MindMapExtractor
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/set', methods=['POST'])
|
@manager.route('/set', methods=['POST'])
|
||||||
@ -28,7 +37,9 @@ import json
|
|||||||
def set_conversation():
|
def set_conversation():
|
||||||
req = request.json
|
req = request.json
|
||||||
conv_id = req.get("conversation_id")
|
conv_id = req.get("conversation_id")
|
||||||
if conv_id:
|
is_new = req.get("is_new")
|
||||||
|
del req["is_new"]
|
||||||
|
if not is_new:
|
||||||
del req["conversation_id"]
|
del req["conversation_id"]
|
||||||
try:
|
try:
|
||||||
if not ConversationService.update_by_id(conv_id, req):
|
if not ConversationService.update_by_id(conv_id, req):
|
||||||
@ -47,7 +58,7 @@ def set_conversation():
|
|||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Dialog not found")
|
return get_data_error_result(retmsg="Dialog not found")
|
||||||
conv = {
|
conv = {
|
||||||
"id": get_uuid(),
|
"id": conv_id,
|
||||||
"dialog_id": req["dialog_id"],
|
"dialog_id": req["dialog_id"],
|
||||||
"name": req.get("name", "New conversation"),
|
"name": req.get("name", "New conversation"),
|
||||||
"message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
|
"message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
|
||||||
@ -70,6 +81,14 @@ def get():
|
|||||||
e, conv = ConversationService.get_by_id(conv_id)
|
e, conv = ConversationService.get_by_id(conv_id)
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Conversation not found!")
|
return get_data_error_result(retmsg="Conversation not found!")
|
||||||
|
tenants = UserTenantService.query(user_id=current_user.id)
|
||||||
|
for tenant in tenants:
|
||||||
|
if DialogService.query(tenant_id=tenant.tenant_id, id=conv.dialog_id):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of conversation authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
conv = conv.to_dict()
|
conv = conv.to_dict()
|
||||||
return get_json_result(data=conv)
|
return get_json_result(data=conv)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -82,6 +101,17 @@ def rm():
|
|||||||
conv_ids = request.json["conversation_ids"]
|
conv_ids = request.json["conversation_ids"]
|
||||||
try:
|
try:
|
||||||
for cid in conv_ids:
|
for cid in conv_ids:
|
||||||
|
exist, conv = ConversationService.get_by_id(cid)
|
||||||
|
if not exist:
|
||||||
|
return get_data_error_result(retmsg="Conversation not found!")
|
||||||
|
tenants = UserTenantService.query(user_id=current_user.id)
|
||||||
|
for tenant in tenants:
|
||||||
|
if DialogService.query(tenant_id=tenant.tenant_id, id=conv.dialog_id):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of conversation authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
ConversationService.delete_by_id(cid)
|
ConversationService.delete_by_id(cid)
|
||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -93,6 +123,10 @@ def rm():
|
|||||||
def list_convsersation():
|
def list_convsersation():
|
||||||
dialog_id = request.args["dialog_id"]
|
dialog_id = request.args["dialog_id"]
|
||||||
try:
|
try:
|
||||||
|
if not DialogService.query(tenant_id=current_user.id, id=dialog_id):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of dialog authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
convs = ConversationService.query(
|
convs = ConversationService.query(
|
||||||
dialog_id=dialog_id,
|
dialog_id=dialog_id,
|
||||||
order_by=ConversationService.model.create_time,
|
order_by=ConversationService.model.create_time,
|
||||||
@ -105,24 +139,25 @@ def list_convsersation():
|
|||||||
|
|
||||||
@manager.route('/completion', methods=['POST'])
|
@manager.route('/completion', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
#@validate_request("conversation_id", "messages")
|
@validate_request("conversation_id", "messages")
|
||||||
def completion():
|
def completion():
|
||||||
req = request.json
|
req = request.json
|
||||||
#req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
|
# req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
|
||||||
# {"role": "user", "content": "上海有吗?"}
|
# {"role": "user", "content": "上海有吗?"}
|
||||||
#]}
|
# ]}
|
||||||
msg = []
|
msg = []
|
||||||
for m in req["messages"]:
|
for m in req["messages"]:
|
||||||
if m["role"] == "system":
|
if m["role"] == "system":
|
||||||
continue
|
continue
|
||||||
if m["role"] == "assistant" and not msg:
|
if m["role"] == "assistant" and not msg:
|
||||||
continue
|
continue
|
||||||
msg.append({"role": m["role"], "content": m["content"]})
|
msg.append(m)
|
||||||
|
message_id = msg[-1].get("id")
|
||||||
try:
|
try:
|
||||||
e, conv = ConversationService.get_by_id(req["conversation_id"])
|
e, conv = ConversationService.get_by_id(req["conversation_id"])
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Conversation not found!")
|
return get_data_error_result(retmsg="Conversation not found!")
|
||||||
conv.message.append(deepcopy(msg[-1]))
|
conv.message = deepcopy(req["messages"])
|
||||||
e, dia = DialogService.get_by_id(conv.dialog_id)
|
e, dia = DialogService.get_by_id(conv.dialog_id)
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Dialog not found!")
|
return get_data_error_result(retmsg="Dialog not found!")
|
||||||
@ -131,28 +166,31 @@ def completion():
|
|||||||
|
|
||||||
if not conv.reference:
|
if not conv.reference:
|
||||||
conv.reference = []
|
conv.reference = []
|
||||||
conv.message.append({"role": "assistant", "content": ""})
|
conv.message.append({"role": "assistant", "content": "", "id": message_id})
|
||||||
conv.reference.append({"chunks": [], "doc_aggs": []})
|
conv.reference.append({"chunks": [], "doc_aggs": []})
|
||||||
|
|
||||||
def fillin_conv(ans):
|
def fillin_conv(ans):
|
||||||
nonlocal conv
|
nonlocal conv, message_id
|
||||||
if not conv.reference:
|
if not conv.reference:
|
||||||
conv.reference.append(ans["reference"])
|
conv.reference.append(ans["reference"])
|
||||||
else: conv.reference[-1] = ans["reference"]
|
else:
|
||||||
conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
|
conv.reference[-1] = ans["reference"]
|
||||||
|
conv.message[-1] = {"role": "assistant", "content": ans["answer"],
|
||||||
|
"id": message_id, "prompt": ans.get("prompt", "")}
|
||||||
|
ans["id"] = message_id
|
||||||
|
|
||||||
def stream():
|
def stream():
|
||||||
nonlocal dia, msg, req, conv
|
nonlocal dia, msg, req, conv
|
||||||
try:
|
try:
|
||||||
for ans in chat(dia, msg, True, **req):
|
for ans in chat(dia, msg, True, **req):
|
||||||
fillin_conv(ans)
|
fillin_conv(ans)
|
||||||
yield "data:"+json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
||||||
ConversationService.update_by_id(conv.id, conv.to_dict())
|
ConversationService.update_by_id(conv.id, conv.to_dict())
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
||||||
"data": {"answer": "**ERROR**: "+str(e), "reference": []}},
|
"data": {"answer": "**ERROR**: " + str(e), "reference": []}},
|
||||||
ensure_ascii=False) + "\n\n"
|
ensure_ascii=False) + "\n\n"
|
||||||
yield "data:"+json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
if req.get("stream", True):
|
if req.get("stream", True):
|
||||||
resp = Response(stream(), mimetype="text/event-stream")
|
resp = Response(stream(), mimetype="text/event-stream")
|
||||||
@ -173,3 +211,169 @@ def completion():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/tts', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
def tts():
|
||||||
|
req = request.json
|
||||||
|
text = req["text"]
|
||||||
|
|
||||||
|
tenants = TenantService.get_by_user_id(current_user.id)
|
||||||
|
if not tenants:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
|
tts_id = tenants[0]["tts_id"]
|
||||||
|
if not tts_id:
|
||||||
|
return get_data_error_result(retmsg="No default TTS model is set")
|
||||||
|
|
||||||
|
tts_mdl = LLMBundle(tenants[0]["tenant_id"], LLMType.TTS, tts_id)
|
||||||
|
|
||||||
|
def stream_audio():
|
||||||
|
try:
|
||||||
|
for txt in re.split(r"[,。/《》?;:!\n\r:;]+", text):
|
||||||
|
for chunk in tts_mdl.tts(txt):
|
||||||
|
yield chunk
|
||||||
|
except Exception as e:
|
||||||
|
yield ("data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
||||||
|
"data": {"answer": "**ERROR**: " + str(e)}},
|
||||||
|
ensure_ascii=False)).encode('utf-8')
|
||||||
|
|
||||||
|
resp = Response(stream_audio(), mimetype="audio/mpeg")
|
||||||
|
resp.headers.add_header("Cache-Control", "no-cache")
|
||||||
|
resp.headers.add_header("Connection", "keep-alive")
|
||||||
|
resp.headers.add_header("X-Accel-Buffering", "no")
|
||||||
|
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/delete_msg', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("conversation_id", "message_id")
|
||||||
|
def delete_msg():
|
||||||
|
req = request.json
|
||||||
|
e, conv = ConversationService.get_by_id(req["conversation_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Conversation not found!")
|
||||||
|
|
||||||
|
conv = conv.to_dict()
|
||||||
|
for i, msg in enumerate(conv["message"]):
|
||||||
|
if req["message_id"] != msg.get("id", ""):
|
||||||
|
continue
|
||||||
|
assert conv["message"][i + 1]["id"] == req["message_id"]
|
||||||
|
conv["message"].pop(i)
|
||||||
|
conv["message"].pop(i)
|
||||||
|
conv["reference"].pop(max(0, i // 2 - 1))
|
||||||
|
break
|
||||||
|
|
||||||
|
ConversationService.update_by_id(conv["id"], conv)
|
||||||
|
return get_json_result(data=conv)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/thumbup', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("conversation_id", "message_id")
|
||||||
|
def thumbup():
|
||||||
|
req = request.json
|
||||||
|
e, conv = ConversationService.get_by_id(req["conversation_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Conversation not found!")
|
||||||
|
up_down = req.get("set")
|
||||||
|
feedback = req.get("feedback", "")
|
||||||
|
conv = conv.to_dict()
|
||||||
|
for i, msg in enumerate(conv["message"]):
|
||||||
|
if req["message_id"] == msg.get("id", "") and msg.get("role", "") == "assistant":
|
||||||
|
if up_down:
|
||||||
|
msg["thumbup"] = True
|
||||||
|
if "feedback" in msg: del msg["feedback"]
|
||||||
|
else:
|
||||||
|
msg["thumbup"] = False
|
||||||
|
if feedback: msg["feedback"] = feedback
|
||||||
|
break
|
||||||
|
|
||||||
|
ConversationService.update_by_id(conv["id"], conv)
|
||||||
|
return get_json_result(data=conv)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/ask', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("question", "kb_ids")
|
||||||
|
def ask_about():
|
||||||
|
req = request.json
|
||||||
|
uid = current_user.id
|
||||||
|
def stream():
|
||||||
|
nonlocal req, uid
|
||||||
|
try:
|
||||||
|
for ans in ask(req["question"], req["kb_ids"], uid):
|
||||||
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
||||||
|
except Exception as e:
|
||||||
|
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
||||||
|
"data": {"answer": "**ERROR**: " + str(e), "reference": []}},
|
||||||
|
ensure_ascii=False) + "\n\n"
|
||||||
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
|
resp = Response(stream(), mimetype="text/event-stream")
|
||||||
|
resp.headers.add_header("Cache-control", "no-cache")
|
||||||
|
resp.headers.add_header("Connection", "keep-alive")
|
||||||
|
resp.headers.add_header("X-Accel-Buffering", "no")
|
||||||
|
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/mindmap', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("question", "kb_ids")
|
||||||
|
def mindmap():
|
||||||
|
req = request.json
|
||||||
|
kb_ids = req["kb_ids"]
|
||||||
|
e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Knowledgebase not found!")
|
||||||
|
|
||||||
|
embd_mdl = TenantLLMService.model_instance(
|
||||||
|
kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
|
||||||
|
chat_mdl = LLMBundle(current_user.id, LLMType.CHAT)
|
||||||
|
ranks = retrievaler.retrieval(req["question"], embd_mdl, kb.tenant_id, kb_ids, 1, 12,
|
||||||
|
0.3, 0.3, aggs=False)
|
||||||
|
mindmap = MindMapExtractor(chat_mdl)
|
||||||
|
mind_map = mindmap([c["content_with_weight"] for c in ranks["chunks"]]).output
|
||||||
|
if "error" in mind_map:
|
||||||
|
return server_error_response(Exception(mind_map["error"]))
|
||||||
|
return get_json_result(data=mind_map)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/related_questions', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("question")
|
||||||
|
def related_questions():
|
||||||
|
req = request.json
|
||||||
|
question = req["question"]
|
||||||
|
chat_mdl = LLMBundle(current_user.id, LLMType.CHAT)
|
||||||
|
prompt = """
|
||||||
|
Objective: To generate search terms related to the user's search keywords, helping users find more valuable information.
|
||||||
|
Instructions:
|
||||||
|
- Based on the keywords provided by the user, generate 5-10 related search terms.
|
||||||
|
- Each search term should be directly or indirectly related to the keyword, guiding the user to find more valuable information.
|
||||||
|
- Use common, general terms as much as possible, avoiding obscure words or technical jargon.
|
||||||
|
- Keep the term length between 2-4 words, concise and clear.
|
||||||
|
- DO NOT translate, use the language of the original keywords.
|
||||||
|
|
||||||
|
### Example:
|
||||||
|
Keywords: Chinese football
|
||||||
|
Related search terms:
|
||||||
|
1. Current status of Chinese football
|
||||||
|
2. Reform of Chinese football
|
||||||
|
3. Youth training of Chinese football
|
||||||
|
4. Chinese football in the Asian Cup
|
||||||
|
5. Chinese football in the World Cup
|
||||||
|
|
||||||
|
Reason:
|
||||||
|
- When searching, users often only use one or two keywords, making it difficult to fully express their information needs.
|
||||||
|
- Generating related search terms can help users dig deeper into relevant information and improve search efficiency.
|
||||||
|
- At the same time, related terms can also help search engines better understand user needs and return more accurate search results.
|
||||||
|
|
||||||
|
"""
|
||||||
|
ans = chat_mdl.chat(prompt, [{"role": "user", "content": f"""
|
||||||
|
Keywords: {question}
|
||||||
|
Related search terms:
|
||||||
|
"""}], {"temperature": 0.9})
|
||||||
|
return get_json_result(data=[re.sub(r"^[0-9]\. ", "", a) for a in ans.split("\n") if re.match(r"^[0-9]\. ", a)])
|
||||||
|
|||||||
@ -16,15 +16,16 @@ import os
|
|||||||
import pathlib
|
import pathlib
|
||||||
import re
|
import re
|
||||||
import warnings
|
import warnings
|
||||||
|
from functools import partial
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
|
from elasticsearch_dsl import Q
|
||||||
from flask import request, send_file
|
from flask import request, send_file
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
from httpx import HTTPError
|
from httpx import HTTPError
|
||||||
from minio import S3Error
|
|
||||||
|
|
||||||
from api.contants import NAME_LENGTH_LIMIT
|
from api.contants import NAME_LENGTH_LIMIT
|
||||||
from api.db import FileType, ParserType, FileSource
|
from api.db import FileType, ParserType, FileSource, TaskStatus
|
||||||
from api.db import StatusEnum
|
from api.db import StatusEnum
|
||||||
from api.db.db_models import File
|
from api.db.db_models import File
|
||||||
from api.db.services import duplicate_name
|
from api.db.services import duplicate_name
|
||||||
@ -38,10 +39,14 @@ from api.utils import get_uuid
|
|||||||
from api.utils.api_utils import construct_json_result, construct_error_response
|
from api.utils.api_utils import construct_json_result, construct_error_response
|
||||||
from api.utils.api_utils import construct_result, validate_request
|
from api.utils.api_utils import construct_result, validate_request
|
||||||
from api.utils.file_utils import filename_type, thumbnail
|
from api.utils.file_utils import filename_type, thumbnail
|
||||||
from rag.utils.minio_conn import MINIO
|
from rag.app import book, laws, manual, naive, one, paper, presentation, qa, resume, table, picture, audio, email
|
||||||
|
from rag.nlp import search
|
||||||
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
|
from rag.utils.storage_factory import STORAGE_IMPL
|
||||||
|
|
||||||
MAXIMUM_OF_UPLOADING_FILES = 256
|
MAXIMUM_OF_UPLOADING_FILES = 256
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------ create a dataset ---------------------------------------
|
# ------------------------------ create a dataset ---------------------------------------
|
||||||
|
|
||||||
@manager.route("/", methods=["POST"])
|
@manager.route("/", methods=["POST"])
|
||||||
@ -116,6 +121,7 @@ def create_dataset():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return construct_error_response(e)
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
# -----------------------------list datasets-------------------------------------------------------
|
# -----------------------------list datasets-------------------------------------------------------
|
||||||
|
|
||||||
@manager.route("/", methods=["GET"])
|
@manager.route("/", methods=["GET"])
|
||||||
@ -135,6 +141,7 @@ def list_datasets():
|
|||||||
except HTTPError as http_err:
|
except HTTPError as http_err:
|
||||||
return construct_json_result(http_err)
|
return construct_json_result(http_err)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------delete a dataset ----------------------------
|
# ---------------------------------delete a dataset ----------------------------
|
||||||
|
|
||||||
@manager.route("/<dataset_id>", methods=["DELETE"])
|
@manager.route("/<dataset_id>", methods=["DELETE"])
|
||||||
@ -162,13 +169,15 @@ def remove_dataset(dataset_id):
|
|||||||
|
|
||||||
# delete the dataset
|
# delete the dataset
|
||||||
if not KnowledgebaseService.delete_by_id(dataset_id):
|
if not KnowledgebaseService.delete_by_id(dataset_id):
|
||||||
return construct_json_result(code=RetCode.DATA_ERROR, message="There was an error during the dataset removal process. "
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
"Please check the status of the RAGFlow server and try the removal again.")
|
message="There was an error during the dataset removal process. "
|
||||||
|
"Please check the status of the RAGFlow server and try the removal again.")
|
||||||
# success
|
# success
|
||||||
return construct_json_result(code=RetCode.SUCCESS, message=f"Remove dataset: {dataset_id} successfully")
|
return construct_json_result(code=RetCode.SUCCESS, message=f"Remove dataset: {dataset_id} successfully")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return construct_error_response(e)
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------ get details of a dataset ----------------------------------------
|
# ------------------------------ get details of a dataset ----------------------------------------
|
||||||
|
|
||||||
@manager.route("/<dataset_id>", methods=["GET"])
|
@manager.route("/<dataset_id>", methods=["GET"])
|
||||||
@ -182,6 +191,7 @@ def get_dataset(dataset_id):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return construct_json_result(e)
|
return construct_json_result(e)
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------ update a dataset --------------------------------------------
|
# ------------------------------ update a dataset --------------------------------------------
|
||||||
|
|
||||||
@manager.route("/<dataset_id>", methods=["PUT"])
|
@manager.route("/<dataset_id>", methods=["PUT"])
|
||||||
@ -209,8 +219,9 @@ def update_dataset(dataset_id):
|
|||||||
if name.lower() != dataset.name.lower() \
|
if name.lower() != dataset.name.lower() \
|
||||||
and len(KnowledgebaseService.query(name=name, tenant_id=current_user.id,
|
and len(KnowledgebaseService.query(name=name, tenant_id=current_user.id,
|
||||||
status=StatusEnum.VALID.value)) > 1:
|
status=StatusEnum.VALID.value)) > 1:
|
||||||
return construct_json_result(code=RetCode.DATA_ERROR, message=f"The name: {name.lower()} is already used by other "
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
f"datasets. Please choose a different name.")
|
message=f"The name: {name.lower()} is already used by other "
|
||||||
|
f"datasets. Please choose a different name.")
|
||||||
|
|
||||||
dataset_updating_data = {}
|
dataset_updating_data = {}
|
||||||
chunk_num = req.get("chunk_num")
|
chunk_num = req.get("chunk_num")
|
||||||
@ -222,17 +233,22 @@ def update_dataset(dataset_id):
|
|||||||
if chunk_num == 0:
|
if chunk_num == 0:
|
||||||
dataset_updating_data["embd_id"] = req["embedding_model_id"]
|
dataset_updating_data["embd_id"] = req["embedding_model_id"]
|
||||||
else:
|
else:
|
||||||
construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document in this "
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
"dataset, so you cannot change the embedding "
|
message="You have already parsed the document in this "
|
||||||
"model.")
|
"dataset, so you cannot change the embedding "
|
||||||
|
"model.")
|
||||||
# only if chunk_num is 0, the user can update the chunk_method
|
# only if chunk_num is 0, the user can update the chunk_method
|
||||||
if req.get("chunk_method"):
|
if "chunk_method" in req:
|
||||||
if chunk_num == 0:
|
type_value = req["chunk_method"]
|
||||||
dataset_updating_data['parser_id'] = req["chunk_method"]
|
if is_illegal_value_for_enum(type_value, ParserType):
|
||||||
else:
|
return construct_json_result(message=f"Illegal value {type_value} for 'chunk_method' field.",
|
||||||
|
code=RetCode.DATA_ERROR)
|
||||||
|
if chunk_num != 0:
|
||||||
construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document "
|
construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document "
|
||||||
"in this dataset, so you cannot "
|
"in this dataset, so you cannot "
|
||||||
"change the chunk method.")
|
"change the chunk method.")
|
||||||
|
dataset_updating_data["parser_id"] = req["template_type"]
|
||||||
|
|
||||||
# convert the photo parameter to avatar
|
# convert the photo parameter to avatar
|
||||||
if req.get("photo"):
|
if req.get("photo"):
|
||||||
dataset_updating_data["avatar"] = req["photo"]
|
dataset_updating_data["avatar"] = req["photo"]
|
||||||
@ -265,6 +281,7 @@ def update_dataset(dataset_id):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return construct_error_response(e)
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------content management ----------------------------------------------
|
# --------------------------------content management ----------------------------------------------
|
||||||
|
|
||||||
# ----------------------------upload files-----------------------------------------------------
|
# ----------------------------upload files-----------------------------------------------------
|
||||||
@ -335,15 +352,16 @@ def upload_documents(dataset_id):
|
|||||||
|
|
||||||
# upload to the minio
|
# upload to the minio
|
||||||
location = filename
|
location = filename
|
||||||
while MINIO.obj_exist(dataset_id, location):
|
while STORAGE_IMPL.obj_exist(dataset_id, location):
|
||||||
location += "_"
|
location += "_"
|
||||||
|
|
||||||
blob = file.read()
|
blob = file.read()
|
||||||
|
|
||||||
# the content is empty, raising a warning
|
# the content is empty, raising a warning
|
||||||
if blob == b'':
|
if blob == b'':
|
||||||
warnings.warn(f"[WARNING]: The file {filename} is empty.")
|
warnings.warn(f"[WARNING]: The content of the file {filename} is empty.")
|
||||||
|
|
||||||
MINIO.put(dataset_id, location, blob)
|
STORAGE_IMPL.put(dataset_id, location, blob)
|
||||||
|
|
||||||
doc = {
|
doc = {
|
||||||
"id": get_uuid(),
|
"id": get_uuid(),
|
||||||
@ -359,8 +377,12 @@ def upload_documents(dataset_id):
|
|||||||
}
|
}
|
||||||
if doc["type"] == FileType.VISUAL:
|
if doc["type"] == FileType.VISUAL:
|
||||||
doc["parser_id"] = ParserType.PICTURE.value
|
doc["parser_id"] = ParserType.PICTURE.value
|
||||||
|
if doc["type"] == FileType.AURAL:
|
||||||
|
doc["parser_id"] = ParserType.AUDIO.value
|
||||||
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
||||||
doc["parser_id"] = ParserType.PRESENTATION.value
|
doc["parser_id"] = ParserType.PRESENTATION.value
|
||||||
|
if re.search(r"\.(eml)$", filename):
|
||||||
|
doc["parser_id"] = ParserType.EMAIL.value
|
||||||
DocumentService.insert(doc)
|
DocumentService.insert(doc)
|
||||||
|
|
||||||
FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
|
FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
|
||||||
@ -400,7 +422,7 @@ def delete_document(document_id, dataset_id): # string
|
|||||||
f" reason!", code=RetCode.AUTHENTICATION_ERROR)
|
f" reason!", code=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
# get the doc's id and location
|
# get the doc's id and location
|
||||||
real_dataset_id, location = File2DocumentService.get_minio_address(doc_id=document_id)
|
real_dataset_id, location = File2DocumentService.get_storage_address(doc_id=document_id)
|
||||||
|
|
||||||
if real_dataset_id != dataset_id:
|
if real_dataset_id != dataset_id:
|
||||||
return construct_json_result(message=f"The document {document_id} is not in the dataset: {dataset_id}, "
|
return construct_json_result(message=f"The document {document_id} is not in the dataset: {dataset_id}, "
|
||||||
@ -421,7 +443,7 @@ def delete_document(document_id, dataset_id): # string
|
|||||||
File2DocumentService.delete_by_document_id(document_id)
|
File2DocumentService.delete_by_document_id(document_id)
|
||||||
|
|
||||||
# delete it from minio
|
# delete it from minio
|
||||||
MINIO.rm(dataset_id, location)
|
STORAGE_IMPL.rm(dataset_id, location)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
errors += str(e)
|
errors += str(e)
|
||||||
if errors:
|
if errors:
|
||||||
@ -453,6 +475,7 @@ def list_documents(dataset_id):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return construct_error_response(e)
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
# ----------------------------update: enable rename-----------------------------------------------------
|
# ----------------------------update: enable rename-----------------------------------------------------
|
||||||
@manager.route("/<dataset_id>/documents/<document_id>", methods=["PUT"])
|
@manager.route("/<dataset_id>/documents/<document_id>", methods=["PUT"])
|
||||||
@login_required
|
@login_required
|
||||||
@ -555,6 +578,7 @@ def update_document(dataset_id, document_id):
|
|||||||
def is_illegal_value_for_enum(value, enum_class):
|
def is_illegal_value_for_enum(value, enum_class):
|
||||||
return value not in enum_class.__members__.values()
|
return value not in enum_class.__members__.values()
|
||||||
|
|
||||||
|
|
||||||
# ----------------------------download a file-----------------------------------------------------
|
# ----------------------------download a file-----------------------------------------------------
|
||||||
@manager.route("/<dataset_id>/documents/<document_id>", methods=["GET"])
|
@manager.route("/<dataset_id>/documents/<document_id>", methods=["GET"])
|
||||||
@login_required
|
@login_required
|
||||||
@ -563,7 +587,8 @@ def download_document(dataset_id, document_id):
|
|||||||
# Check whether there is this dataset
|
# Check whether there is this dataset
|
||||||
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
if not exist:
|
if not exist:
|
||||||
return construct_json_result(code=RetCode.DATA_ERROR, message=f"This dataset '{dataset_id}' cannot be found!")
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This dataset '{dataset_id}' cannot be found!")
|
||||||
|
|
||||||
# Check whether there is this document
|
# Check whether there is this document
|
||||||
exist, document = DocumentService.get_by_id(document_id)
|
exist, document = DocumentService.get_by_id(document_id)
|
||||||
@ -572,8 +597,8 @@ def download_document(dataset_id, document_id):
|
|||||||
code=RetCode.ARGUMENT_ERROR)
|
code=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
# The process of downloading
|
# The process of downloading
|
||||||
doc_id, doc_location = File2DocumentService.get_minio_address(doc_id=document_id) # minio address
|
doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
|
||||||
file_stream = MINIO.get(doc_id, doc_location)
|
file_stream = STORAGE_IMPL.get(doc_id, doc_location)
|
||||||
if not file_stream:
|
if not file_stream:
|
||||||
return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
|
return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
|
||||||
|
|
||||||
@ -591,11 +616,254 @@ def download_document(dataset_id, document_id):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return construct_error_response(e)
|
return construct_error_response(e)
|
||||||
|
|
||||||
# ----------------------------start parsing-----------------------------------------------------
|
|
||||||
|
|
||||||
# ----------------------------stop parsing-----------------------------------------------------
|
# ----------------------------start parsing a document-----------------------------------------------------
|
||||||
|
# helper method for parsing
|
||||||
|
# callback method
|
||||||
|
def doc_parse_callback(doc_id, prog=None, msg=""):
|
||||||
|
cancel = DocumentService.do_cancel(doc_id)
|
||||||
|
if cancel:
|
||||||
|
raise Exception("The parsing process has been cancelled!")
|
||||||
|
|
||||||
|
"""
|
||||||
|
def doc_parse(binary, doc_name, parser_name, tenant_id, doc_id):
|
||||||
|
match parser_name:
|
||||||
|
case "book":
|
||||||
|
book.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "laws":
|
||||||
|
laws.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "manual":
|
||||||
|
manual.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "naive":
|
||||||
|
# It's the mode by default, which is general in the front-end
|
||||||
|
naive.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "one":
|
||||||
|
one.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "paper":
|
||||||
|
paper.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "picture":
|
||||||
|
picture.chunk(doc_name, binary=binary, tenant_id=tenant_id, lang="Chinese",
|
||||||
|
callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "presentation":
|
||||||
|
presentation.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "qa":
|
||||||
|
qa.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "resume":
|
||||||
|
resume.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "table":
|
||||||
|
table.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "audio":
|
||||||
|
audio.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case "email":
|
||||||
|
email.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
|
||||||
|
case _:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route("/<dataset_id>/documents/<document_id>/status", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def parse_document(dataset_id, document_id):
|
||||||
|
try:
|
||||||
|
# valid dataset
|
||||||
|
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This dataset '{dataset_id}' cannot be found!")
|
||||||
|
|
||||||
|
return parsing_document_internal(document_id)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------start parsing documents-----------------------------------------------------
|
||||||
|
@manager.route("/<dataset_id>/documents/status", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
def parse_documents(dataset_id):
|
||||||
|
doc_ids = request.json["doc_ids"]
|
||||||
|
try:
|
||||||
|
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This dataset '{dataset_id}' cannot be found!")
|
||||||
|
# two conditions
|
||||||
|
if not doc_ids:
|
||||||
|
# documents inside the dataset
|
||||||
|
docs, total = DocumentService.list_documents_in_dataset(dataset_id, 0, -1, "create_time",
|
||||||
|
True, "")
|
||||||
|
doc_ids = [doc["id"] for doc in docs]
|
||||||
|
|
||||||
|
message = ""
|
||||||
|
# for loop
|
||||||
|
for id in doc_ids:
|
||||||
|
res = parsing_document_internal(id)
|
||||||
|
res_body = res.json
|
||||||
|
if res_body["code"] == RetCode.SUCCESS:
|
||||||
|
message += res_body["message"]
|
||||||
|
else:
|
||||||
|
return res
|
||||||
|
return construct_json_result(data=True, code=RetCode.SUCCESS, message=message)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
# helper method for parsing the document
|
||||||
|
def parsing_document_internal(id):
|
||||||
|
message = ""
|
||||||
|
try:
|
||||||
|
# Check whether there is this document
|
||||||
|
exist, document = DocumentService.get_by_id(id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(message=f"This document '{id}' cannot be found!",
|
||||||
|
code=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
tenant_id = DocumentService.get_tenant_id(id)
|
||||||
|
if not tenant_id:
|
||||||
|
return construct_json_result(message="Tenant not found!", code=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
|
info = {"run": "1", "progress": 0}
|
||||||
|
info["progress_msg"] = ""
|
||||||
|
info["chunk_num"] = 0
|
||||||
|
info["token_num"] = 0
|
||||||
|
|
||||||
|
DocumentService.update_by_id(id, info)
|
||||||
|
|
||||||
|
ELASTICSEARCH.deleteByQuery(Q("match", doc_id=id), idxnm=search.index_name(tenant_id))
|
||||||
|
|
||||||
|
_, doc_attributes = DocumentService.get_by_id(id)
|
||||||
|
doc_attributes = doc_attributes.to_dict()
|
||||||
|
doc_id = doc_attributes["id"]
|
||||||
|
|
||||||
|
bucket, doc_name = File2DocumentService.get_storage_address(doc_id=doc_id)
|
||||||
|
binary = STORAGE_IMPL.get(bucket, doc_name)
|
||||||
|
parser_name = doc_attributes["parser_id"]
|
||||||
|
if binary:
|
||||||
|
res = doc_parse(binary, doc_name, parser_name, tenant_id, doc_id)
|
||||||
|
if res is False:
|
||||||
|
message += f"The parser id: {parser_name} of the document {doc_id} is not supported; "
|
||||||
|
else:
|
||||||
|
message += f"Empty data in the document: {doc_name}; "
|
||||||
|
# failed in parsing
|
||||||
|
if doc_attributes["status"] == TaskStatus.FAIL.value:
|
||||||
|
message += f"Failed in parsing the document: {doc_id}; "
|
||||||
|
return construct_json_result(code=RetCode.SUCCESS, message=message)
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------stop parsing a doc-----------------------------------------------------
|
||||||
|
@manager.route("<dataset_id>/documents/<document_id>/status", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
def stop_parsing_document(dataset_id, document_id):
|
||||||
|
try:
|
||||||
|
# valid dataset
|
||||||
|
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This dataset '{dataset_id}' cannot be found!")
|
||||||
|
|
||||||
|
return stop_parsing_document_internal(document_id)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------stop parsing docs-----------------------------------------------------
|
||||||
|
@manager.route("<dataset_id>/documents/status", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
def stop_parsing_documents(dataset_id):
|
||||||
|
doc_ids = request.json["doc_ids"]
|
||||||
|
try:
|
||||||
|
# valid dataset?
|
||||||
|
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This dataset '{dataset_id}' cannot be found!")
|
||||||
|
if not doc_ids:
|
||||||
|
# documents inside the dataset
|
||||||
|
docs, total = DocumentService.list_documents_in_dataset(dataset_id, 0, -1, "create_time",
|
||||||
|
True, "")
|
||||||
|
doc_ids = [doc["id"] for doc in docs]
|
||||||
|
|
||||||
|
message = ""
|
||||||
|
# for loop
|
||||||
|
for id in doc_ids:
|
||||||
|
res = stop_parsing_document_internal(id)
|
||||||
|
res_body = res.json
|
||||||
|
if res_body["code"] == RetCode.SUCCESS:
|
||||||
|
message += res_body["message"]
|
||||||
|
else:
|
||||||
|
return res
|
||||||
|
return construct_json_result(data=True, code=RetCode.SUCCESS, message=message)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
# Helper method
|
||||||
|
def stop_parsing_document_internal(document_id):
|
||||||
|
try:
|
||||||
|
# valid doc?
|
||||||
|
exist, doc = DocumentService.get_by_id(document_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(message=f"This document '{document_id}' cannot be found!",
|
||||||
|
code=RetCode.ARGUMENT_ERROR)
|
||||||
|
doc_attributes = doc.to_dict()
|
||||||
|
|
||||||
|
# only when the status is parsing, we need to stop it
|
||||||
|
if doc_attributes["status"] == TaskStatus.RUNNING.value:
|
||||||
|
tenant_id = DocumentService.get_tenant_id(document_id)
|
||||||
|
if not tenant_id:
|
||||||
|
return construct_json_result(message="Tenant not found!", code=RetCode.AUTHENTICATION_ERROR)
|
||||||
|
|
||||||
|
# update successfully?
|
||||||
|
if not DocumentService.update_by_id(document_id, {"status": "2"}): # cancel
|
||||||
|
return construct_json_result(
|
||||||
|
code=RetCode.OPERATING_ERROR,
|
||||||
|
message="There was an error during the stopping parsing the document process. "
|
||||||
|
"Please check the status of the RAGFlow server and try the update again."
|
||||||
|
)
|
||||||
|
|
||||||
|
_, doc_attributes = DocumentService.get_by_id(document_id)
|
||||||
|
doc_attributes = doc_attributes.to_dict()
|
||||||
|
|
||||||
|
# failed in stop parsing
|
||||||
|
if doc_attributes["status"] == TaskStatus.RUNNING.value:
|
||||||
|
return construct_json_result(message=f"Failed in parsing the document: {document_id}; ", code=RetCode.SUCCESS)
|
||||||
|
return construct_json_result(code=RetCode.SUCCESS, message="")
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
# ----------------------------show the status of the file-----------------------------------------------------
|
# ----------------------------show the status of the file-----------------------------------------------------
|
||||||
|
@manager.route("/<dataset_id>/documents/<document_id>/status", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def show_parsing_status(dataset_id, document_id):
|
||||||
|
try:
|
||||||
|
# valid dataset
|
||||||
|
exist, _ = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This dataset: '{dataset_id}' cannot be found!")
|
||||||
|
# valid document
|
||||||
|
exist, _ = DocumentService.get_by_id(document_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This document: '{document_id}' is not a valid document.")
|
||||||
|
|
||||||
|
_, doc = DocumentService.get_by_id(document_id) # get doc object
|
||||||
|
doc_attributes = doc.to_dict()
|
||||||
|
|
||||||
|
return construct_json_result(
|
||||||
|
data={"progress": doc_attributes["progress"], "status": TaskStatus(doc_attributes["status"]).name},
|
||||||
|
code=RetCode.SUCCESS
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
# ----------------------------list the chunks of the file-----------------------------------------------------
|
# ----------------------------list the chunks of the file-----------------------------------------------------
|
||||||
|
|
||||||
@ -610,6 +878,3 @@ def download_document(dataset_id, document_id):
|
|||||||
# ----------------------------get a specific chunk-----------------------------------------------------
|
# ----------------------------get a specific chunk-----------------------------------------------------
|
||||||
|
|
||||||
# ----------------------------retrieval test-----------------------------------------------------
|
# ----------------------------retrieval test-----------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -19,7 +19,8 @@ from flask_login import login_required, current_user
|
|||||||
from api.db.services.dialog_service import DialogService
|
from api.db.services.dialog_service import DialogService
|
||||||
from api.db import StatusEnum
|
from api.db import StatusEnum
|
||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
from api.db.services.user_service import TenantService
|
from api.db.services.user_service import TenantService, UserTenantService
|
||||||
|
from api.settings import RetCode
|
||||||
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
from api.utils import get_uuid
|
from api.utils import get_uuid
|
||||||
from api.utils.api_utils import get_json_result
|
from api.utils.api_utils import get_json_result
|
||||||
@ -164,9 +165,19 @@ def list_dialogs():
|
|||||||
@validate_request("dialog_ids")
|
@validate_request("dialog_ids")
|
||||||
def rm():
|
def rm():
|
||||||
req = request.json
|
req = request.json
|
||||||
|
dialog_list=[]
|
||||||
|
tenants = UserTenantService.query(user_id=current_user.id)
|
||||||
try:
|
try:
|
||||||
DialogService.update_many_by_id(
|
for id in req["dialog_ids"]:
|
||||||
[{"id": id, "status": StatusEnum.INVALID.value} for id in req["dialog_ids"]])
|
for tenant in tenants:
|
||||||
|
if DialogService.query(tenant_id=tenant.tenant_id, id=id):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of dialog authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
dialog_list.append({"id": id,"status":StatusEnum.INVALID.value})
|
||||||
|
DialogService.update_many_by_id(dialog_list)
|
||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|||||||
@ -13,10 +13,16 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License
|
# limitations under the License
|
||||||
#
|
#
|
||||||
|
import datetime
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
import pathlib
|
import pathlib
|
||||||
import re
|
import re
|
||||||
|
import traceback
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from copy import deepcopy
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
import flask
|
import flask
|
||||||
from elasticsearch_dsl import Q
|
from elasticsearch_dsl import Q
|
||||||
@ -24,22 +30,26 @@ from flask import request
|
|||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
|
|
||||||
from api.db.db_models import Task, File
|
from api.db.db_models import Task, File
|
||||||
|
from api.db.services.dialog_service import DialogService, ConversationService
|
||||||
from api.db.services.file2document_service import File2DocumentService
|
from api.db.services.file2document_service import File2DocumentService
|
||||||
from api.db.services.file_service import FileService
|
from api.db.services.file_service import FileService
|
||||||
|
from api.db.services.llm_service import LLMBundle
|
||||||
from api.db.services.task_service import TaskService, queue_tasks
|
from api.db.services.task_service import TaskService, queue_tasks
|
||||||
|
from api.db.services.user_service import TenantService, UserTenantService
|
||||||
|
from graphrag.mind_map_extractor import MindMapExtractor
|
||||||
|
from rag.app import naive
|
||||||
from rag.nlp import search
|
from rag.nlp import search
|
||||||
from rag.utils.es_conn import ELASTICSEARCH
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
from api.db.services import duplicate_name
|
from api.db.services import duplicate_name
|
||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
from api.utils import get_uuid
|
from api.utils import get_uuid
|
||||||
from api.db import FileType, TaskStatus, ParserType, FileSource
|
from api.db import FileType, TaskStatus, ParserType, FileSource, LLMType
|
||||||
from api.db.services.document_service import DocumentService
|
from api.db.services.document_service import DocumentService, doc_upload_and_parse
|
||||||
from api.settings import RetCode
|
from api.settings import RetCode, stat_logger
|
||||||
from api.utils.api_utils import get_json_result
|
from api.utils.api_utils import get_json_result
|
||||||
from rag.utils.minio_conn import MINIO
|
from rag.utils.storage_factory import STORAGE_IMPL
|
||||||
from api.utils.file_utils import filename_type, thumbnail
|
from api.utils.file_utils import filename_type, thumbnail, get_project_base_directory
|
||||||
from api.utils.web_utils import html2pdf, is_valid_url
|
|
||||||
from api.utils.web_utils import html2pdf, is_valid_url
|
from api.utils.web_utils import html2pdf, is_valid_url
|
||||||
|
|
||||||
|
|
||||||
@ -65,53 +75,7 @@ def upload():
|
|||||||
if not e:
|
if not e:
|
||||||
raise LookupError("Can't find this knowledgebase!")
|
raise LookupError("Can't find this knowledgebase!")
|
||||||
|
|
||||||
root_folder = FileService.get_root_folder(current_user.id)
|
err, _ = FileService.upload_document(kb, file_objs, current_user.id)
|
||||||
pf_id = root_folder["id"]
|
|
||||||
FileService.init_knowledgebase_docs(pf_id, current_user.id)
|
|
||||||
kb_root_folder = FileService.get_kb_folder(current_user.id)
|
|
||||||
kb_folder = FileService.new_a_file_from_kb(kb.tenant_id, kb.name, kb_root_folder["id"])
|
|
||||||
|
|
||||||
err = []
|
|
||||||
for file in file_objs:
|
|
||||||
try:
|
|
||||||
MAX_FILE_NUM_PER_USER = int(os.environ.get('MAX_FILE_NUM_PER_USER', 0))
|
|
||||||
if MAX_FILE_NUM_PER_USER > 0 and DocumentService.get_doc_count(kb.tenant_id) >= MAX_FILE_NUM_PER_USER:
|
|
||||||
raise RuntimeError("Exceed the maximum file number of a free user!")
|
|
||||||
|
|
||||||
filename = duplicate_name(
|
|
||||||
DocumentService.query,
|
|
||||||
name=file.filename,
|
|
||||||
kb_id=kb.id)
|
|
||||||
filetype = filename_type(filename)
|
|
||||||
if filetype == FileType.OTHER.value:
|
|
||||||
raise RuntimeError("This type of file has not been supported yet!")
|
|
||||||
|
|
||||||
location = filename
|
|
||||||
while MINIO.obj_exist(kb_id, location):
|
|
||||||
location += "_"
|
|
||||||
blob = file.read()
|
|
||||||
MINIO.put(kb_id, location, blob)
|
|
||||||
doc = {
|
|
||||||
"id": get_uuid(),
|
|
||||||
"kb_id": kb.id,
|
|
||||||
"parser_id": kb.parser_id,
|
|
||||||
"parser_config": kb.parser_config,
|
|
||||||
"created_by": current_user.id,
|
|
||||||
"type": filetype,
|
|
||||||
"name": filename,
|
|
||||||
"location": location,
|
|
||||||
"size": len(blob),
|
|
||||||
"thumbnail": thumbnail(filename, blob)
|
|
||||||
}
|
|
||||||
if doc["type"] == FileType.VISUAL:
|
|
||||||
doc["parser_id"] = ParserType.PICTURE.value
|
|
||||||
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
|
||||||
doc["parser_id"] = ParserType.PRESENTATION.value
|
|
||||||
DocumentService.insert(doc)
|
|
||||||
|
|
||||||
FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id)
|
|
||||||
except Exception as e:
|
|
||||||
err.append(file.filename + ": " + str(e))
|
|
||||||
if err:
|
if err:
|
||||||
return get_json_result(
|
return get_json_result(
|
||||||
data=False, retmsg="\n".join(err), retcode=RetCode.SERVER_ERROR)
|
data=False, retmsg="\n".join(err), retcode=RetCode.SERVER_ERROR)
|
||||||
@ -147,16 +111,16 @@ def web_crawl():
|
|||||||
try:
|
try:
|
||||||
filename = duplicate_name(
|
filename = duplicate_name(
|
||||||
DocumentService.query,
|
DocumentService.query,
|
||||||
name=name+".pdf",
|
name=name + ".pdf",
|
||||||
kb_id=kb.id)
|
kb_id=kb.id)
|
||||||
filetype = filename_type(filename)
|
filetype = filename_type(filename)
|
||||||
if filetype == FileType.OTHER.value:
|
if filetype == FileType.OTHER.value:
|
||||||
raise RuntimeError("This type of file has not been supported yet!")
|
raise RuntimeError("This type of file has not been supported yet!")
|
||||||
|
|
||||||
location = filename
|
location = filename
|
||||||
while MINIO.obj_exist(kb_id, location):
|
while STORAGE_IMPL.obj_exist(kb_id, location):
|
||||||
location += "_"
|
location += "_"
|
||||||
MINIO.put(kb_id, location, blob)
|
STORAGE_IMPL.put(kb_id, location, blob)
|
||||||
doc = {
|
doc = {
|
||||||
"id": get_uuid(),
|
"id": get_uuid(),
|
||||||
"kb_id": kb.id,
|
"kb_id": kb.id,
|
||||||
@ -171,8 +135,12 @@ def web_crawl():
|
|||||||
}
|
}
|
||||||
if doc["type"] == FileType.VISUAL:
|
if doc["type"] == FileType.VISUAL:
|
||||||
doc["parser_id"] = ParserType.PICTURE.value
|
doc["parser_id"] = ParserType.PICTURE.value
|
||||||
|
if doc["type"] == FileType.AURAL:
|
||||||
|
doc["parser_id"] = ParserType.AUDIO.value
|
||||||
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
if re.search(r"\.(ppt|pptx|pages)$", filename):
|
||||||
doc["parser_id"] = ParserType.PRESENTATION.value
|
doc["parser_id"] = ParserType.PRESENTATION.value
|
||||||
|
if re.search(r"\.(eml)$", filename):
|
||||||
|
doc["parser_id"] = ParserType.EMAIL.value
|
||||||
DocumentService.insert(doc)
|
DocumentService.insert(doc)
|
||||||
FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id)
|
FileService.add_file_from_kb(doc, kb_folder["id"], kb.tenant_id)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -223,6 +191,15 @@ def list_docs():
|
|||||||
if not kb_id:
|
if not kb_id:
|
||||||
return get_json_result(
|
return get_json_result(
|
||||||
data=False, retmsg='Lack of "KB ID"', retcode=RetCode.ARGUMENT_ERROR)
|
data=False, retmsg='Lack of "KB ID"', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
tenants = UserTenantService.query(user_id=current_user.id)
|
||||||
|
for tenant in tenants:
|
||||||
|
if KnowledgebaseService.query(
|
||||||
|
tenant_id=tenant.tenant_id, id=kb_id):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of knowledgebase authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
keywords = request.args.get("keywords", "")
|
keywords = request.args.get("keywords", "")
|
||||||
|
|
||||||
page_number = int(request.args.get("page", 1))
|
page_number = int(request.args.get("page", 1))
|
||||||
@ -237,8 +214,16 @@ def list_docs():
|
|||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/infos', methods=['POST'])
|
||||||
|
def docinfos():
|
||||||
|
req = request.json
|
||||||
|
doc_ids = req["doc_ids"]
|
||||||
|
docs = DocumentService.get_by_ids(doc_ids)
|
||||||
|
return get_json_result(data=list(docs.dicts()))
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/thumbnails', methods=['GET'])
|
@manager.route('/thumbnails', methods=['GET'])
|
||||||
@login_required
|
#@login_required
|
||||||
def thumbnails():
|
def thumbnails():
|
||||||
doc_ids = request.args.get("doc_ids").split(",")
|
doc_ids = request.args.get("doc_ids").split(",")
|
||||||
if not doc_ids:
|
if not doc_ids:
|
||||||
@ -314,7 +299,7 @@ def rm():
|
|||||||
if not tenant_id:
|
if not tenant_id:
|
||||||
return get_data_error_result(retmsg="Tenant not found!")
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
b, n = File2DocumentService.get_minio_address(doc_id=doc_id)
|
b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
|
||||||
|
|
||||||
if not DocumentService.remove_document(doc, tenant_id):
|
if not DocumentService.remove_document(doc, tenant_id):
|
||||||
return get_data_error_result(
|
return get_data_error_result(
|
||||||
@ -324,7 +309,7 @@ def rm():
|
|||||||
FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
|
FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
|
||||||
File2DocumentService.delete_by_document_id(doc_id)
|
File2DocumentService.delete_by_document_id(doc_id)
|
||||||
|
|
||||||
MINIO.rm(b, n)
|
STORAGE_IMPL.rm(b, n)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
errors += str(e)
|
errors += str(e)
|
||||||
|
|
||||||
@ -359,7 +344,7 @@ def run():
|
|||||||
e, doc = DocumentService.get_by_id(id)
|
e, doc = DocumentService.get_by_id(id)
|
||||||
doc = doc.to_dict()
|
doc = doc.to_dict()
|
||||||
doc["tenant_id"] = tenant_id
|
doc["tenant_id"] = tenant_id
|
||||||
bucket, name = File2DocumentService.get_minio_address(doc_id=doc["id"])
|
bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
|
||||||
queue_tasks(doc, bucket, name)
|
queue_tasks(doc, bucket, name)
|
||||||
|
|
||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
@ -410,8 +395,8 @@ def get(doc_id):
|
|||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Document not found!")
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
|
||||||
b,n = File2DocumentService.get_minio_address(doc_id=doc_id)
|
b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
|
||||||
response = flask.make_response(MINIO.get(b, n))
|
response = flask.make_response(STORAGE_IMPL.get(b, n))
|
||||||
|
|
||||||
ext = re.search(r"\.([^.]+)$", doc.name)
|
ext = re.search(r"\.([^.]+)$", doc.name)
|
||||||
if ext:
|
if ext:
|
||||||
@ -475,8 +460,27 @@ def change_parser():
|
|||||||
def get_image(image_id):
|
def get_image(image_id):
|
||||||
try:
|
try:
|
||||||
bkt, nm = image_id.split("-")
|
bkt, nm = image_id.split("-")
|
||||||
response = flask.make_response(MINIO.get(bkt, nm))
|
response = flask.make_response(STORAGE_IMPL.get(bkt, nm))
|
||||||
response.headers.set('Content-Type', 'image/JPEG')
|
response.headers.set('Content-Type', 'image/JPEG')
|
||||||
return response
|
return response
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/upload_and_parse', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("conversation_id")
|
||||||
|
def upload_and_parse():
|
||||||
|
if 'file' not in request.files:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='No file part!', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
file_objs = request.files.getlist('file')
|
||||||
|
for file_obj in file_objs:
|
||||||
|
if file_obj.filename == '':
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='No file selected!', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
doc_ids = doc_upload_and_parse(request.form.get("conversation_id"), file_objs, current_user.id)
|
||||||
|
|
||||||
|
return get_json_result(data=doc_ids)
|
||||||
|
|||||||
@ -77,7 +77,7 @@ def convert():
|
|||||||
doc = DocumentService.insert({
|
doc = DocumentService.insert({
|
||||||
"id": get_uuid(),
|
"id": get_uuid(),
|
||||||
"kb_id": kb.id,
|
"kb_id": kb.id,
|
||||||
"parser_id": kb.parser_id,
|
"parser_id": FileService.get_parser(file.type, file.name, kb.parser_id),
|
||||||
"parser_config": kb.parser_config,
|
"parser_config": kb.parser_config,
|
||||||
"created_by": current_user.id,
|
"created_by": current_user.id,
|
||||||
"type": file.type,
|
"type": file.type,
|
||||||
|
|||||||
@ -34,7 +34,7 @@ from api.utils.api_utils import get_json_result
|
|||||||
from api.utils.file_utils import filename_type
|
from api.utils.file_utils import filename_type
|
||||||
from rag.nlp import search
|
from rag.nlp import search
|
||||||
from rag.utils.es_conn import ELASTICSEARCH
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
from rag.utils.minio_conn import MINIO
|
from rag.utils.storage_factory import STORAGE_IMPL
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/upload', methods=['POST'])
|
@manager.route('/upload', methods=['POST'])
|
||||||
@ -98,7 +98,7 @@ def upload():
|
|||||||
# file type
|
# file type
|
||||||
filetype = filename_type(file_obj_names[file_len - 1])
|
filetype = filename_type(file_obj_names[file_len - 1])
|
||||||
location = file_obj_names[file_len - 1]
|
location = file_obj_names[file_len - 1]
|
||||||
while MINIO.obj_exist(last_folder.id, location):
|
while STORAGE_IMPL.obj_exist(last_folder.id, location):
|
||||||
location += "_"
|
location += "_"
|
||||||
blob = file_obj.read()
|
blob = file_obj.read()
|
||||||
filename = duplicate_name(
|
filename = duplicate_name(
|
||||||
@ -116,7 +116,7 @@ def upload():
|
|||||||
"size": len(blob),
|
"size": len(blob),
|
||||||
}
|
}
|
||||||
file = FileService.insert(file)
|
file = FileService.insert(file)
|
||||||
MINIO.put(last_folder.id, location, blob)
|
STORAGE_IMPL.put(last_folder.id, location, blob)
|
||||||
file_res.append(file.to_json())
|
file_res.append(file.to_json())
|
||||||
return get_json_result(data=file_res)
|
return get_json_result(data=file_res)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -260,7 +260,7 @@ def rm():
|
|||||||
e, file = FileService.get_by_id(inner_file_id)
|
e, file = FileService.get_by_id(inner_file_id)
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="File not found!")
|
return get_data_error_result(retmsg="File not found!")
|
||||||
MINIO.rm(file.parent_id, file.location)
|
STORAGE_IMPL.rm(file.parent_id, file.location)
|
||||||
FileService.delete_folder_by_pf_id(current_user.id, file_id)
|
FileService.delete_folder_by_pf_id(current_user.id, file_id)
|
||||||
else:
|
else:
|
||||||
if not FileService.delete(file):
|
if not FileService.delete(file):
|
||||||
@ -296,7 +296,8 @@ def rename():
|
|||||||
e, file = FileService.get_by_id(req["file_id"])
|
e, file = FileService.get_by_id(req["file_id"])
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="File not found!")
|
return get_data_error_result(retmsg="File not found!")
|
||||||
if pathlib.Path(req["name"].lower()).suffix != pathlib.Path(
|
if file.type != FileType.FOLDER.value \
|
||||||
|
and pathlib.Path(req["name"].lower()).suffix != pathlib.Path(
|
||||||
file.name.lower()).suffix:
|
file.name.lower()).suffix:
|
||||||
return get_json_result(
|
return get_json_result(
|
||||||
data=False,
|
data=False,
|
||||||
@ -331,8 +332,8 @@ def get(file_id):
|
|||||||
e, file = FileService.get_by_id(file_id)
|
e, file = FileService.get_by_id(file_id)
|
||||||
if not e:
|
if not e:
|
||||||
return get_data_error_result(retmsg="Document not found!")
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
b, n = File2DocumentService.get_minio_address(file_id=file_id)
|
b, n = File2DocumentService.get_storage_address(file_id=file_id)
|
||||||
response = flask.make_response(MINIO.get(b, n))
|
response = flask.make_response(STORAGE_IMPL.get(b, n))
|
||||||
ext = re.search(r"\.([^.]+)$", file.name)
|
ext = re.search(r"\.([^.]+)$", file.name)
|
||||||
if ext:
|
if ext:
|
||||||
if file.type == FileType.VISUAL.value:
|
if file.type == FileType.VISUAL.value:
|
||||||
|
|||||||
@ -100,6 +100,15 @@ def update():
|
|||||||
def detail():
|
def detail():
|
||||||
kb_id = request.args["kb_id"]
|
kb_id = request.args["kb_id"]
|
||||||
try:
|
try:
|
||||||
|
tenants = UserTenantService.query(user_id=current_user.id)
|
||||||
|
for tenant in tenants:
|
||||||
|
if KnowledgebaseService.query(
|
||||||
|
tenant_id=tenant.tenant_id, id=kb_id):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of knowledgebase authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
kb = KnowledgebaseService.get_detail(kb_id)
|
kb = KnowledgebaseService.get_detail(kb_id)
|
||||||
if not kb:
|
if not kb:
|
||||||
return get_data_error_result(
|
return get_data_error_result(
|
||||||
|
|||||||
@ -13,14 +13,18 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
|
import json
|
||||||
|
|
||||||
from flask import request
|
from flask import request
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
from api.db.services.llm_service import LLMFactoriesService, TenantLLMService, LLMService
|
from api.db.services.llm_service import LLMFactoriesService, TenantLLMService, LLMService
|
||||||
|
from api.settings import LIGHTEN
|
||||||
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
from api.db import StatusEnum, LLMType
|
from api.db import StatusEnum, LLMType
|
||||||
from api.db.db_models import TenantLLM
|
from api.db.db_models import TenantLLM
|
||||||
from api.utils.api_utils import get_json_result
|
from api.utils.api_utils import get_json_result
|
||||||
from rag.llm import EmbeddingModel, ChatModel, RerankModel
|
from rag.llm import EmbeddingModel, ChatModel, RerankModel, CvModel, TTSModel
|
||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/factories', methods=['GET'])
|
@manager.route('/factories', methods=['GET'])
|
||||||
@ -28,7 +32,19 @@ from rag.llm import EmbeddingModel, ChatModel, RerankModel
|
|||||||
def factories():
|
def factories():
|
||||||
try:
|
try:
|
||||||
fac = LLMFactoriesService.get_all()
|
fac = LLMFactoriesService.get_all()
|
||||||
return get_json_result(data=[f.to_dict() for f in fac if f.name not in ["Youdao", "FastEmbed", "BAAI"]])
|
fac = [f.to_dict() for f in fac if f.name not in ["Youdao", "FastEmbed", "BAAI"]]
|
||||||
|
llms = LLMService.get_all()
|
||||||
|
mdl_types = {}
|
||||||
|
for m in llms:
|
||||||
|
if m.status != StatusEnum.VALID.value:
|
||||||
|
continue
|
||||||
|
if m.fid not in mdl_types:
|
||||||
|
mdl_types[m.fid] = set([])
|
||||||
|
mdl_types[m.fid].add(m.model_type)
|
||||||
|
for f in fac:
|
||||||
|
f["model_types"] = list(mdl_types.get(f["name"], [LLMType.CHAT, LLMType.EMBEDDING, LLMType.RERANK,
|
||||||
|
LLMType.IMAGE2TEXT, LLMType.SPEECH2TEXT, LLMType.TTS]))
|
||||||
|
return get_json_result(data=fac)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return server_error_response(e)
|
return server_error_response(e)
|
||||||
|
|
||||||
@ -42,13 +58,13 @@ def set_api_key():
|
|||||||
chat_passed, embd_passed, rerank_passed = False, False, False
|
chat_passed, embd_passed, rerank_passed = False, False, False
|
||||||
factory = req["llm_factory"]
|
factory = req["llm_factory"]
|
||||||
msg = ""
|
msg = ""
|
||||||
for llm in LLMService.query(fid=factory):
|
for llm in LLMService.query(fid=factory)[:3]:
|
||||||
if not embd_passed and llm.model_type == LLMType.EMBEDDING.value:
|
if not embd_passed and llm.model_type == LLMType.EMBEDDING.value:
|
||||||
mdl = EmbeddingModel[factory](
|
mdl = EmbeddingModel[factory](
|
||||||
req["api_key"], llm.llm_name, base_url=req.get("base_url"))
|
req["api_key"], llm.llm_name, base_url=req.get("base_url"))
|
||||||
try:
|
try:
|
||||||
arr, tc = mdl.encode(["Test if the api key is available"])
|
arr, tc = mdl.encode(["Test if the api key is available"])
|
||||||
if len(arr[0]) == 0 or tc == 0:
|
if len(arr[0]) == 0:
|
||||||
raise Exception("Fail")
|
raise Exception("Fail")
|
||||||
embd_passed = True
|
embd_passed = True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@ -57,9 +73,9 @@ def set_api_key():
|
|||||||
mdl = ChatModel[factory](
|
mdl = ChatModel[factory](
|
||||||
req["api_key"], llm.llm_name, base_url=req.get("base_url"))
|
req["api_key"], llm.llm_name, base_url=req.get("base_url"))
|
||||||
try:
|
try:
|
||||||
m, tc = mdl.chat(None, [{"role": "user", "content": "Hello! How are you doing!"}], {
|
m, tc = mdl.chat(None, [{"role": "user", "content": "Hello! How are you doing!"}],
|
||||||
"temperature": 0.9})
|
{"temperature": 0.9,'max_tokens':50})
|
||||||
if not tc:
|
if m.find("**ERROR**") >=0:
|
||||||
raise Exception(m)
|
raise Exception(m)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
msg += f"\nFail to access model({llm.llm_name}) using this api key." + str(
|
msg += f"\nFail to access model({llm.llm_name}) using this api key." + str(
|
||||||
@ -80,24 +96,27 @@ def set_api_key():
|
|||||||
if msg:
|
if msg:
|
||||||
return get_data_error_result(retmsg=msg)
|
return get_data_error_result(retmsg=msg)
|
||||||
|
|
||||||
llm = {
|
llm_config = {
|
||||||
"api_key": req["api_key"],
|
"api_key": req["api_key"],
|
||||||
"api_base": req.get("base_url", "")
|
"api_base": req.get("base_url", "")
|
||||||
}
|
}
|
||||||
for n in ["model_type", "llm_name"]:
|
for n in ["model_type", "llm_name"]:
|
||||||
if n in req:
|
if n in req:
|
||||||
llm[n] = req[n]
|
llm_config[n] = req[n]
|
||||||
|
|
||||||
if not TenantLLMService.filter_update(
|
for llm in LLMService.query(fid=factory):
|
||||||
[TenantLLM.tenant_id == current_user.id, TenantLLM.llm_factory == factory], llm):
|
if not TenantLLMService.filter_update(
|
||||||
for llm in LLMService.query(fid=factory):
|
[TenantLLM.tenant_id == current_user.id,
|
||||||
|
TenantLLM.llm_factory == factory,
|
||||||
|
TenantLLM.llm_name == llm.llm_name],
|
||||||
|
llm_config):
|
||||||
TenantLLMService.save(
|
TenantLLMService.save(
|
||||||
tenant_id=current_user.id,
|
tenant_id=current_user.id,
|
||||||
llm_factory=factory,
|
llm_factory=factory,
|
||||||
llm_name=llm.llm_name,
|
llm_name=llm.llm_name,
|
||||||
model_type=llm.model_type,
|
model_type=llm.model_type,
|
||||||
api_key=req["api_key"],
|
api_key=llm_config["api_key"],
|
||||||
api_base=req.get("base_url", "")
|
api_base=llm_config["api_base"]
|
||||||
)
|
)
|
||||||
|
|
||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
@ -105,30 +124,68 @@ def set_api_key():
|
|||||||
|
|
||||||
@manager.route('/add_llm', methods=['POST'])
|
@manager.route('/add_llm', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
@validate_request("llm_factory", "llm_name", "model_type")
|
@validate_request("llm_factory")
|
||||||
def add_llm():
|
def add_llm():
|
||||||
req = request.json
|
req = request.json
|
||||||
factory = req["llm_factory"]
|
factory = req["llm_factory"]
|
||||||
|
|
||||||
|
def apikey_json(keys):
|
||||||
|
nonlocal req
|
||||||
|
return json.dumps({k: req.get(k, "") for k in keys})
|
||||||
|
|
||||||
if factory == "VolcEngine":
|
if factory == "VolcEngine":
|
||||||
# For VolcEngine, due to its special authentication method
|
# For VolcEngine, due to its special authentication method
|
||||||
# Assemble volc_ak, volc_sk, endpoint_id into api_key
|
# Assemble ark_api_key endpoint_id into api_key
|
||||||
temp = list(eval(req["llm_name"]).items())[0]
|
llm_name = req["llm_name"]
|
||||||
llm_name = temp[0]
|
api_key = apikey_json(["ark_api_key", "endpoint_id"])
|
||||||
endpoint_id = temp[1]
|
|
||||||
api_key = '{' + f'"volc_ak": "{req.get("volc_ak", "")}", ' \
|
elif factory == "Tencent Hunyuan":
|
||||||
f'"volc_sk": "{req.get("volc_sk", "")}", ' \
|
req["api_key"] = apikey_json(["hunyuan_sid", "hunyuan_sk"])
|
||||||
f'"ep_id": "{endpoint_id}", ' + '}'
|
return set_api_key()
|
||||||
|
|
||||||
|
elif factory == "Tencent Cloud":
|
||||||
|
req["api_key"] = apikey_json(["tencent_cloud_sid", "tencent_cloud_sk"])
|
||||||
|
|
||||||
elif factory == "Bedrock":
|
elif factory == "Bedrock":
|
||||||
# For Bedrock, due to its special authentication method
|
# For Bedrock, due to its special authentication method
|
||||||
# Assemble bedrock_ak, bedrock_sk, bedrock_region
|
# Assemble bedrock_ak, bedrock_sk, bedrock_region
|
||||||
llm_name = req["llm_name"]
|
llm_name = req["llm_name"]
|
||||||
api_key = '{' + f'"bedrock_ak": "{req.get("bedrock_ak", "")}", ' \
|
api_key = apikey_json(["bedrock_ak", "bedrock_sk", "bedrock_region"])
|
||||||
f'"bedrock_sk": "{req.get("bedrock_sk", "")}", ' \
|
|
||||||
f'"bedrock_region": "{req.get("bedrock_region", "")}", ' + '}'
|
elif factory == "LocalAI":
|
||||||
|
llm_name = req["llm_name"]+"___LocalAI"
|
||||||
|
api_key = "xxxxxxxxxxxxxxx"
|
||||||
|
|
||||||
|
elif factory == "HuggingFace":
|
||||||
|
llm_name = req["llm_name"]+"___HuggingFace"
|
||||||
|
api_key = "xxxxxxxxxxxxxxx"
|
||||||
|
|
||||||
|
elif factory == "OpenAI-API-Compatible":
|
||||||
|
llm_name = req["llm_name"]+"___OpenAI-API"
|
||||||
|
api_key = req.get("api_key","xxxxxxxxxxxxxxx")
|
||||||
|
|
||||||
|
elif factory =="XunFei Spark":
|
||||||
|
llm_name = req["llm_name"]
|
||||||
|
if req["model_type"] == "chat":
|
||||||
|
api_key = req.get("spark_api_password", "xxxxxxxxxxxxxxx")
|
||||||
|
elif req["model_type"] == "tts":
|
||||||
|
api_key = apikey_json(["spark_app_id", "spark_api_secret","spark_api_key"])
|
||||||
|
|
||||||
|
elif factory == "BaiduYiyan":
|
||||||
|
llm_name = req["llm_name"]
|
||||||
|
api_key = apikey_json(["yiyan_ak", "yiyan_sk"])
|
||||||
|
|
||||||
|
elif factory == "Fish Audio":
|
||||||
|
llm_name = req["llm_name"]
|
||||||
|
api_key = apikey_json(["fish_audio_ak", "fish_audio_refid"])
|
||||||
|
|
||||||
|
elif factory == "Google Cloud":
|
||||||
|
llm_name = req["llm_name"]
|
||||||
|
api_key = apikey_json(["google_project_id", "google_region", "google_service_account_key"])
|
||||||
|
|
||||||
else:
|
else:
|
||||||
llm_name = req["llm_name"]
|
llm_name = req["llm_name"]
|
||||||
api_key = "xxxxxxxxxxxxxxx"
|
api_key = req.get("api_key", "xxxxxxxxxxxxxxx")
|
||||||
|
|
||||||
llm = {
|
llm = {
|
||||||
"tenant_id": current_user.id,
|
"tenant_id": current_user.id,
|
||||||
@ -142,7 +199,7 @@ def add_llm():
|
|||||||
msg = ""
|
msg = ""
|
||||||
if llm["model_type"] == LLMType.EMBEDDING.value:
|
if llm["model_type"] == LLMType.EMBEDDING.value:
|
||||||
mdl = EmbeddingModel[factory](
|
mdl = EmbeddingModel[factory](
|
||||||
key=llm['api_key'] if factory in ["VolcEngine", "Bedrock"] else None,
|
key=llm['api_key'],
|
||||||
model_name=llm["llm_name"],
|
model_name=llm["llm_name"],
|
||||||
base_url=llm["api_base"])
|
base_url=llm["api_base"])
|
||||||
try:
|
try:
|
||||||
@ -153,7 +210,7 @@ def add_llm():
|
|||||||
msg += f"\nFail to access embedding model({llm['llm_name']})." + str(e)
|
msg += f"\nFail to access embedding model({llm['llm_name']})." + str(e)
|
||||||
elif llm["model_type"] == LLMType.CHAT.value:
|
elif llm["model_type"] == LLMType.CHAT.value:
|
||||||
mdl = ChatModel[factory](
|
mdl = ChatModel[factory](
|
||||||
key=llm['api_key'] if factory in ["VolcEngine", "Bedrock"] else None,
|
key=llm['api_key'],
|
||||||
model_name=llm["llm_name"],
|
model_name=llm["llm_name"],
|
||||||
base_url=llm["api_base"]
|
base_url=llm["api_base"]
|
||||||
)
|
)
|
||||||
@ -165,6 +222,49 @@ def add_llm():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
msg += f"\nFail to access model({llm['llm_name']})." + str(
|
msg += f"\nFail to access model({llm['llm_name']})." + str(
|
||||||
e)
|
e)
|
||||||
|
elif llm["model_type"] == LLMType.RERANK:
|
||||||
|
mdl = RerankModel[factory](
|
||||||
|
key=llm["api_key"],
|
||||||
|
model_name=llm["llm_name"],
|
||||||
|
base_url=llm["api_base"]
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
arr, tc = mdl.similarity("Hello~ Ragflower!", ["Hi, there!"])
|
||||||
|
if len(arr) == 0 or tc == 0:
|
||||||
|
raise Exception("Not known.")
|
||||||
|
except Exception as e:
|
||||||
|
msg += f"\nFail to access model({llm['llm_name']})." + str(
|
||||||
|
e)
|
||||||
|
elif llm["model_type"] == LLMType.IMAGE2TEXT.value:
|
||||||
|
mdl = CvModel[factory](
|
||||||
|
key=llm["api_key"],
|
||||||
|
model_name=llm["llm_name"],
|
||||||
|
base_url=llm["api_base"]
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
img_url = (
|
||||||
|
"https://upload.wikimedia.org/wikipedia/comm"
|
||||||
|
"ons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/256"
|
||||||
|
"0px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
|
||||||
|
)
|
||||||
|
res = requests.get(img_url)
|
||||||
|
if res.status_code == 200:
|
||||||
|
m, tc = mdl.describe(res.content)
|
||||||
|
if not tc:
|
||||||
|
raise Exception(m)
|
||||||
|
else:
|
||||||
|
pass
|
||||||
|
except Exception as e:
|
||||||
|
msg += f"\nFail to access model({llm['llm_name']})." + str(e)
|
||||||
|
elif llm["model_type"] == LLMType.TTS:
|
||||||
|
mdl = TTSModel[factory](
|
||||||
|
key=llm["api_key"], model_name=llm["llm_name"], base_url=llm["api_base"]
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
for resp in mdl.tts("Hello~ Ragflower!"):
|
||||||
|
pass
|
||||||
|
except RuntimeError as e:
|
||||||
|
msg += f"\nFail to access model({llm['llm_name']})." + str(e)
|
||||||
else:
|
else:
|
||||||
# TODO: check other type of models
|
# TODO: check other type of models
|
||||||
pass
|
pass
|
||||||
@ -189,6 +289,16 @@ def delete_llm():
|
|||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/delete_factory', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("llm_factory")
|
||||||
|
def delete_factory():
|
||||||
|
req = request.json
|
||||||
|
TenantLLMService.filter_delete(
|
||||||
|
[TenantLLM.tenant_id == current_user.id, TenantLLM.llm_factory == req["llm_factory"]])
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/my_llms', methods=['GET'])
|
@manager.route('/my_llms', methods=['GET'])
|
||||||
@login_required
|
@login_required
|
||||||
def my_llms():
|
def my_llms():
|
||||||
@ -213,15 +323,17 @@ def my_llms():
|
|||||||
@manager.route('/list', methods=['GET'])
|
@manager.route('/list', methods=['GET'])
|
||||||
@login_required
|
@login_required
|
||||||
def list_app():
|
def list_app():
|
||||||
|
self_deploied = ["Youdao","FastEmbed", "BAAI", "Ollama", "Xinference", "LocalAI", "LM-Studio"]
|
||||||
|
weighted = ["Youdao","FastEmbed", "BAAI"] if LIGHTEN else []
|
||||||
model_type = request.args.get("model_type")
|
model_type = request.args.get("model_type")
|
||||||
try:
|
try:
|
||||||
objs = TenantLLMService.query(tenant_id=current_user.id)
|
objs = TenantLLMService.query(tenant_id=current_user.id)
|
||||||
facts = set([o.to_dict()["llm_factory"] for o in objs if o.api_key])
|
facts = set([o.to_dict()["llm_factory"] for o in objs if o.api_key])
|
||||||
llms = LLMService.get_all()
|
llms = LLMService.get_all()
|
||||||
llms = [m.to_dict()
|
llms = [m.to_dict()
|
||||||
for m in llms if m.status == StatusEnum.VALID.value]
|
for m in llms if m.status == StatusEnum.VALID.value and m.fid not in weighted]
|
||||||
for m in llms:
|
for m in llms:
|
||||||
m["available"] = m["fid"] in facts or m["llm_name"].lower() == "flag-embedding" or m["fid"] in ["Youdao","FastEmbed", "BAAI"]
|
m["available"] = m["fid"] in facts or m["llm_name"].lower() == "flag-embedding" or m["fid"] in self_deploied
|
||||||
|
|
||||||
llm_set = set([m["llm_name"] for m in llms])
|
llm_set = set([m["llm_name"] for m in llms])
|
||||||
for o in objs:
|
for o in objs:
|
||||||
|
|||||||
304
api/apps/sdk/assistant.py
Normal file
304
api/apps/sdk/assistant.py
Normal file
@ -0,0 +1,304 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
from flask import request
|
||||||
|
|
||||||
|
from api.db import StatusEnum
|
||||||
|
from api.db.db_models import TenantLLM
|
||||||
|
from api.db.services.dialog_service import DialogService
|
||||||
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
|
from api.db.services.llm_service import LLMService, TenantLLMService
|
||||||
|
from api.db.services.user_service import TenantService
|
||||||
|
from api.settings import RetCode
|
||||||
|
from api.utils import get_uuid
|
||||||
|
from api.utils.api_utils import get_data_error_result, token_required
|
||||||
|
from api.utils.api_utils import get_json_result
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/save', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def save(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
# dataset
|
||||||
|
if req.get("knowledgebases") == []:
|
||||||
|
return get_data_error_result(retmsg="knowledgebases can not be empty list")
|
||||||
|
kb_list = []
|
||||||
|
if req.get("knowledgebases"):
|
||||||
|
for kb in req.get("knowledgebases"):
|
||||||
|
if not kb["id"]:
|
||||||
|
return get_data_error_result(retmsg="knowledgebase needs id")
|
||||||
|
if not KnowledgebaseService.query(id=kb["id"], tenant_id=tenant_id):
|
||||||
|
return get_data_error_result(retmsg="you do not own the knowledgebase")
|
||||||
|
# if not DocumentService.query(kb_id=kb["id"]):
|
||||||
|
# return get_data_error_result(retmsg="There is a invalid knowledgebase")
|
||||||
|
kb_list.append(kb["id"])
|
||||||
|
req["kb_ids"] = kb_list
|
||||||
|
# llm
|
||||||
|
llm = req.get("llm")
|
||||||
|
if llm:
|
||||||
|
if "model_name" in llm:
|
||||||
|
req["llm_id"] = llm.pop("model_name")
|
||||||
|
req["llm_setting"] = req.pop("llm")
|
||||||
|
e, tenant = TenantService.get_by_id(tenant_id)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
# prompt
|
||||||
|
prompt = req.get("prompt")
|
||||||
|
key_mapping = {"parameters": "variables",
|
||||||
|
"prologue": "opener",
|
||||||
|
"quote": "show_quote",
|
||||||
|
"system": "prompt",
|
||||||
|
"rerank_id": "rerank_model",
|
||||||
|
"vector_similarity_weight": "keywords_similarity_weight"}
|
||||||
|
key_list = ["similarity_threshold", "vector_similarity_weight", "top_n", "rerank_id"]
|
||||||
|
if prompt:
|
||||||
|
for new_key, old_key in key_mapping.items():
|
||||||
|
if old_key in prompt:
|
||||||
|
prompt[new_key] = prompt.pop(old_key)
|
||||||
|
for key in key_list:
|
||||||
|
if key in prompt:
|
||||||
|
req[key] = prompt.pop(key)
|
||||||
|
req["prompt_config"] = req.pop("prompt")
|
||||||
|
# create
|
||||||
|
if "id" not in req:
|
||||||
|
# dataset
|
||||||
|
if not kb_list:
|
||||||
|
return get_data_error_result(retmsg="knowledgebases are required!")
|
||||||
|
# init
|
||||||
|
req["id"] = get_uuid()
|
||||||
|
req["description"] = req.get("description", "A helpful Assistant")
|
||||||
|
req["icon"] = req.get("avatar", "")
|
||||||
|
req["top_n"] = req.get("top_n", 6)
|
||||||
|
req["top_k"] = req.get("top_k", 1024)
|
||||||
|
req["rerank_id"] = req.get("rerank_id", "")
|
||||||
|
if req.get("llm_id"):
|
||||||
|
if not TenantLLMService.query(llm_name=req["llm_id"]):
|
||||||
|
return get_data_error_result(retmsg="the model_name does not exist.")
|
||||||
|
else:
|
||||||
|
req["llm_id"] = tenant.llm_id
|
||||||
|
if not req.get("name"):
|
||||||
|
return get_data_error_result(retmsg="name is required.")
|
||||||
|
if DialogService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_data_error_result(retmsg="Duplicated assistant name in creating dataset.")
|
||||||
|
# tenant_id
|
||||||
|
if req.get("tenant_id"):
|
||||||
|
return get_data_error_result(retmsg="tenant_id must not be provided.")
|
||||||
|
req["tenant_id"] = tenant_id
|
||||||
|
# prompt more parameter
|
||||||
|
default_prompt = {
|
||||||
|
"system": """你是一个智能助手,请总结知识库的内容来回答问题,请列举知识库中的数据详细回答。当所有知识库内容都与问题无关时,你的回答必须包括“知识库中未找到您要的答案!”这句话。回答需要考虑聊天历史。
|
||||||
|
以下是知识库:
|
||||||
|
{knowledge}
|
||||||
|
以上是知识库。""",
|
||||||
|
"prologue": "您好,我是您的助手小樱,长得可爱又善良,can I help you?",
|
||||||
|
"parameters": [
|
||||||
|
{"key": "knowledge", "optional": False}
|
||||||
|
],
|
||||||
|
"empty_response": "Sorry! 知识库中未找到相关内容!"
|
||||||
|
}
|
||||||
|
key_list_2 = ["system", "prologue", "parameters", "empty_response"]
|
||||||
|
if "prompt_config" not in req:
|
||||||
|
req['prompt_config'] = {}
|
||||||
|
for key in key_list_2:
|
||||||
|
temp = req['prompt_config'].get(key)
|
||||||
|
if not temp:
|
||||||
|
req['prompt_config'][key] = default_prompt[key]
|
||||||
|
for p in req['prompt_config']["parameters"]:
|
||||||
|
if p["optional"]:
|
||||||
|
continue
|
||||||
|
if req['prompt_config']["system"].find("{%s}" % p["key"]) < 0:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Parameter '{}' is not used".format(p["key"]))
|
||||||
|
# save
|
||||||
|
if not DialogService.save(**req):
|
||||||
|
return get_data_error_result(retmsg="Fail to new an assistant!")
|
||||||
|
# response
|
||||||
|
e, res = DialogService.get_by_id(req["id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Fail to new an assistant!")
|
||||||
|
res = res.to_json()
|
||||||
|
renamed_dict = {}
|
||||||
|
for key, value in res["prompt_config"].items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_dict[new_key] = value
|
||||||
|
res["prompt"] = renamed_dict
|
||||||
|
del res["prompt_config"]
|
||||||
|
new_dict = {"similarity_threshold": res["similarity_threshold"],
|
||||||
|
"keywords_similarity_weight": res["vector_similarity_weight"],
|
||||||
|
"top_n": res["top_n"],
|
||||||
|
"rerank_model": res['rerank_id']}
|
||||||
|
res["prompt"].update(new_dict)
|
||||||
|
for key in key_list:
|
||||||
|
del res[key]
|
||||||
|
res["llm"] = res.pop("llm_setting")
|
||||||
|
res["llm"]["model_name"] = res.pop("llm_id")
|
||||||
|
del res["kb_ids"]
|
||||||
|
res["knowledgebases"] = req["knowledgebases"]
|
||||||
|
res["avatar"] = res.pop("icon")
|
||||||
|
return get_json_result(data=res)
|
||||||
|
else:
|
||||||
|
# authorization
|
||||||
|
if not DialogService.query(tenant_id=tenant_id, id=req["id"], status=StatusEnum.VALID.value):
|
||||||
|
return get_json_result(data=False, retmsg='You do not own the assistant', retcode=RetCode.OPERATING_ERROR)
|
||||||
|
# prompt
|
||||||
|
if not req["id"]:
|
||||||
|
return get_data_error_result(retmsg="id can not be empty")
|
||||||
|
e, res = DialogService.get_by_id(req["id"])
|
||||||
|
res = res.to_json()
|
||||||
|
if "llm_id" in req:
|
||||||
|
if not TenantLLMService.query(llm_name=req["llm_id"]):
|
||||||
|
return get_data_error_result(retmsg="the model_name does not exist.")
|
||||||
|
if "name" in req:
|
||||||
|
if not req.get("name"):
|
||||||
|
return get_data_error_result(retmsg="name is not empty.")
|
||||||
|
if req["name"].lower() != res["name"].lower() \
|
||||||
|
and len(
|
||||||
|
DialogService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value)) > 0:
|
||||||
|
return get_data_error_result(retmsg="Duplicated assistant name in updating dataset.")
|
||||||
|
if "prompt_config" in req:
|
||||||
|
res["prompt_config"].update(req["prompt_config"])
|
||||||
|
for p in res["prompt_config"]["parameters"]:
|
||||||
|
if p["optional"]:
|
||||||
|
continue
|
||||||
|
if res["prompt_config"]["system"].find("{%s}" % p["key"]) < 0:
|
||||||
|
return get_data_error_result(retmsg="Parameter '{}' is not used".format(p["key"]))
|
||||||
|
if "llm_setting" in req:
|
||||||
|
res["llm_setting"].update(req["llm_setting"])
|
||||||
|
req["prompt_config"] = res["prompt_config"]
|
||||||
|
req["llm_setting"] = res["llm_setting"]
|
||||||
|
# avatar
|
||||||
|
if "avatar" in req:
|
||||||
|
req["icon"] = req.pop("avatar")
|
||||||
|
assistant_id = req.pop("id")
|
||||||
|
if "knowledgebases" in req:
|
||||||
|
req.pop("knowledgebases")
|
||||||
|
if not DialogService.update_by_id(assistant_id, req):
|
||||||
|
return get_data_error_result(retmsg="Assistant not found!")
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/delete', methods=['DELETE'])
|
||||||
|
@token_required
|
||||||
|
def delete(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
if "id" not in req:
|
||||||
|
return get_data_error_result(retmsg="id is required")
|
||||||
|
id = req['id']
|
||||||
|
if not DialogService.query(tenant_id=tenant_id, id=id, status=StatusEnum.VALID.value):
|
||||||
|
return get_json_result(data=False, retmsg='you do not own the assistant.', retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
temp_dict = {"status": StatusEnum.INVALID.value}
|
||||||
|
DialogService.update_by_id(req["id"], temp_dict)
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/get', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def get(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
if "id" in req:
|
||||||
|
id = req["id"]
|
||||||
|
ass = DialogService.query(tenant_id=tenant_id, id=id, status=StatusEnum.VALID.value)
|
||||||
|
if not ass:
|
||||||
|
return get_json_result(data=False, retmsg='You do not own the assistant.', retcode=RetCode.OPERATING_ERROR)
|
||||||
|
if "name" in req:
|
||||||
|
name = req["name"]
|
||||||
|
if ass[0].name != name:
|
||||||
|
return get_json_result(data=False, retmsg='name does not match id.', retcode=RetCode.OPERATING_ERROR)
|
||||||
|
res = ass[0].to_json()
|
||||||
|
else:
|
||||||
|
if "name" in req:
|
||||||
|
name = req["name"]
|
||||||
|
ass = DialogService.query(name=name, tenant_id=tenant_id, status=StatusEnum.VALID.value)
|
||||||
|
if not ass:
|
||||||
|
return get_json_result(data=False, retmsg='You do not own the assistant.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
res = ass[0].to_json()
|
||||||
|
else:
|
||||||
|
return get_data_error_result(retmsg="At least one of `id` or `name` must be provided.")
|
||||||
|
renamed_dict = {}
|
||||||
|
key_mapping = {"parameters": "variables",
|
||||||
|
"prologue": "opener",
|
||||||
|
"quote": "show_quote",
|
||||||
|
"system": "prompt",
|
||||||
|
"rerank_id": "rerank_model",
|
||||||
|
"vector_similarity_weight": "keywords_similarity_weight"}
|
||||||
|
key_list = ["similarity_threshold", "vector_similarity_weight", "top_n", "rerank_id"]
|
||||||
|
for key, value in res["prompt_config"].items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_dict[new_key] = value
|
||||||
|
res["prompt"] = renamed_dict
|
||||||
|
del res["prompt_config"]
|
||||||
|
new_dict = {"similarity_threshold": res["similarity_threshold"],
|
||||||
|
"keywords_similarity_weight": res["vector_similarity_weight"],
|
||||||
|
"top_n": res["top_n"],
|
||||||
|
"rerank_model": res['rerank_id']}
|
||||||
|
res["prompt"].update(new_dict)
|
||||||
|
for key in key_list:
|
||||||
|
del res[key]
|
||||||
|
res["llm"] = res.pop("llm_setting")
|
||||||
|
res["llm"]["model_name"] = res.pop("llm_id")
|
||||||
|
kb_list = []
|
||||||
|
for kb_id in res["kb_ids"]:
|
||||||
|
kb = KnowledgebaseService.query(id=kb_id)
|
||||||
|
kb_list.append(kb[0].to_json())
|
||||||
|
del res["kb_ids"]
|
||||||
|
res["knowledgebases"] = kb_list
|
||||||
|
res["avatar"] = res.pop("icon")
|
||||||
|
return get_json_result(data=res)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/list', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def list_assistants(tenant_id):
|
||||||
|
assts = DialogService.query(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
status=StatusEnum.VALID.value,
|
||||||
|
reverse=True,
|
||||||
|
order_by=DialogService.model.create_time)
|
||||||
|
assts = [d.to_dict() for d in assts]
|
||||||
|
list_assts = []
|
||||||
|
renamed_dict = {}
|
||||||
|
key_mapping = {"parameters": "variables",
|
||||||
|
"prologue": "opener",
|
||||||
|
"quote": "show_quote",
|
||||||
|
"system": "prompt",
|
||||||
|
"rerank_id": "rerank_model",
|
||||||
|
"vector_similarity_weight": "keywords_similarity_weight"}
|
||||||
|
key_list = ["similarity_threshold", "vector_similarity_weight", "top_n", "rerank_id"]
|
||||||
|
for res in assts:
|
||||||
|
for key, value in res["prompt_config"].items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_dict[new_key] = value
|
||||||
|
res["prompt"] = renamed_dict
|
||||||
|
del res["prompt_config"]
|
||||||
|
new_dict = {"similarity_threshold": res["similarity_threshold"],
|
||||||
|
"keywords_similarity_weight": res["vector_similarity_weight"],
|
||||||
|
"top_n": res["top_n"],
|
||||||
|
"rerank_model": res['rerank_id']}
|
||||||
|
res["prompt"].update(new_dict)
|
||||||
|
for key in key_list:
|
||||||
|
del res[key]
|
||||||
|
res["llm"] = res.pop("llm_setting")
|
||||||
|
res["llm"]["model_name"] = res.pop("llm_id")
|
||||||
|
kb_list = []
|
||||||
|
for kb_id in res["kb_ids"]:
|
||||||
|
kb = KnowledgebaseService.query(id=kb_id)
|
||||||
|
kb_list.append(kb[0].to_json())
|
||||||
|
del res["kb_ids"]
|
||||||
|
res["knowledgebases"] = kb_list
|
||||||
|
res["avatar"] = res.pop("icon")
|
||||||
|
list_assts.append(res)
|
||||||
|
return get_json_result(data=list_assts)
|
||||||
224
api/apps/sdk/dataset.py
Normal file
224
api/apps/sdk/dataset.py
Normal file
@ -0,0 +1,224 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
|
from flask import request
|
||||||
|
|
||||||
|
from api.db import StatusEnum, FileSource
|
||||||
|
from api.db.db_models import File
|
||||||
|
from api.db.services.document_service import DocumentService
|
||||||
|
from api.db.services.file2document_service import File2DocumentService
|
||||||
|
from api.db.services.file_service import FileService
|
||||||
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
|
from api.db.services.user_service import TenantService
|
||||||
|
from api.settings import RetCode
|
||||||
|
from api.utils import get_uuid
|
||||||
|
from api.utils.api_utils import get_json_result, token_required, get_data_error_result
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/save', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def save(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
e, t = TenantService.get_by_id(tenant_id)
|
||||||
|
if "id" not in req:
|
||||||
|
if "tenant_id" in req or "embedding_model" in req:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Tenant_id or embedding_model must not be provided")
|
||||||
|
if "name" not in req:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Name is not empty!")
|
||||||
|
req['id'] = get_uuid()
|
||||||
|
req["name"] = req["name"].strip()
|
||||||
|
if req["name"] == "":
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Name is not empty string!")
|
||||||
|
if KnowledgebaseService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Duplicated knowledgebase name in creating dataset.")
|
||||||
|
req["tenant_id"] = req['created_by'] = tenant_id
|
||||||
|
req['embedding_model'] = t.embd_id
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_num": "chunk_count",
|
||||||
|
"doc_num": "document_count",
|
||||||
|
"parser_id": "parse_method",
|
||||||
|
"embd_id": "embedding_model"
|
||||||
|
}
|
||||||
|
mapped_keys = {new_key: req[old_key] for new_key, old_key in key_mapping.items() if old_key in req}
|
||||||
|
req.update(mapped_keys)
|
||||||
|
if not KnowledgebaseService.save(**req):
|
||||||
|
return get_data_error_result(retmsg="Create dataset error.(Database error)")
|
||||||
|
renamed_data = {}
|
||||||
|
e, k = KnowledgebaseService.get_by_id(req["id"])
|
||||||
|
for key, value in k.to_dict().items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_data[new_key] = value
|
||||||
|
return get_json_result(data=renamed_data)
|
||||||
|
else:
|
||||||
|
invalid_keys = {"embd_id", "chunk_num", "doc_num", "parser_id"}
|
||||||
|
if any(key in req for key in invalid_keys):
|
||||||
|
return get_data_error_result(retmsg="The input parameters are invalid.")
|
||||||
|
|
||||||
|
if "tenant_id" in req:
|
||||||
|
if req["tenant_id"] != tenant_id:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change tenant_id.")
|
||||||
|
|
||||||
|
if "embedding_model" in req:
|
||||||
|
if req["embedding_model"] != t.embd_id:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change embedding_model.")
|
||||||
|
req.pop("embedding_model")
|
||||||
|
|
||||||
|
if not KnowledgebaseService.query(
|
||||||
|
created_by=tenant_id, id=req["id"]):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='You do not own the dataset.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
if not req["id"]:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="id can not be empty.")
|
||||||
|
e, kb = KnowledgebaseService.get_by_id(req["id"])
|
||||||
|
|
||||||
|
if "chunk_count" in req:
|
||||||
|
if req["chunk_count"] != kb.chunk_num:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change chunk_count.")
|
||||||
|
req.pop("chunk_count")
|
||||||
|
|
||||||
|
if "document_count" in req:
|
||||||
|
if req['document_count'] != kb.doc_num:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change document_count.")
|
||||||
|
req.pop("document_count")
|
||||||
|
|
||||||
|
if "parse_method" in req:
|
||||||
|
if kb.chunk_num != 0 and req['parse_method'] != kb.parser_id:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="If chunk count is not 0, parse method is not changable.")
|
||||||
|
req['parser_id'] = req.pop('parse_method')
|
||||||
|
if "name" in req:
|
||||||
|
req["name"] = req["name"].strip()
|
||||||
|
if req["name"].lower() != kb.name.lower() \
|
||||||
|
and len(KnowledgebaseService.query(name=req["name"], tenant_id=tenant_id,
|
||||||
|
status=StatusEnum.VALID.value)) > 0:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Duplicated knowledgebase name in updating dataset.")
|
||||||
|
|
||||||
|
del req["id"]
|
||||||
|
if not KnowledgebaseService.update_by_id(kb.id, req):
|
||||||
|
return get_data_error_result(retmsg="Update dataset error.(Database error)")
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/delete', methods=['DELETE'])
|
||||||
|
@token_required
|
||||||
|
def delete(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
if "id" not in req:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="id is required")
|
||||||
|
kbs = KnowledgebaseService.query(
|
||||||
|
created_by=tenant_id, id=req["id"])
|
||||||
|
if not kbs:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='You do not own the dataset',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
for doc in DocumentService.query(kb_id=req["id"]):
|
||||||
|
if not DocumentService.remove_document(doc, kbs[0].tenant_id):
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Remove document error.(Database error)")
|
||||||
|
f2d = File2DocumentService.get_by_document_id(doc.id)
|
||||||
|
FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
|
||||||
|
File2DocumentService.delete_by_document_id(doc.id)
|
||||||
|
|
||||||
|
if not KnowledgebaseService.delete_by_id(req["id"]):
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Delete dataset error.(Database serror)")
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/list', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def list_datasets(tenant_id):
|
||||||
|
page_number = int(request.args.get("page", 1))
|
||||||
|
items_per_page = int(request.args.get("page_size", 1024))
|
||||||
|
orderby = request.args.get("orderby", "create_time")
|
||||||
|
desc = bool(request.args.get("desc", True))
|
||||||
|
tenants = TenantService.get_joined_tenants_by_user_id(tenant_id)
|
||||||
|
kbs = KnowledgebaseService.get_by_tenant_ids(
|
||||||
|
[m["tenant_id"] for m in tenants], tenant_id, page_number, items_per_page, orderby, desc)
|
||||||
|
renamed_list = []
|
||||||
|
for kb in kbs:
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_num": "chunk_count",
|
||||||
|
"doc_num": "document_count",
|
||||||
|
"parser_id": "parse_method",
|
||||||
|
"embd_id": "embedding_model"
|
||||||
|
}
|
||||||
|
renamed_data = {}
|
||||||
|
for key, value in kb.items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_data[new_key] = value
|
||||||
|
renamed_list.append(renamed_data)
|
||||||
|
return get_json_result(data=renamed_list)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/detail', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def detail(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_num": "chunk_count",
|
||||||
|
"doc_num": "document_count",
|
||||||
|
"parser_id": "parse_method",
|
||||||
|
"embd_id": "embedding_model"
|
||||||
|
}
|
||||||
|
renamed_data = {}
|
||||||
|
if "id" in req:
|
||||||
|
id = req["id"]
|
||||||
|
kb = KnowledgebaseService.query(created_by=tenant_id, id=req["id"])
|
||||||
|
if not kb:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='You do not own the dataset.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
if "name" in req:
|
||||||
|
name = req["name"]
|
||||||
|
if kb[0].name != name:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='You do not own the dataset.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
e, k = KnowledgebaseService.get_by_id(id)
|
||||||
|
for key, value in k.to_dict().items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_data[new_key] = value
|
||||||
|
return get_json_result(data=renamed_data)
|
||||||
|
else:
|
||||||
|
if "name" in req:
|
||||||
|
name = req["name"]
|
||||||
|
e, k = KnowledgebaseService.get_by_name(kb_name=name, tenant_id=tenant_id)
|
||||||
|
if not e:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='You do not own the dataset.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
for key, value in k.to_dict().items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_data[new_key] = value
|
||||||
|
return get_json_result(data=renamed_data)
|
||||||
|
else:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="At least one of `id` or `name` must be provided.")
|
||||||
720
api/apps/sdk/doc.py
Normal file
720
api/apps/sdk/doc.py
Normal file
@ -0,0 +1,720 @@
|
|||||||
|
import pathlib
|
||||||
|
import re
|
||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from flask import request
|
||||||
|
from flask_login import login_required, current_user
|
||||||
|
from elasticsearch_dsl import Q
|
||||||
|
|
||||||
|
from rag.app.qa import rmPrefix, beAdoc
|
||||||
|
from rag.nlp import search, rag_tokenizer, keyword_extraction
|
||||||
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
|
from rag.utils import rmSpace
|
||||||
|
from api.db import LLMType, ParserType
|
||||||
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
|
from api.db.services.llm_service import TenantLLMService
|
||||||
|
from api.db.services.user_service import UserTenantService
|
||||||
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
|
from api.db.services.document_service import DocumentService
|
||||||
|
from api.settings import RetCode, retrievaler, kg_retrievaler
|
||||||
|
from api.utils.api_utils import get_json_result
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
from api.utils.api_utils import get_json_result, token_required, get_data_error_result
|
||||||
|
|
||||||
|
from api.db.db_models import Task, File
|
||||||
|
|
||||||
|
from api.db.services.task_service import TaskService, queue_tasks
|
||||||
|
from api.db.services.user_service import TenantService, UserTenantService
|
||||||
|
|
||||||
|
from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
|
||||||
|
|
||||||
|
from api.utils.api_utils import get_json_result
|
||||||
|
|
||||||
|
from functools import partial
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from elasticsearch_dsl import Q
|
||||||
|
from flask import request, send_file
|
||||||
|
from flask_login import login_required
|
||||||
|
|
||||||
|
from api.db import FileSource, TaskStatus, FileType
|
||||||
|
from api.db.db_models import File
|
||||||
|
from api.db.services.document_service import DocumentService
|
||||||
|
from api.db.services.file2document_service import File2DocumentService
|
||||||
|
from api.db.services.file_service import FileService
|
||||||
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
|
from api.settings import RetCode, retrievaler
|
||||||
|
from api.utils.api_utils import construct_json_result, construct_error_response
|
||||||
|
from rag.app import book, laws, manual, naive, one, paper, presentation, qa, resume, table, picture, audio, email
|
||||||
|
from rag.nlp import search
|
||||||
|
from rag.utils import rmSpace
|
||||||
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
|
from rag.utils.storage_factory import STORAGE_IMPL
|
||||||
|
|
||||||
|
MAXIMUM_OF_UPLOADING_FILES = 256
|
||||||
|
|
||||||
|
MAXIMUM_OF_UPLOADING_FILES = 256
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/dataset/<dataset_id>/documents/upload', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def upload(dataset_id, tenant_id):
|
||||||
|
if 'file' not in request.files:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='No file part!', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
file_objs = request.files.getlist('file')
|
||||||
|
for file_obj in file_objs:
|
||||||
|
if file_obj.filename == '':
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='No file selected!', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
e, kb = KnowledgebaseService.get_by_id(dataset_id)
|
||||||
|
if not e:
|
||||||
|
raise LookupError(f"Can't find the knowledgebase with ID {dataset_id}!")
|
||||||
|
err, _ = FileService.upload_document(kb, file_objs, tenant_id)
|
||||||
|
if err:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg="\n".join(err), retcode=RetCode.SERVER_ERROR)
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/infos', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def docinfos(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
if "id" not in req and "name" not in req:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Id or name should be provided")
|
||||||
|
doc_id=None
|
||||||
|
if "id" in req:
|
||||||
|
doc_id = req["id"]
|
||||||
|
if "name" in req:
|
||||||
|
doc_name = req["name"]
|
||||||
|
doc_id = DocumentService.get_doc_id_by_doc_name(doc_name)
|
||||||
|
e, doc = DocumentService.get_by_id(doc_id)
|
||||||
|
#rename key's name
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_num": "chunk_count",
|
||||||
|
"kb_id": "knowledgebase_id",
|
||||||
|
"token_num": "token_count",
|
||||||
|
"parser_id":"parser_method",
|
||||||
|
}
|
||||||
|
renamed_doc = {}
|
||||||
|
for key, value in doc.to_dict().items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_doc[new_key] = value
|
||||||
|
|
||||||
|
return get_json_result(data=renamed_doc)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/save', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def save_doc(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
#get doc by id or name
|
||||||
|
doc_id = None
|
||||||
|
if "id" in req:
|
||||||
|
doc_id = req["id"]
|
||||||
|
elif "name" in req:
|
||||||
|
doc_name = req["name"]
|
||||||
|
doc_id = DocumentService.get_doc_id_by_doc_name(doc_name)
|
||||||
|
if not doc_id:
|
||||||
|
return get_json_result(retcode=400, retmsg="Document ID or name is required")
|
||||||
|
e, doc = DocumentService.get_by_id(doc_id)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
#other value can't be changed
|
||||||
|
if "chunk_count" in req:
|
||||||
|
if req["chunk_count"] != doc.chunk_num:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change chunk_count.")
|
||||||
|
if "token_count" in req:
|
||||||
|
if req["token_count"] != doc.token_num:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change token_count.")
|
||||||
|
if "progress" in req:
|
||||||
|
if req['progress'] != doc.progress:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Can't change progress.")
|
||||||
|
#change name or parse_method
|
||||||
|
if "name" in req and req["name"] != doc.name:
|
||||||
|
try:
|
||||||
|
if pathlib.Path(req["name"].lower()).suffix != pathlib.Path(
|
||||||
|
doc.name.lower()).suffix:
|
||||||
|
return get_json_result(
|
||||||
|
data=False,
|
||||||
|
retmsg="The extension of file can't be changed",
|
||||||
|
retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
for d in DocumentService.query(name=req["name"], kb_id=doc.kb_id):
|
||||||
|
if d.name == req["name"]:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Duplicated document name in the same knowledgebase.")
|
||||||
|
|
||||||
|
if not DocumentService.update_by_id(
|
||||||
|
doc_id, {"name": req["name"]}):
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Database error (Document rename)!")
|
||||||
|
|
||||||
|
informs = File2DocumentService.get_by_document_id(doc_id)
|
||||||
|
if informs:
|
||||||
|
e, file = FileService.get_by_id(informs[0].file_id)
|
||||||
|
FileService.update_by_id(file.id, {"name": req["name"]})
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
if "parser_method" in req:
|
||||||
|
try:
|
||||||
|
if doc.parser_id.lower() == req["parser_method"].lower():
|
||||||
|
if "parser_config" in req:
|
||||||
|
if req["parser_config"] == doc.parser_config:
|
||||||
|
return get_json_result(data=True)
|
||||||
|
else:
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
if doc.type == FileType.VISUAL or re.search(
|
||||||
|
r"\.(ppt|pptx|pages)$", doc.name):
|
||||||
|
return get_data_error_result(retmsg="Not supported yet!")
|
||||||
|
|
||||||
|
e = DocumentService.update_by_id(doc.id,
|
||||||
|
{"parser_id": req["parser_method"], "progress": 0, "progress_msg": "",
|
||||||
|
"run": TaskStatus.UNSTART.value})
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
if "parser_config" in req:
|
||||||
|
DocumentService.update_parser_config(doc.id, req["parser_config"])
|
||||||
|
if doc.token_num > 0:
|
||||||
|
e = DocumentService.increment_chunk_num(doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1,
|
||||||
|
doc.process_duation * -1)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
tenant_id = DocumentService.get_tenant_id(req["id"])
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
ELASTICSEARCH.deleteByQuery(
|
||||||
|
Q("match", doc_id=doc.id), idxnm=search.index_name(tenant_id))
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/change_parser', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def change_parser(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
try:
|
||||||
|
e, doc = DocumentService.get_by_id(req["doc_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
if doc.parser_id.lower() == req["parser_id"].lower():
|
||||||
|
if "parser_config" in req:
|
||||||
|
if req["parser_config"] == doc.parser_config:
|
||||||
|
return get_json_result(data=True)
|
||||||
|
else:
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
if doc.type == FileType.VISUAL or re.search(
|
||||||
|
r"\.(ppt|pptx|pages)$", doc.name):
|
||||||
|
return get_data_error_result(retmsg="Not supported yet!")
|
||||||
|
|
||||||
|
e = DocumentService.update_by_id(doc.id,
|
||||||
|
{"parser_id": req["parser_id"], "progress": 0, "progress_msg": "",
|
||||||
|
"run": TaskStatus.UNSTART.value})
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
if "parser_config" in req:
|
||||||
|
DocumentService.update_parser_config(doc.id, req["parser_config"])
|
||||||
|
if doc.token_num > 0:
|
||||||
|
e = DocumentService.increment_chunk_num(doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1,
|
||||||
|
doc.process_duation * -1)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
tenant_id = DocumentService.get_tenant_id(req["doc_id"])
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
ELASTICSEARCH.deleteByQuery(
|
||||||
|
Q("match", doc_id=doc.id), idxnm=search.index_name(tenant_id))
|
||||||
|
|
||||||
|
return get_json_result(data=True)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
@manager.route('/rename', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("doc_id", "name")
|
||||||
|
def rename():
|
||||||
|
req = request.json
|
||||||
|
try:
|
||||||
|
e, doc = DocumentService.get_by_id(req["doc_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
if pathlib.Path(req["name"].lower()).suffix != pathlib.Path(
|
||||||
|
doc.name.lower()).suffix:
|
||||||
|
return get_json_result(
|
||||||
|
data=False,
|
||||||
|
retmsg="The extension of file can't be changed",
|
||||||
|
retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
for d in DocumentService.query(name=req["name"], kb_id=doc.kb_id):
|
||||||
|
if d.name == req["name"]:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Duplicated document name in the same knowledgebase.")
|
||||||
|
|
||||||
|
if not DocumentService.update_by_id(
|
||||||
|
req["doc_id"], {"name": req["name"]}):
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Database error (Document rename)!")
|
||||||
|
|
||||||
|
informs = File2DocumentService.get_by_document_id(req["doc_id"])
|
||||||
|
if informs:
|
||||||
|
e, file = FileService.get_by_id(informs[0].file_id)
|
||||||
|
FileService.update_by_id(file.id, {"name": req["name"]})
|
||||||
|
|
||||||
|
return get_json_result(data=True)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route("/<document_id>", methods=["GET"])
|
||||||
|
@token_required
|
||||||
|
def download_document(document_id,tenant_id):
|
||||||
|
try:
|
||||||
|
# Check whether there is this document
|
||||||
|
exist, document = DocumentService.get_by_id(document_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(message=f"This document '{document_id}' cannot be found!",
|
||||||
|
code=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
# The process of downloading
|
||||||
|
doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
|
||||||
|
file_stream = STORAGE_IMPL.get(doc_id, doc_location)
|
||||||
|
if not file_stream:
|
||||||
|
return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
|
||||||
|
|
||||||
|
file = BytesIO(file_stream)
|
||||||
|
|
||||||
|
# Use send_file with a proper filename and MIME type
|
||||||
|
return send_file(
|
||||||
|
file,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=document.name,
|
||||||
|
mimetype='application/octet-stream' # Set a default MIME type
|
||||||
|
)
|
||||||
|
|
||||||
|
# Error
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/dataset/<dataset_id>/documents', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def list_docs(dataset_id, tenant_id):
|
||||||
|
kb_id = request.args.get("knowledgebase_id")
|
||||||
|
if not kb_id:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Lack of "KB ID"', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
tenants = UserTenantService.query(user_id=tenant_id)
|
||||||
|
for tenant in tenants:
|
||||||
|
if KnowledgebaseService.query(
|
||||||
|
tenant_id=tenant.tenant_id, id=kb_id):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of knowledgebase authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
keywords = request.args.get("keywords", "")
|
||||||
|
|
||||||
|
page_number = int(request.args.get("page", 1))
|
||||||
|
items_per_page = int(request.args.get("page_size", 15))
|
||||||
|
orderby = request.args.get("orderby", "create_time")
|
||||||
|
desc = request.args.get("desc", True)
|
||||||
|
try:
|
||||||
|
docs, tol = DocumentService.get_by_kb_id(
|
||||||
|
kb_id, page_number, items_per_page, orderby, desc, keywords)
|
||||||
|
|
||||||
|
# rename key's name
|
||||||
|
renamed_doc_list = []
|
||||||
|
for doc in docs:
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_num": "chunk_count",
|
||||||
|
"kb_id": "knowledgebase_id",
|
||||||
|
"token_num": "token_count",
|
||||||
|
"parser_id":"parser_method"
|
||||||
|
}
|
||||||
|
renamed_doc = {}
|
||||||
|
for key, value in doc.items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_doc[new_key] = value
|
||||||
|
renamed_doc_list.append(renamed_doc)
|
||||||
|
return get_json_result(data={"total": tol, "docs": renamed_doc_list})
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/delete', methods=['DELETE'])
|
||||||
|
@token_required
|
||||||
|
def rm(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
if "document_id" not in req:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="doc_id is required")
|
||||||
|
doc_ids = req["document_id"]
|
||||||
|
if isinstance(doc_ids, str): doc_ids = [doc_ids]
|
||||||
|
root_folder = FileService.get_root_folder(tenant_id)
|
||||||
|
pf_id = root_folder["id"]
|
||||||
|
FileService.init_knowledgebase_docs(pf_id, tenant_id)
|
||||||
|
errors = ""
|
||||||
|
for doc_id in doc_ids:
|
||||||
|
try:
|
||||||
|
e, doc = DocumentService.get_by_id(doc_id)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
tenant_id = DocumentService.get_tenant_id(doc_id)
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
|
b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
|
||||||
|
|
||||||
|
if not DocumentService.remove_document(doc, tenant_id):
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Database error (Document removal)!")
|
||||||
|
|
||||||
|
f2d = File2DocumentService.get_by_document_id(doc_id)
|
||||||
|
FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
|
||||||
|
File2DocumentService.delete_by_document_id(doc_id)
|
||||||
|
|
||||||
|
STORAGE_IMPL.rm(b, n)
|
||||||
|
except Exception as e:
|
||||||
|
errors += str(e)
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
return get_json_result(data=False, retmsg=errors, retcode=RetCode.SERVER_ERROR)
|
||||||
|
|
||||||
|
return get_json_result(data=True, retmsg="success")
|
||||||
|
|
||||||
|
@manager.route("/<document_id>/status", methods=["GET"])
|
||||||
|
@token_required
|
||||||
|
def show_parsing_status(tenant_id, document_id):
|
||||||
|
try:
|
||||||
|
# valid document
|
||||||
|
exist, _ = DocumentService.get_by_id(document_id)
|
||||||
|
if not exist:
|
||||||
|
return construct_json_result(code=RetCode.DATA_ERROR,
|
||||||
|
message=f"This document: '{document_id}' is not a valid document.")
|
||||||
|
|
||||||
|
_, doc = DocumentService.get_by_id(document_id) # get doc object
|
||||||
|
doc_attributes = doc.to_dict()
|
||||||
|
|
||||||
|
return construct_json_result(
|
||||||
|
data={"progress": doc_attributes["progress"], "status": TaskStatus(doc_attributes["status"]).name},
|
||||||
|
code=RetCode.SUCCESS
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
return construct_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/run', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def run(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
try:
|
||||||
|
for id in req["document_ids"]:
|
||||||
|
info = {"run": str(req["run"]), "progress": 0}
|
||||||
|
if str(req["run"]) == TaskStatus.RUNNING.value:
|
||||||
|
info["progress_msg"] = ""
|
||||||
|
info["chunk_num"] = 0
|
||||||
|
info["token_num"] = 0
|
||||||
|
DocumentService.update_by_id(id, info)
|
||||||
|
# if str(req["run"]) == TaskStatus.CANCEL.value:
|
||||||
|
tenant_id = DocumentService.get_tenant_id(id)
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
ELASTICSEARCH.deleteByQuery(
|
||||||
|
Q("match", doc_id=id), idxnm=search.index_name(tenant_id))
|
||||||
|
|
||||||
|
if str(req["run"]) == TaskStatus.RUNNING.value:
|
||||||
|
TaskService.filter_delete([Task.doc_id == id])
|
||||||
|
e, doc = DocumentService.get_by_id(id)
|
||||||
|
doc = doc.to_dict()
|
||||||
|
doc["tenant_id"] = tenant_id
|
||||||
|
bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
|
||||||
|
queue_tasks(doc, bucket, name)
|
||||||
|
|
||||||
|
return get_json_result(data=True)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/chunk/list', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
@validate_request("document_id")
|
||||||
|
def list_chunk(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
doc_id = req["document_id"]
|
||||||
|
page = int(req.get("page", 1))
|
||||||
|
size = int(req.get("size", 30))
|
||||||
|
question = req.get("keywords", "")
|
||||||
|
try:
|
||||||
|
tenant_id = DocumentService.get_tenant_id(req["document_id"])
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
e, doc = DocumentService.get_by_id(doc_id)
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
query = {
|
||||||
|
"doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
|
||||||
|
}
|
||||||
|
if "available_int" in req:
|
||||||
|
query["available_int"] = int(req["available_int"])
|
||||||
|
sres = retrievaler.search(query, search.index_name(tenant_id), highlight=True)
|
||||||
|
res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
|
||||||
|
|
||||||
|
origin_chunks=[]
|
||||||
|
for id in sres.ids:
|
||||||
|
d = {
|
||||||
|
"chunk_id": id,
|
||||||
|
"content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[
|
||||||
|
id].get(
|
||||||
|
"content_with_weight", ""),
|
||||||
|
"doc_id": sres.field[id]["doc_id"],
|
||||||
|
"docnm_kwd": sres.field[id]["docnm_kwd"],
|
||||||
|
"important_kwd": sres.field[id].get("important_kwd", []),
|
||||||
|
"img_id": sres.field[id].get("img_id", ""),
|
||||||
|
"available_int": sres.field[id].get("available_int", 1),
|
||||||
|
"positions": sres.field[id].get("position_int", "").split("\t")
|
||||||
|
}
|
||||||
|
if len(d["positions"]) % 5 == 0:
|
||||||
|
poss = []
|
||||||
|
for i in range(0, len(d["positions"]), 5):
|
||||||
|
poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
|
||||||
|
float(d["positions"][i + 3]), float(d["positions"][i + 4])])
|
||||||
|
d["positions"] = poss
|
||||||
|
|
||||||
|
origin_chunks.append(d)
|
||||||
|
##rename keys
|
||||||
|
for chunk in origin_chunks:
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_id": "id",
|
||||||
|
"content_with_weight": "content",
|
||||||
|
"doc_id": "document_id",
|
||||||
|
"important_kwd": "important_keywords",
|
||||||
|
"img_id":"image_id",
|
||||||
|
}
|
||||||
|
renamed_chunk = {}
|
||||||
|
for key, value in chunk.items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_chunk[new_key] = value
|
||||||
|
res["chunks"].append(renamed_chunk)
|
||||||
|
return get_json_result(data=res)
|
||||||
|
except Exception as e:
|
||||||
|
if str(e).find("not_found") > 0:
|
||||||
|
return get_json_result(data=False, retmsg=f'No chunk found!',
|
||||||
|
retcode=RetCode.DATA_ERROR)
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/chunk/create', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
@validate_request("document_id", "content")
|
||||||
|
def create(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
md5 = hashlib.md5()
|
||||||
|
md5.update((req["content"] + req["document_id"]).encode("utf-8"))
|
||||||
|
|
||||||
|
chunk_id = md5.hexdigest()
|
||||||
|
d = {"id": chunk_id, "content_ltks": rag_tokenizer.tokenize(req["content"]),
|
||||||
|
"content_with_weight": req["content"]}
|
||||||
|
d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
|
||||||
|
d["important_kwd"] = req.get("important_kwd", [])
|
||||||
|
d["important_tks"] = rag_tokenizer.tokenize(" ".join(req.get("important_kwd", [])))
|
||||||
|
d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
|
||||||
|
d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
|
||||||
|
|
||||||
|
try:
|
||||||
|
e, doc = DocumentService.get_by_id(req["document_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
d["kb_id"] = [doc.kb_id]
|
||||||
|
d["docnm_kwd"] = doc.name
|
||||||
|
d["doc_id"] = doc.id
|
||||||
|
|
||||||
|
tenant_id = DocumentService.get_tenant_id(req["document_id"])
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
|
embd_id = DocumentService.get_embd_id(req["document_id"])
|
||||||
|
embd_mdl = TenantLLMService.model_instance(
|
||||||
|
tenant_id, LLMType.EMBEDDING.value, embd_id)
|
||||||
|
|
||||||
|
v, c = embd_mdl.encode([doc.name, req["content"]])
|
||||||
|
v = 0.1 * v[0] + 0.9 * v[1]
|
||||||
|
d["q_%d_vec" % len(v)] = v.tolist()
|
||||||
|
ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
|
||||||
|
|
||||||
|
DocumentService.increment_chunk_num(
|
||||||
|
doc.id, doc.kb_id, c, 1, 0)
|
||||||
|
d["chunk_id"] = chunk_id
|
||||||
|
#rename keys
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_id": "id",
|
||||||
|
"content_with_weight": "content",
|
||||||
|
"doc_id": "document_id",
|
||||||
|
"important_kwd": "important_keywords",
|
||||||
|
"kb_id":"dataset_id",
|
||||||
|
"create_timestamp_flt":"create_timestamp",
|
||||||
|
"create_time": "create_time",
|
||||||
|
"document_keyword":"document",
|
||||||
|
}
|
||||||
|
renamed_chunk = {}
|
||||||
|
for key, value in d.items():
|
||||||
|
if key in key_mapping:
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
renamed_chunk[new_key] = value
|
||||||
|
|
||||||
|
return get_json_result(data={"chunk": renamed_chunk})
|
||||||
|
# return get_json_result(data={"chunk_id": chunk_id})
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
@manager.route('/chunk/rm', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
@validate_request("chunk_ids", "document_id")
|
||||||
|
def rm_chunk(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
try:
|
||||||
|
if not ELASTICSEARCH.deleteByQuery(
|
||||||
|
Q("ids", values=req["chunk_ids"]), search.index_name(tenant_id)):
|
||||||
|
return get_data_error_result(retmsg="Index updating failure")
|
||||||
|
e, doc = DocumentService.get_by_id(req["document_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
deleted_chunk_ids = req["chunk_ids"]
|
||||||
|
chunk_number = len(deleted_chunk_ids)
|
||||||
|
DocumentService.decrement_chunk_num(doc.id, doc.kb_id, 1, chunk_number, 0)
|
||||||
|
return get_json_result(data=True)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
@manager.route('/chunk/set', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
@validate_request("document_id", "chunk_id", "content",
|
||||||
|
"important_keywords")
|
||||||
|
def set(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
d = {
|
||||||
|
"id": req["chunk_id"],
|
||||||
|
"content_with_weight": req["content"]}
|
||||||
|
d["content_ltks"] = rag_tokenizer.tokenize(req["content"])
|
||||||
|
d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
|
||||||
|
d["important_kwd"] = req["important_keywords"]
|
||||||
|
d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
|
||||||
|
if "available" in req:
|
||||||
|
d["available_int"] = req["available"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
tenant_id = DocumentService.get_tenant_id(req["document_id"])
|
||||||
|
if not tenant_id:
|
||||||
|
return get_data_error_result(retmsg="Tenant not found!")
|
||||||
|
|
||||||
|
embd_id = DocumentService.get_embd_id(req["document_id"])
|
||||||
|
embd_mdl = TenantLLMService.model_instance(
|
||||||
|
tenant_id, LLMType.EMBEDDING.value, embd_id)
|
||||||
|
|
||||||
|
e, doc = DocumentService.get_by_id(req["document_id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Document not found!")
|
||||||
|
|
||||||
|
if doc.parser_id == ParserType.QA:
|
||||||
|
arr = [
|
||||||
|
t for t in re.split(
|
||||||
|
r"[\n\t]",
|
||||||
|
req["content"]) if len(t) > 1]
|
||||||
|
if len(arr) != 2:
|
||||||
|
return get_data_error_result(
|
||||||
|
retmsg="Q&A must be separated by TAB/ENTER key.")
|
||||||
|
q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
|
||||||
|
d = beAdoc(d, arr[0], arr[1], not any(
|
||||||
|
[rag_tokenizer.is_chinese(t) for t in q + a]))
|
||||||
|
|
||||||
|
v, c = embd_mdl.encode([doc.name, req["content"]])
|
||||||
|
v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
|
||||||
|
d["q_%d_vec" % len(v)] = v.tolist()
|
||||||
|
ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
|
||||||
|
return get_json_result(data=True)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
@manager.route('/retrieval_test', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
@validate_request("knowledgebase_id", "question")
|
||||||
|
def retrieval_test(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
page = int(req.get("page", 1))
|
||||||
|
size = int(req.get("size", 30))
|
||||||
|
question = req["question"]
|
||||||
|
kb_id = req["knowledgebase_id"]
|
||||||
|
if isinstance(kb_id, str): kb_id = [kb_id]
|
||||||
|
doc_ids = req.get("doc_ids", [])
|
||||||
|
similarity_threshold = float(req.get("similarity_threshold", 0.2))
|
||||||
|
vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
|
||||||
|
top = int(req.get("top_k", 1024))
|
||||||
|
|
||||||
|
try:
|
||||||
|
tenants = UserTenantService.query(user_id=tenant_id)
|
||||||
|
for kid in kb_id:
|
||||||
|
for tenant in tenants:
|
||||||
|
if KnowledgebaseService.query(
|
||||||
|
tenant_id=tenant.tenant_id, id=kid):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f'Only owner of knowledgebase authorized for this operation.',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
e, kb = KnowledgebaseService.get_by_id(kb_id[0])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Knowledgebase not found!")
|
||||||
|
|
||||||
|
embd_mdl = TenantLLMService.model_instance(
|
||||||
|
kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
|
||||||
|
|
||||||
|
rerank_mdl = None
|
||||||
|
if req.get("rerank_id"):
|
||||||
|
rerank_mdl = TenantLLMService.model_instance(
|
||||||
|
kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
|
||||||
|
|
||||||
|
if req.get("keyword", False):
|
||||||
|
chat_mdl = TenantLLMService.model_instance(kb.tenant_id, LLMType.CHAT)
|
||||||
|
question += keyword_extraction(chat_mdl, question)
|
||||||
|
|
||||||
|
retr = retrievaler if kb.parser_id != ParserType.KG else kg_retrievaler
|
||||||
|
ranks = retr.retrieval(question, embd_mdl, kb.tenant_id, kb_id, page, size,
|
||||||
|
similarity_threshold, vector_similarity_weight, top,
|
||||||
|
doc_ids, rerank_mdl=rerank_mdl, highlight=req.get("highlight"))
|
||||||
|
for c in ranks["chunks"]:
|
||||||
|
if "vector" in c:
|
||||||
|
del c["vector"]
|
||||||
|
|
||||||
|
##rename keys
|
||||||
|
renamed_chunks=[]
|
||||||
|
for chunk in ranks["chunks"]:
|
||||||
|
key_mapping = {
|
||||||
|
"chunk_id": "id",
|
||||||
|
"content_with_weight": "content",
|
||||||
|
"doc_id": "document_id",
|
||||||
|
"important_kwd": "important_keywords",
|
||||||
|
"docnm_kwd":"document_keyword"
|
||||||
|
}
|
||||||
|
rename_chunk={}
|
||||||
|
for key, value in chunk.items():
|
||||||
|
new_key = key_mapping.get(key, key)
|
||||||
|
rename_chunk[new_key] = value
|
||||||
|
renamed_chunks.append(rename_chunk)
|
||||||
|
ranks["chunks"] = renamed_chunks
|
||||||
|
return get_json_result(data=ranks)
|
||||||
|
except Exception as e:
|
||||||
|
if str(e).find("not_found") > 0:
|
||||||
|
return get_json_result(data=False, retmsg=f'No chunk found! Check the chunk status please!',
|
||||||
|
retcode=RetCode.DATA_ERROR)
|
||||||
|
return server_error_response(e)
|
||||||
266
api/apps/sdk/session.py
Normal file
266
api/apps/sdk/session.py
Normal file
@ -0,0 +1,266 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
import json
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from flask import request, Response
|
||||||
|
|
||||||
|
from api.db import StatusEnum
|
||||||
|
from api.db.services.dialog_service import DialogService, ConversationService, chat
|
||||||
|
from api.settings import RetCode
|
||||||
|
from api.utils import get_uuid
|
||||||
|
from api.utils.api_utils import get_data_error_result
|
||||||
|
from api.utils.api_utils import get_json_result, token_required
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/save', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def set_conversation(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
conv_id = req.get("id")
|
||||||
|
if "assistant_id" in req:
|
||||||
|
req["dialog_id"] = req.pop("assistant_id")
|
||||||
|
if "id" in req:
|
||||||
|
del req["id"]
|
||||||
|
conv = ConversationService.query(id=conv_id)
|
||||||
|
if not conv:
|
||||||
|
return get_data_error_result(retmsg="Session does not exist")
|
||||||
|
if not DialogService.query(id=conv[0].dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_data_error_result(retmsg="You do not own the session")
|
||||||
|
if req.get("dialog_id"):
|
||||||
|
dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
|
||||||
|
if not dia:
|
||||||
|
return get_data_error_result(retmsg="You do not own the assistant")
|
||||||
|
if "dialog_id" in req and not req.get("dialog_id"):
|
||||||
|
return get_data_error_result(retmsg="assistant_id can not be empty.")
|
||||||
|
if "message" in req:
|
||||||
|
return get_data_error_result(retmsg="message can not be change")
|
||||||
|
if "reference" in req:
|
||||||
|
return get_data_error_result(retmsg="reference can not be change")
|
||||||
|
if "name" in req and not req.get("name"):
|
||||||
|
return get_data_error_result(retmsg="name can not be empty.")
|
||||||
|
if not ConversationService.update_by_id(conv_id, req):
|
||||||
|
return get_data_error_result(retmsg="Session updates error")
|
||||||
|
return get_json_result(data=True)
|
||||||
|
|
||||||
|
if not req.get("dialog_id"):
|
||||||
|
return get_data_error_result(retmsg="assistant_id is required.")
|
||||||
|
dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
|
||||||
|
if not dia:
|
||||||
|
return get_data_error_result(retmsg="You do not own the assistant")
|
||||||
|
conv = {
|
||||||
|
"id": get_uuid(),
|
||||||
|
"dialog_id": req["dialog_id"],
|
||||||
|
"name": req.get("name", "New session"),
|
||||||
|
"message": [{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]
|
||||||
|
}
|
||||||
|
if not conv.get("name"):
|
||||||
|
return get_data_error_result(retmsg="name can not be empty.")
|
||||||
|
ConversationService.save(**conv)
|
||||||
|
e, conv = ConversationService.get_by_id(conv["id"])
|
||||||
|
if not e:
|
||||||
|
return get_data_error_result(retmsg="Fail to new session!")
|
||||||
|
conv = conv.to_dict()
|
||||||
|
conv['messages'] = conv.pop("message")
|
||||||
|
conv["assistant_id"] = conv.pop("dialog_id")
|
||||||
|
del conv["reference"]
|
||||||
|
return get_json_result(data=conv)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/completion', methods=['POST'])
|
||||||
|
@token_required
|
||||||
|
def completion(tenant_id):
|
||||||
|
req = request.json
|
||||||
|
# req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
|
||||||
|
# {"role": "user", "content": "上海有吗?"}
|
||||||
|
# ]}
|
||||||
|
if "session_id" not in req:
|
||||||
|
return get_data_error_result(retmsg="session_id is required")
|
||||||
|
conv = ConversationService.query(id=req["session_id"])
|
||||||
|
if not conv:
|
||||||
|
return get_data_error_result(retmsg="Session does not exist")
|
||||||
|
conv = conv[0]
|
||||||
|
if not DialogService.query(id=conv.dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_data_error_result(retmsg="You do not own the session")
|
||||||
|
msg = []
|
||||||
|
question = {
|
||||||
|
"content": req.get("question"),
|
||||||
|
"role": "user",
|
||||||
|
"id": str(uuid4())
|
||||||
|
}
|
||||||
|
conv.message.append(question)
|
||||||
|
for m in conv.message:
|
||||||
|
if m["role"] == "system": continue
|
||||||
|
if m["role"] == "assistant" and not msg: continue
|
||||||
|
msg.append(m)
|
||||||
|
message_id = msg[-1].get("id")
|
||||||
|
e, dia = DialogService.get_by_id(conv.dialog_id)
|
||||||
|
del req["session_id"]
|
||||||
|
|
||||||
|
if not conv.reference:
|
||||||
|
conv.reference = []
|
||||||
|
conv.message.append({"role": "assistant", "content": "", "id": message_id})
|
||||||
|
conv.reference.append({"chunks": [], "doc_aggs": []})
|
||||||
|
|
||||||
|
def fillin_conv(ans):
|
||||||
|
nonlocal conv, message_id
|
||||||
|
if not conv.reference:
|
||||||
|
conv.reference.append(ans["reference"])
|
||||||
|
else:
|
||||||
|
conv.reference[-1] = ans["reference"]
|
||||||
|
conv.message[-1] = {"role": "assistant", "content": ans["answer"],
|
||||||
|
"id": message_id, "prompt": ans.get("prompt", "")}
|
||||||
|
ans["id"] = message_id
|
||||||
|
|
||||||
|
def stream():
|
||||||
|
nonlocal dia, msg, req, conv
|
||||||
|
try:
|
||||||
|
for ans in chat(dia, msg, **req):
|
||||||
|
fillin_conv(ans)
|
||||||
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
|
||||||
|
ConversationService.update_by_id(conv.id, conv.to_dict())
|
||||||
|
except Exception as e:
|
||||||
|
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
|
||||||
|
"data": {"answer": "**ERROR**: " + str(e), "reference": []}},
|
||||||
|
ensure_ascii=False) + "\n\n"
|
||||||
|
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
|
||||||
|
|
||||||
|
if req.get("stream", True):
|
||||||
|
resp = Response(stream(), mimetype="text/event-stream")
|
||||||
|
resp.headers.add_header("Cache-control", "no-cache")
|
||||||
|
resp.headers.add_header("Connection", "keep-alive")
|
||||||
|
resp.headers.add_header("X-Accel-Buffering", "no")
|
||||||
|
resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
|
||||||
|
return resp
|
||||||
|
|
||||||
|
else:
|
||||||
|
answer = None
|
||||||
|
for ans in chat(dia, msg, **req):
|
||||||
|
answer = ans
|
||||||
|
fillin_conv(ans)
|
||||||
|
ConversationService.update_by_id(conv.id, conv.to_dict())
|
||||||
|
break
|
||||||
|
return get_json_result(data=answer)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/get', methods=['GET'])
|
||||||
|
@token_required
|
||||||
|
def get(tenant_id):
|
||||||
|
req = request.args
|
||||||
|
if "id" not in req:
|
||||||
|
return get_data_error_result(retmsg="id is required")
|
||||||
|
conv_id = req["id"]
|
||||||
|
conv = ConversationService.query(id=conv_id)
|
||||||
|
if not conv:
|
||||||
|
return get_data_error_result(retmsg="Session does not exist")
|
||||||
|
if not DialogService.query(id=conv[0].dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_data_error_result(retmsg="You do not own the session")
|
||||||
|
if "assistant_id" in req:
|
||||||
|
if req["assistant_id"] != conv[0].dialog_id:
|
||||||
|
return get_data_error_result(retmsg="The session doesn't belong to the assistant")
|
||||||
|
conv = conv[0].to_dict()
|
||||||
|
conv['messages'] = conv.pop("message")
|
||||||
|
conv["assistant_id"] = conv.pop("dialog_id")
|
||||||
|
if conv["reference"]:
|
||||||
|
messages = conv["messages"]
|
||||||
|
message_num = 0
|
||||||
|
chunk_num = 0
|
||||||
|
while message_num < len(messages):
|
||||||
|
if message_num != 0 and messages[message_num]["role"] != "user":
|
||||||
|
chunk_list = []
|
||||||
|
if "chunks" in conv["reference"][chunk_num]:
|
||||||
|
chunks = conv["reference"][chunk_num]["chunks"]
|
||||||
|
for chunk in chunks:
|
||||||
|
new_chunk = {
|
||||||
|
"id": chunk["chunk_id"],
|
||||||
|
"content": chunk["content_with_weight"],
|
||||||
|
"document_id": chunk["doc_id"],
|
||||||
|
"document_name": chunk["docnm_kwd"],
|
||||||
|
"knowledgebase_id": chunk["kb_id"],
|
||||||
|
"image_id": chunk["img_id"],
|
||||||
|
"similarity": chunk["similarity"],
|
||||||
|
"vector_similarity": chunk["vector_similarity"],
|
||||||
|
"term_similarity": chunk["term_similarity"],
|
||||||
|
"positions": chunk["positions"],
|
||||||
|
}
|
||||||
|
chunk_list.append(new_chunk)
|
||||||
|
chunk_num += 1
|
||||||
|
messages[message_num]["reference"] = chunk_list
|
||||||
|
message_num += 1
|
||||||
|
del conv["reference"]
|
||||||
|
return get_json_result(data=conv)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/list', methods=["GET"])
|
||||||
|
@token_required
|
||||||
|
def list(tenant_id):
|
||||||
|
assistant_id = request.args["assistant_id"]
|
||||||
|
if not DialogService.query(tenant_id=tenant_id, id=assistant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg=f"You don't own the assistant.",
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
convs = ConversationService.query(
|
||||||
|
dialog_id=assistant_id,
|
||||||
|
order_by=ConversationService.model.create_time,
|
||||||
|
reverse=True)
|
||||||
|
convs = [d.to_dict() for d in convs]
|
||||||
|
for conv in convs:
|
||||||
|
conv['messages'] = conv.pop("message")
|
||||||
|
conv["assistant_id"] = conv.pop("dialog_id")
|
||||||
|
if conv["reference"]:
|
||||||
|
messages = conv["messages"]
|
||||||
|
message_num = 0
|
||||||
|
chunk_num = 0
|
||||||
|
while message_num < len(messages):
|
||||||
|
if message_num != 0 and messages[message_num]["role"] != "user":
|
||||||
|
chunk_list = []
|
||||||
|
if "chunks" in conv["reference"][chunk_num]:
|
||||||
|
chunks = conv["reference"][chunk_num]["chunks"]
|
||||||
|
for chunk in chunks:
|
||||||
|
new_chunk = {
|
||||||
|
"id": chunk["chunk_id"],
|
||||||
|
"content": chunk["content_with_weight"],
|
||||||
|
"document_id": chunk["doc_id"],
|
||||||
|
"document_name": chunk["docnm_kwd"],
|
||||||
|
"knowledgebase_id": chunk["kb_id"],
|
||||||
|
"image_id": chunk["img_id"],
|
||||||
|
"similarity": chunk["similarity"],
|
||||||
|
"vector_similarity": chunk["vector_similarity"],
|
||||||
|
"term_similarity": chunk["term_similarity"],
|
||||||
|
"positions": chunk["positions"],
|
||||||
|
}
|
||||||
|
chunk_list.append(new_chunk)
|
||||||
|
chunk_num += 1
|
||||||
|
messages[message_num]["reference"] = chunk_list
|
||||||
|
message_num += 1
|
||||||
|
del conv["reference"]
|
||||||
|
return get_json_result(data=convs)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/delete', methods=["DELETE"])
|
||||||
|
@token_required
|
||||||
|
def delete(tenant_id):
|
||||||
|
id = request.args.get("id")
|
||||||
|
if not id:
|
||||||
|
return get_data_error_result(retmsg="`id` is required in deleting operation")
|
||||||
|
conv = ConversationService.query(id=id)
|
||||||
|
if not conv:
|
||||||
|
return get_data_error_result(retmsg="Session doesn't exist")
|
||||||
|
conv = conv[0]
|
||||||
|
if not DialogService.query(id=conv.dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
||||||
|
return get_data_error_result(retmsg="You don't own the session")
|
||||||
|
ConversationService.delete_by_id(id)
|
||||||
|
return get_json_result(data=True)
|
||||||
@ -13,14 +13,17 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License
|
# limitations under the License
|
||||||
#
|
#
|
||||||
|
import json
|
||||||
|
|
||||||
from flask_login import login_required
|
from flask_login import login_required
|
||||||
|
|
||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
|
from api.settings import DATABASE_TYPE
|
||||||
from api.utils.api_utils import get_json_result
|
from api.utils.api_utils import get_json_result
|
||||||
from api.versions import get_rag_version
|
from api.versions import get_rag_version
|
||||||
from rag.settings import SVR_QUEUE_NAME
|
from rag.settings import SVR_QUEUE_NAME
|
||||||
from rag.utils.es_conn import ELASTICSEARCH
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
from rag.utils.minio_conn import MINIO
|
from rag.utils.storage_factory import STORAGE_IMPL, STORAGE_IMPL_TYPE
|
||||||
from timeit import default_timer as timer
|
from timeit import default_timer as timer
|
||||||
|
|
||||||
from rag.utils.redis_conn import REDIS_CONN
|
from rag.utils.redis_conn import REDIS_CONN
|
||||||
@ -45,24 +48,43 @@ def status():
|
|||||||
|
|
||||||
st = timer()
|
st = timer()
|
||||||
try:
|
try:
|
||||||
MINIO.health()
|
STORAGE_IMPL.health()
|
||||||
res["minio"] = {"status": "green", "elapsed": "{:.1f}".format((timer() - st)*1000.)}
|
res["storage"] = {"storage": STORAGE_IMPL_TYPE.lower(), "status": "green", "elapsed": "{:.1f}".format((timer() - st)*1000.)}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
res["minio"] = {"status": "red", "elapsed": "{:.1f}".format((timer() - st)*1000.), "error": str(e)}
|
res["storage"] = {"storage": STORAGE_IMPL_TYPE.lower(), "status": "red", "elapsed": "{:.1f}".format((timer() - st)*1000.), "error": str(e)}
|
||||||
|
|
||||||
st = timer()
|
st = timer()
|
||||||
try:
|
try:
|
||||||
KnowledgebaseService.get_by_id("x")
|
KnowledgebaseService.get_by_id("x")
|
||||||
res["mysql"] = {"status": "green", "elapsed": "{:.1f}".format((timer() - st)*1000.)}
|
res["database"] = {"database": DATABASE_TYPE.lower(), "status": "green", "elapsed": "{:.1f}".format((timer() - st)*1000.)}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
res["mysql"] = {"status": "red", "elapsed": "{:.1f}".format((timer() - st)*1000.), "error": str(e)}
|
res["database"] = {"database": DATABASE_TYPE.lower(), "status": "red", "elapsed": "{:.1f}".format((timer() - st)*1000.), "error": str(e)}
|
||||||
|
|
||||||
st = timer()
|
st = timer()
|
||||||
try:
|
try:
|
||||||
qinfo = REDIS_CONN.health(SVR_QUEUE_NAME)
|
if not REDIS_CONN.health():
|
||||||
res["redis"] = {"status": "green", "elapsed": "{:.1f}".format((timer() - st)*1000.),
|
raise Exception("Lost connection!")
|
||||||
"pending": qinfo.get("pending", 0)}
|
res["redis"] = {"status": "green", "elapsed": "{:.1f}".format((timer() - st)*1000.)}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
res["redis"] = {"status": "red", "elapsed": "{:.1f}".format((timer() - st)*1000.), "error": str(e)}
|
res["redis"] = {"status": "red", "elapsed": "{:.1f}".format((timer() - st)*1000.), "error": str(e)}
|
||||||
|
|
||||||
|
try:
|
||||||
|
v = REDIS_CONN.get("TASKEXE")
|
||||||
|
if not v:
|
||||||
|
raise Exception("No task executor running!")
|
||||||
|
obj = json.loads(v)
|
||||||
|
color = "green"
|
||||||
|
for id in obj.keys():
|
||||||
|
arr = obj[id]
|
||||||
|
if len(arr) == 1:
|
||||||
|
obj[id] = [0]
|
||||||
|
else:
|
||||||
|
obj[id] = [arr[i+1]-arr[i] for i in range(len(arr)-1)]
|
||||||
|
elapsed = max(obj[id])
|
||||||
|
if elapsed > 50: color = "yellow"
|
||||||
|
if elapsed > 120: color = "red"
|
||||||
|
res["task_executor"] = {"status": color, "elapsed": obj}
|
||||||
|
except Exception as e:
|
||||||
|
res["task_executor"] = {"status": "red", "error": str(e)}
|
||||||
|
|
||||||
return get_json_result(data=res)
|
return get_json_result(data=res)
|
||||||
|
|||||||
85
api/apps/tenant_app.py
Normal file
85
api/apps/tenant_app.py
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
#
|
||||||
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
|
from flask import request
|
||||||
|
from flask_login import current_user, login_required
|
||||||
|
|
||||||
|
from api.db import UserTenantRole, StatusEnum
|
||||||
|
from api.db.db_models import UserTenant
|
||||||
|
from api.db.services.user_service import TenantService, UserTenantService
|
||||||
|
from api.settings import RetCode
|
||||||
|
|
||||||
|
from api.utils import get_uuid
|
||||||
|
from api.utils.api_utils import get_json_result, validate_request, server_error_response
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route("/list", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def tenant_list():
|
||||||
|
try:
|
||||||
|
tenants = TenantService.get_by_user_id(current_user.id)
|
||||||
|
return get_json_result(data=tenants)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route("/<tenant_id>/user/list", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
def user_list(tenant_id):
|
||||||
|
try:
|
||||||
|
users = UserTenantService.get_by_tenant_id(tenant_id)
|
||||||
|
return get_json_result(data=users)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/<tenant_id>/user', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@validate_request("user_id")
|
||||||
|
def create(tenant_id):
|
||||||
|
user_id = request.json.get("user_id")
|
||||||
|
if not user_id:
|
||||||
|
return get_json_result(
|
||||||
|
data=False, retmsg='Lack of "USER ID"', retcode=RetCode.ARGUMENT_ERROR)
|
||||||
|
|
||||||
|
try:
|
||||||
|
user_tenants = UserTenantService.query(user_id=user_id, tenant_id=tenant_id)
|
||||||
|
if user_tenants:
|
||||||
|
uuid = user_tenants[0].id
|
||||||
|
return get_json_result(data={"id": uuid})
|
||||||
|
|
||||||
|
uuid = get_uuid()
|
||||||
|
UserTenantService.save(
|
||||||
|
id = uuid,
|
||||||
|
user_id = user_id,
|
||||||
|
tenant_id = tenant_id,
|
||||||
|
role = UserTenantRole.NORMAL.value,
|
||||||
|
status = StatusEnum.VALID.value)
|
||||||
|
|
||||||
|
return get_json_result(data={"id": uuid})
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
|
|
||||||
|
@manager.route('/<tenant_id>/user/<user_id>', methods=['DELETE'])
|
||||||
|
@login_required
|
||||||
|
def rm(tenant_id, user_id):
|
||||||
|
try:
|
||||||
|
UserTenantService.filter_delete([UserTenant.tenant_id == tenant_id, UserTenant.user_id == user_id])
|
||||||
|
return get_json_result(data=True)
|
||||||
|
except Exception as e:
|
||||||
|
return server_error_response(e)
|
||||||
|
|
||||||
@ -32,28 +32,30 @@ from api.settings import RetCode, GITHUB_OAUTH, FEISHU_OAUTH, CHAT_MDL, EMBEDDIN
|
|||||||
from api.db.services.user_service import UserService, TenantService, UserTenantService
|
from api.db.services.user_service import UserService, TenantService, UserTenantService
|
||||||
from api.db.services.file_service import FileService
|
from api.db.services.file_service import FileService
|
||||||
from api.settings import stat_logger
|
from api.settings import stat_logger
|
||||||
from api.utils.api_utils import get_json_result, cors_reponse
|
from api.utils.api_utils import get_json_result, construct_response
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/login', methods=['POST', 'GET'])
|
@manager.route('/login', methods=['POST', 'GET'])
|
||||||
def login():
|
def login():
|
||||||
login_channel = "password"
|
|
||||||
if not request.json:
|
if not request.json:
|
||||||
return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR,
|
return get_json_result(data=False,
|
||||||
retmsg='Unautherized!')
|
retcode=RetCode.AUTHENTICATION_ERROR,
|
||||||
|
retmsg='Unauthorized!')
|
||||||
|
|
||||||
email = request.json.get('email', "")
|
email = request.json.get('email', "")
|
||||||
users = UserService.query(email=email)
|
users = UserService.query(email=email)
|
||||||
if not users:
|
if not users:
|
||||||
return get_json_result(
|
return get_json_result(data=False,
|
||||||
data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg=f'This Email is not registered!')
|
retcode=RetCode.AUTHENTICATION_ERROR,
|
||||||
|
retmsg=f'Email: {email} is not registered!')
|
||||||
|
|
||||||
password = request.json.get('password')
|
password = request.json.get('password')
|
||||||
try:
|
try:
|
||||||
password = decrypt(password)
|
password = decrypt(password)
|
||||||
except BaseException:
|
except BaseException:
|
||||||
return get_json_result(
|
return get_json_result(data=False,
|
||||||
data=False, retcode=RetCode.SERVER_ERROR, retmsg='Fail to crypt password')
|
retcode=RetCode.SERVER_ERROR,
|
||||||
|
retmsg='Fail to crypt password')
|
||||||
|
|
||||||
user = UserService.query_user(email, password)
|
user = UserService.query_user(email, password)
|
||||||
if user:
|
if user:
|
||||||
@ -64,20 +66,22 @@ def login():
|
|||||||
user.update_date = datetime_format(datetime.now()),
|
user.update_date = datetime_format(datetime.now()),
|
||||||
user.save()
|
user.save()
|
||||||
msg = "Welcome back!"
|
msg = "Welcome back!"
|
||||||
return cors_reponse(data=response_data, auth=user.get_id(), retmsg=msg)
|
return construct_response(data=response_data, auth=user.get_id(), retmsg=msg)
|
||||||
else:
|
else:
|
||||||
return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR,
|
return get_json_result(data=False,
|
||||||
retmsg='Email and Password do not match!')
|
retcode=RetCode.AUTHENTICATION_ERROR,
|
||||||
|
retmsg='Email and password do not match!')
|
||||||
|
|
||||||
|
|
||||||
@manager.route('/github_callback', methods=['GET'])
|
@manager.route('/github_callback', methods=['GET'])
|
||||||
def github_callback():
|
def github_callback():
|
||||||
import requests
|
import requests
|
||||||
res = requests.post(GITHUB_OAUTH.get("url"), data={
|
res = requests.post(GITHUB_OAUTH.get("url"),
|
||||||
"client_id": GITHUB_OAUTH.get("client_id"),
|
data={
|
||||||
"client_secret": GITHUB_OAUTH.get("secret_key"),
|
"client_id": GITHUB_OAUTH.get("client_id"),
|
||||||
"code": request.args.get('code')
|
"client_secret": GITHUB_OAUTH.get("secret_key"),
|
||||||
}, headers={"Accept": "application/json"})
|
"code": request.args.get('code')},
|
||||||
|
headers={"Accept": "application/json"})
|
||||||
res = res.json()
|
res = res.json()
|
||||||
if "error" in res:
|
if "error" in res:
|
||||||
return redirect("/?error=%s" % res["error_description"])
|
return redirect("/?error=%s" % res["error_description"])
|
||||||
@ -87,29 +91,33 @@ def github_callback():
|
|||||||
|
|
||||||
session["access_token"] = res["access_token"]
|
session["access_token"] = res["access_token"]
|
||||||
session["access_token_from"] = "github"
|
session["access_token_from"] = "github"
|
||||||
userinfo = user_info_from_github(session["access_token"])
|
user_info = user_info_from_github(session["access_token"])
|
||||||
users = UserService.query(email=userinfo["email"])
|
email_address = user_info["email"]
|
||||||
|
users = UserService.query(email=email_address)
|
||||||
user_id = get_uuid()
|
user_id = get_uuid()
|
||||||
if not users:
|
if not users:
|
||||||
|
# User isn't try to register
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
avatar = download_img(userinfo["avatar_url"])
|
avatar = download_img(user_info["avatar_url"])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
stat_logger.exception(e)
|
stat_logger.exception(e)
|
||||||
avatar = ""
|
avatar = ""
|
||||||
users = user_register(user_id, {
|
users = user_register(user_id, {
|
||||||
"access_token": session["access_token"],
|
"access_token": session["access_token"],
|
||||||
"email": userinfo["email"],
|
"email": email_address,
|
||||||
"avatar": avatar,
|
"avatar": avatar,
|
||||||
"nickname": userinfo["login"],
|
"nickname": user_info["login"],
|
||||||
"login_channel": "github",
|
"login_channel": "github",
|
||||||
"last_login_time": get_format_time(),
|
"last_login_time": get_format_time(),
|
||||||
"is_superuser": False,
|
"is_superuser": False,
|
||||||
})
|
})
|
||||||
if not users:
|
if not users:
|
||||||
raise Exception('Register user failure.')
|
raise Exception(f'Fail to register {email_address}.')
|
||||||
if len(users) > 1:
|
if len(users) > 1:
|
||||||
raise Exception('Same E-mail exist!')
|
raise Exception(f'Same email: {email_address} exists!')
|
||||||
|
|
||||||
|
# Try to log in
|
||||||
user = users[0]
|
user = users[0]
|
||||||
login_user(user)
|
login_user(user)
|
||||||
return redirect("/?auth=%s" % user.get_id())
|
return redirect("/?auth=%s" % user.get_id())
|
||||||
@ -117,6 +125,8 @@ def github_callback():
|
|||||||
rollback_user_registration(user_id)
|
rollback_user_registration(user_id)
|
||||||
stat_logger.exception(e)
|
stat_logger.exception(e)
|
||||||
return redirect("/?error=%s" % str(e))
|
return redirect("/?error=%s" % str(e))
|
||||||
|
|
||||||
|
# User has already registered, try to log in
|
||||||
user = users[0]
|
user = users[0]
|
||||||
user.access_token = get_uuid()
|
user.access_token = get_uuid()
|
||||||
login_user(user)
|
login_user(user)
|
||||||
@ -127,19 +137,25 @@ def github_callback():
|
|||||||
@manager.route('/feishu_callback', methods=['GET'])
|
@manager.route('/feishu_callback', methods=['GET'])
|
||||||
def feishu_callback():
|
def feishu_callback():
|
||||||
import requests
|
import requests
|
||||||
app_access_token_res = requests.post(FEISHU_OAUTH.get("app_access_token_url"), data=json.dumps({
|
app_access_token_res = requests.post(FEISHU_OAUTH.get("app_access_token_url"),
|
||||||
"app_id": FEISHU_OAUTH.get("app_id"),
|
data=json.dumps({
|
||||||
"app_secret": FEISHU_OAUTH.get("app_secret")
|
"app_id": FEISHU_OAUTH.get("app_id"),
|
||||||
}), headers={"Content-Type": "application/json; charset=utf-8"})
|
"app_secret": FEISHU_OAUTH.get("app_secret")
|
||||||
|
}),
|
||||||
|
headers={"Content-Type": "application/json; charset=utf-8"})
|
||||||
app_access_token_res = app_access_token_res.json()
|
app_access_token_res = app_access_token_res.json()
|
||||||
if app_access_token_res['code'] != 0:
|
if app_access_token_res['code'] != 0:
|
||||||
return redirect("/?error=%s" % app_access_token_res)
|
return redirect("/?error=%s" % app_access_token_res)
|
||||||
|
|
||||||
res = requests.post(FEISHU_OAUTH.get("user_access_token_url"), data=json.dumps({
|
res = requests.post(FEISHU_OAUTH.get("user_access_token_url"),
|
||||||
"grant_type": FEISHU_OAUTH.get("grant_type"),
|
data=json.dumps({
|
||||||
"code": request.args.get('code')
|
"grant_type": FEISHU_OAUTH.get("grant_type"),
|
||||||
}), headers={"Content-Type": "application/json; charset=utf-8",
|
"code": request.args.get('code')
|
||||||
'Authorization': f"Bearer {app_access_token_res['app_access_token']}"})
|
}),
|
||||||
|
headers={
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
'Authorization': f"Bearer {app_access_token_res['app_access_token']}"
|
||||||
|
})
|
||||||
res = res.json()
|
res = res.json()
|
||||||
if res['code'] != 0:
|
if res['code'] != 0:
|
||||||
return redirect("/?error=%s" % res["message"])
|
return redirect("/?error=%s" % res["message"])
|
||||||
@ -148,29 +164,33 @@ def feishu_callback():
|
|||||||
return redirect("/?error=contact:user.email:readonly not in scope")
|
return redirect("/?error=contact:user.email:readonly not in scope")
|
||||||
session["access_token"] = res["data"]["access_token"]
|
session["access_token"] = res["data"]["access_token"]
|
||||||
session["access_token_from"] = "feishu"
|
session["access_token_from"] = "feishu"
|
||||||
userinfo = user_info_from_feishu(session["access_token"])
|
user_info = user_info_from_feishu(session["access_token"])
|
||||||
users = UserService.query(email=userinfo["email"])
|
email_address = user_info["email"]
|
||||||
|
users = UserService.query(email=email_address)
|
||||||
user_id = get_uuid()
|
user_id = get_uuid()
|
||||||
if not users:
|
if not users:
|
||||||
|
# User isn't try to register
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
avatar = download_img(userinfo["avatar_url"])
|
avatar = download_img(user_info["avatar_url"])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
stat_logger.exception(e)
|
stat_logger.exception(e)
|
||||||
avatar = ""
|
avatar = ""
|
||||||
users = user_register(user_id, {
|
users = user_register(user_id, {
|
||||||
"access_token": session["access_token"],
|
"access_token": session["access_token"],
|
||||||
"email": userinfo["email"],
|
"email": email_address,
|
||||||
"avatar": avatar,
|
"avatar": avatar,
|
||||||
"nickname": userinfo["en_name"],
|
"nickname": user_info["en_name"],
|
||||||
"login_channel": "feishu",
|
"login_channel": "feishu",
|
||||||
"last_login_time": get_format_time(),
|
"last_login_time": get_format_time(),
|
||||||
"is_superuser": False,
|
"is_superuser": False,
|
||||||
})
|
})
|
||||||
if not users:
|
if not users:
|
||||||
raise Exception('Register user failure.')
|
raise Exception(f'Fail to register {email_address}.')
|
||||||
if len(users) > 1:
|
if len(users) > 1:
|
||||||
raise Exception('Same E-mail exist!')
|
raise Exception(f'Same email: {email_address} exists!')
|
||||||
|
|
||||||
|
# Try to log in
|
||||||
user = users[0]
|
user = users[0]
|
||||||
login_user(user)
|
login_user(user)
|
||||||
return redirect("/?auth=%s" % user.get_id())
|
return redirect("/?auth=%s" % user.get_id())
|
||||||
@ -178,6 +198,8 @@ def feishu_callback():
|
|||||||
rollback_user_registration(user_id)
|
rollback_user_registration(user_id)
|
||||||
stat_logger.exception(e)
|
stat_logger.exception(e)
|
||||||
return redirect("/?error=%s" % str(e))
|
return redirect("/?error=%s" % str(e))
|
||||||
|
|
||||||
|
# User has already registered, try to log in
|
||||||
user = users[0]
|
user = users[0]
|
||||||
user.access_token = get_uuid()
|
user.access_token = get_uuid()
|
||||||
login_user(user)
|
login_user(user)
|
||||||
@ -232,12 +254,10 @@ def setting_user():
|
|||||||
new_password = request_data.get("new_password")
|
new_password = request_data.get("new_password")
|
||||||
if not check_password_hash(
|
if not check_password_hash(
|
||||||
current_user.password, decrypt(request_data["password"])):
|
current_user.password, decrypt(request_data["password"])):
|
||||||
return get_json_result(
|
return get_json_result(data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg='Password error!')
|
||||||
data=False, retcode=RetCode.AUTHENTICATION_ERROR, retmsg='Password error!')
|
|
||||||
|
|
||||||
if new_password:
|
if new_password:
|
||||||
update_dict["password"] = generate_password_hash(
|
update_dict["password"] = generate_password_hash(decrypt(new_password))
|
||||||
decrypt(new_password))
|
|
||||||
|
|
||||||
for k in request_data.keys():
|
for k in request_data.keys():
|
||||||
if k in ["password", "new_password"]:
|
if k in ["password", "new_password"]:
|
||||||
@ -249,13 +269,12 @@ def setting_user():
|
|||||||
return get_json_result(data=True)
|
return get_json_result(data=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
stat_logger.exception(e)
|
stat_logger.exception(e)
|
||||||
return get_json_result(
|
return get_json_result(data=False, retmsg='Update failure!', retcode=RetCode.EXCEPTION_ERROR)
|
||||||
data=False, retmsg='Update failure!', retcode=RetCode.EXCEPTION_ERROR)
|
|
||||||
|
|
||||||
|
|
||||||
@manager.route("/info", methods=["GET"])
|
@manager.route("/info", methods=["GET"])
|
||||||
@login_required
|
@login_required
|
||||||
def user_info():
|
def user_profile():
|
||||||
return get_json_result(data=current_user.to_dict())
|
return get_json_result(data=current_user.to_dict())
|
||||||
|
|
||||||
|
|
||||||
@ -332,17 +351,27 @@ def user_register(user_id, user):
|
|||||||
@validate_request("nickname", "email", "password")
|
@validate_request("nickname", "email", "password")
|
||||||
def user_add():
|
def user_add():
|
||||||
req = request.json
|
req = request.json
|
||||||
if UserService.query(email=req["email"]):
|
email_address = req["email"]
|
||||||
return get_json_result(
|
|
||||||
data=False, retmsg=f'Email: {req["email"]} has already registered!', retcode=RetCode.OPERATING_ERROR)
|
# Validate the email address
|
||||||
if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", req["email"]):
|
if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", email_address):
|
||||||
return get_json_result(data=False, retmsg=f'Invaliad e-mail: {req["email"]}!',
|
return get_json_result(data=False,
|
||||||
|
retmsg=f'Invalid email address: {email_address}!',
|
||||||
retcode=RetCode.OPERATING_ERROR)
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
# Check if the email address is already used
|
||||||
|
if UserService.query(email=email_address):
|
||||||
|
return get_json_result(
|
||||||
|
data=False,
|
||||||
|
retmsg=f'Email: {email_address} has already registered!',
|
||||||
|
retcode=RetCode.OPERATING_ERROR)
|
||||||
|
|
||||||
|
# Construct user info data
|
||||||
|
nickname = req["nickname"]
|
||||||
user_dict = {
|
user_dict = {
|
||||||
"access_token": get_uuid(),
|
"access_token": get_uuid(),
|
||||||
"email": req["email"],
|
"email": email_address,
|
||||||
"nickname": req["nickname"],
|
"nickname": nickname,
|
||||||
"password": decrypt(req["password"]),
|
"password": decrypt(req["password"]),
|
||||||
"login_channel": "password",
|
"login_channel": "password",
|
||||||
"last_login_time": get_format_time(),
|
"last_login_time": get_format_time(),
|
||||||
@ -353,18 +382,20 @@ def user_add():
|
|||||||
try:
|
try:
|
||||||
users = user_register(user_id, user_dict)
|
users = user_register(user_id, user_dict)
|
||||||
if not users:
|
if not users:
|
||||||
raise Exception('Register user failure.')
|
raise Exception(f'Fail to register {email_address}.')
|
||||||
if len(users) > 1:
|
if len(users) > 1:
|
||||||
raise Exception('Same E-mail exist!')
|
raise Exception(f'Same email: {email_address} exists!')
|
||||||
user = users[0]
|
user = users[0]
|
||||||
login_user(user)
|
login_user(user)
|
||||||
return cors_reponse(data=user.to_json(),
|
return construct_response(data=user.to_json(),
|
||||||
auth=user.get_id(), retmsg="Welcome aboard!")
|
auth=user.get_id(),
|
||||||
|
retmsg=f"{nickname}, welcome aboard!")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
rollback_user_registration(user_id)
|
rollback_user_registration(user_id)
|
||||||
stat_logger.exception(e)
|
stat_logger.exception(e)
|
||||||
return get_json_result(
|
return get_json_result(data=False,
|
||||||
data=False, retmsg='User registration failure!', retcode=RetCode.EXCEPTION_ERROR)
|
retmsg=f'User registration failure, error: {str(e)}',
|
||||||
|
retcode=RetCode.EXCEPTION_ERROR)
|
||||||
|
|
||||||
|
|
||||||
@manager.route("/tenant_info", methods=["GET"])
|
@manager.route("/tenant_info", methods=["GET"])
|
||||||
|
|||||||
@ -55,6 +55,7 @@ class LLMType(StrEnum):
|
|||||||
SPEECH2TEXT = 'speech2text'
|
SPEECH2TEXT = 'speech2text'
|
||||||
IMAGE2TEXT = 'image2text'
|
IMAGE2TEXT = 'image2text'
|
||||||
RERANK = 'rerank'
|
RERANK = 'rerank'
|
||||||
|
TTS = 'tts'
|
||||||
|
|
||||||
|
|
||||||
class ChatStyle(StrEnum):
|
class ChatStyle(StrEnum):
|
||||||
@ -84,6 +85,9 @@ class ParserType(StrEnum):
|
|||||||
NAIVE = "naive"
|
NAIVE = "naive"
|
||||||
PICTURE = "picture"
|
PICTURE = "picture"
|
||||||
ONE = "one"
|
ONE = "one"
|
||||||
|
AUDIO = "audio"
|
||||||
|
EMAIL = "email"
|
||||||
|
KG = "knowledge_graph"
|
||||||
|
|
||||||
|
|
||||||
class FileSource(StrEnum):
|
class FileSource(StrEnum):
|
||||||
|
|||||||
@ -18,18 +18,19 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
import typing
|
import typing
|
||||||
import operator
|
import operator
|
||||||
|
from enum import Enum
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer
|
from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer
|
||||||
from flask_login import UserMixin
|
from flask_login import UserMixin
|
||||||
from playhouse.migrate import MySQLMigrator, migrate
|
from playhouse.migrate import MySQLMigrator, PostgresqlMigrator, migrate
|
||||||
from peewee import (
|
from peewee import (
|
||||||
BigIntegerField, BooleanField, CharField,
|
BigIntegerField, BooleanField, CharField,
|
||||||
CompositeKey, IntegerField, TextField, FloatField, DateTimeField,
|
CompositeKey, IntegerField, TextField, FloatField, DateTimeField,
|
||||||
Field, Model, Metadata
|
Field, Model, Metadata
|
||||||
)
|
)
|
||||||
from playhouse.pool import PooledMySQLDatabase
|
from playhouse.pool import PooledMySQLDatabase, PooledPostgresqlDatabase
|
||||||
from api.db import SerializedType, ParserType
|
from api.db import SerializedType, ParserType
|
||||||
from api.settings import DATABASE, stat_logger, SECRET_KEY
|
from api.settings import DATABASE, stat_logger, SECRET_KEY, DATABASE_TYPE
|
||||||
from api.utils.log_utils import getLogger
|
from api.utils.log_utils import getLogger
|
||||||
from api import utils
|
from api import utils
|
||||||
|
|
||||||
@ -58,8 +59,13 @@ AUTO_DATE_TIMESTAMP_FIELD_PREFIX = {
|
|||||||
"write_access"}
|
"write_access"}
|
||||||
|
|
||||||
|
|
||||||
|
class TextFieldType(Enum):
|
||||||
|
MYSQL = 'LONGTEXT'
|
||||||
|
POSTGRES = 'TEXT'
|
||||||
|
|
||||||
|
|
||||||
class LongTextField(TextField):
|
class LongTextField(TextField):
|
||||||
field_type = 'LONGTEXT'
|
field_type = TextFieldType[DATABASE_TYPE.upper()].value
|
||||||
|
|
||||||
|
|
||||||
class JSONField(LongTextField):
|
class JSONField(LongTextField):
|
||||||
@ -144,10 +150,10 @@ def remove_field_name_prefix(field_name):
|
|||||||
|
|
||||||
|
|
||||||
class BaseModel(Model):
|
class BaseModel(Model):
|
||||||
create_time = BigIntegerField(null=True)
|
create_time = BigIntegerField(null=True, index=True)
|
||||||
create_date = DateTimeField(null=True)
|
create_date = DateTimeField(null=True, index=True)
|
||||||
update_time = BigIntegerField(null=True)
|
update_time = BigIntegerField(null=True, index=True)
|
||||||
update_date = DateTimeField(null=True)
|
update_date = DateTimeField(null=True, index=True)
|
||||||
|
|
||||||
def to_json(self):
|
def to_json(self):
|
||||||
# This function is obsolete
|
# This function is obsolete
|
||||||
@ -234,7 +240,7 @@ class BaseModel(Model):
|
|||||||
def insert(cls, __data=None, **insert):
|
def insert(cls, __data=None, **insert):
|
||||||
if isinstance(__data, dict) and __data:
|
if isinstance(__data, dict) and __data:
|
||||||
__data[cls._meta.combined["create_time"]
|
__data[cls._meta.combined["create_time"]
|
||||||
] = utils.current_timestamp()
|
] = utils.current_timestamp()
|
||||||
if insert:
|
if insert:
|
||||||
insert["create_time"] = utils.current_timestamp()
|
insert["create_time"] = utils.current_timestamp()
|
||||||
|
|
||||||
@ -248,7 +254,7 @@ class BaseModel(Model):
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
normalized[cls._meta.combined["update_time"]
|
normalized[cls._meta.combined["update_time"]
|
||||||
] = utils.current_timestamp()
|
] = utils.current_timestamp()
|
||||||
|
|
||||||
for f_n in AUTO_DATE_TIMESTAMP_FIELD_PREFIX:
|
for f_n in AUTO_DATE_TIMESTAMP_FIELD_PREFIX:
|
||||||
if {f"{f_n}_time", f"{f_n}_date"}.issubset(cls._meta.combined.keys()) and \
|
if {f"{f_n}_time", f"{f_n}_date"}.issubset(cls._meta.combined.keys()) and \
|
||||||
@ -266,18 +272,69 @@ class JsonSerializedField(SerializedField):
|
|||||||
super(JsonSerializedField, self).__init__(serialized_type=SerializedType.JSON, object_hook=object_hook,
|
super(JsonSerializedField, self).__init__(serialized_type=SerializedType.JSON, object_hook=object_hook,
|
||||||
object_pairs_hook=object_pairs_hook, **kwargs)
|
object_pairs_hook=object_pairs_hook, **kwargs)
|
||||||
|
|
||||||
|
class PooledDatabase(Enum):
|
||||||
|
MYSQL = PooledMySQLDatabase
|
||||||
|
POSTGRES = PooledPostgresqlDatabase
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseMigrator(Enum):
|
||||||
|
MYSQL = MySQLMigrator
|
||||||
|
POSTGRES = PostgresqlMigrator
|
||||||
|
|
||||||
|
|
||||||
@singleton
|
@singleton
|
||||||
class BaseDataBase:
|
class BaseDataBase:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
database_config = DATABASE.copy()
|
database_config = DATABASE.copy()
|
||||||
db_name = database_config.pop("name")
|
db_name = database_config.pop("name")
|
||||||
self.database_connection = PooledMySQLDatabase(
|
self.database_connection = PooledDatabase[DATABASE_TYPE.upper()].value(db_name, **database_config)
|
||||||
db_name, **database_config)
|
stat_logger.info('init database on cluster mode successfully')
|
||||||
stat_logger.info('init mysql database on cluster mode successfully')
|
|
||||||
|
|
||||||
|
class PostgresDatabaseLock:
|
||||||
|
def __init__(self, lock_name, timeout=10, db=None):
|
||||||
|
self.lock_name = lock_name
|
||||||
|
self.timeout = int(timeout)
|
||||||
|
self.db = db if db else DB
|
||||||
|
|
||||||
class DatabaseLock:
|
def lock(self):
|
||||||
|
cursor = self.db.execute_sql("SELECT pg_try_advisory_lock(%s)", self.timeout)
|
||||||
|
ret = cursor.fetchone()
|
||||||
|
if ret[0] == 0:
|
||||||
|
raise Exception(f'acquire postgres lock {self.lock_name} timeout')
|
||||||
|
elif ret[0] == 1:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
raise Exception(f'failed to acquire lock {self.lock_name}')
|
||||||
|
|
||||||
|
def unlock(self):
|
||||||
|
cursor = self.db.execute_sql("SELECT pg_advisory_unlock(%s)", self.timeout)
|
||||||
|
ret = cursor.fetchone()
|
||||||
|
if ret[0] == 0:
|
||||||
|
raise Exception(
|
||||||
|
f'postgres lock {self.lock_name} was not established by this thread')
|
||||||
|
elif ret[0] == 1:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
raise Exception(f'postgres lock {self.lock_name} does not exist')
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
if isinstance(self.db, PostgresDatabaseLock):
|
||||||
|
self.lock()
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
if isinstance(self.db, PostgresDatabaseLock):
|
||||||
|
self.unlock()
|
||||||
|
|
||||||
|
def __call__(self, func):
|
||||||
|
@wraps(func)
|
||||||
|
def magic(*args, **kwargs):
|
||||||
|
with self:
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
|
||||||
|
return magic
|
||||||
|
|
||||||
|
class MysqlDatabaseLock:
|
||||||
def __init__(self, lock_name, timeout=10, db=None):
|
def __init__(self, lock_name, timeout=10, db=None):
|
||||||
self.lock_name = lock_name
|
self.lock_name = lock_name
|
||||||
self.timeout = int(timeout)
|
self.timeout = int(timeout)
|
||||||
@ -325,14 +382,19 @@ class DatabaseLock:
|
|||||||
return magic
|
return magic
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseLock(Enum):
|
||||||
|
MYSQL = MysqlDatabaseLock
|
||||||
|
POSTGRES = PostgresDatabaseLock
|
||||||
|
|
||||||
|
|
||||||
DB = BaseDataBase().database_connection
|
DB = BaseDataBase().database_connection
|
||||||
DB.lock = DatabaseLock
|
DB.lock = DatabaseLock[DATABASE_TYPE.upper()].value
|
||||||
|
|
||||||
|
|
||||||
def close_connection():
|
def close_connection():
|
||||||
try:
|
try:
|
||||||
if DB:
|
if DB:
|
||||||
DB.close()
|
DB.close_stale(age=30)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
LOGGER.exception(e)
|
LOGGER.exception(e)
|
||||||
|
|
||||||
@ -373,9 +435,9 @@ def fill_db_model_object(model_object, human_model_dict):
|
|||||||
|
|
||||||
class User(DataBaseModel, UserMixin):
|
class User(DataBaseModel, UserMixin):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
access_token = CharField(max_length=255, null=True)
|
access_token = CharField(max_length=255, null=True, index=True)
|
||||||
nickname = CharField(max_length=100, null=False, help_text="nicky name")
|
nickname = CharField(max_length=100, null=False, help_text="nicky name", index=True)
|
||||||
password = CharField(max_length=255, null=True, help_text="password")
|
password = CharField(max_length=255, null=True, help_text="password", index=True)
|
||||||
email = CharField(
|
email = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=False,
|
null=False,
|
||||||
@ -386,28 +448,32 @@ class User(DataBaseModel, UserMixin):
|
|||||||
max_length=32,
|
max_length=32,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="English|Chinese",
|
help_text="English|Chinese",
|
||||||
default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English")
|
default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
|
||||||
|
index=True)
|
||||||
color_schema = CharField(
|
color_schema = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="Bright|Dark",
|
help_text="Bright|Dark",
|
||||||
default="Bright")
|
default="Bright",
|
||||||
|
index=True)
|
||||||
timezone = CharField(
|
timezone = CharField(
|
||||||
max_length=64,
|
max_length=64,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="Timezone",
|
help_text="Timezone",
|
||||||
default="UTC+8\tAsia/Shanghai")
|
default="UTC+8\tAsia/Shanghai",
|
||||||
last_login_time = DateTimeField(null=True)
|
index=True)
|
||||||
is_authenticated = CharField(max_length=1, null=False, default="1")
|
last_login_time = DateTimeField(null=True, index=True)
|
||||||
is_active = CharField(max_length=1, null=False, default="1")
|
is_authenticated = CharField(max_length=1, null=False, default="1", index=True)
|
||||||
is_anonymous = CharField(max_length=1, null=False, default="0")
|
is_active = CharField(max_length=1, null=False, default="1", index=True)
|
||||||
login_channel = CharField(null=True, help_text="from which user login")
|
is_anonymous = CharField(max_length=1, null=False, default="0", index=True)
|
||||||
|
login_channel = CharField(null=True, help_text="from which user login", index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
is_superuser = BooleanField(null=True, help_text="is root", default=False)
|
index=True)
|
||||||
|
is_superuser = BooleanField(null=True, help_text="is root", default=False, index=True)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.email
|
return self.email
|
||||||
@ -422,35 +488,46 @@ class User(DataBaseModel, UserMixin):
|
|||||||
|
|
||||||
class Tenant(DataBaseModel):
|
class Tenant(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
name = CharField(max_length=100, null=True, help_text="Tenant name")
|
name = CharField(max_length=100, null=True, help_text="Tenant name", index=True)
|
||||||
public_key = CharField(max_length=255, null=True)
|
public_key = CharField(max_length=255, null=True, index=True)
|
||||||
llm_id = CharField(max_length=128, null=False, help_text="default llm ID")
|
llm_id = CharField(max_length=128, null=False, help_text="default llm ID", index=True)
|
||||||
embd_id = CharField(
|
embd_id = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default embedding model ID")
|
help_text="default embedding model ID",
|
||||||
|
index=True)
|
||||||
asr_id = CharField(
|
asr_id = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default ASR model ID")
|
help_text="default ASR model ID",
|
||||||
|
index=True)
|
||||||
img2txt_id = CharField(
|
img2txt_id = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default image to text model ID")
|
help_text="default image to text model ID",
|
||||||
|
index=True)
|
||||||
rerank_id = CharField(
|
rerank_id = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default rerank model ID")
|
help_text="default rerank model ID",
|
||||||
|
index=True)
|
||||||
|
tts_id = CharField(
|
||||||
|
max_length=256,
|
||||||
|
null=True,
|
||||||
|
help_text="default tts model ID",
|
||||||
|
index=True)
|
||||||
parser_ids = CharField(
|
parser_ids = CharField(
|
||||||
max_length=256,
|
max_length=256,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="document processors")
|
help_text="document processors",
|
||||||
credit = IntegerField(default=512)
|
index=True)
|
||||||
|
credit = IntegerField(default=512, index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "tenant"
|
db_table = "tenant"
|
||||||
@ -458,15 +535,16 @@ class Tenant(DataBaseModel):
|
|||||||
|
|
||||||
class UserTenant(DataBaseModel):
|
class UserTenant(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
user_id = CharField(max_length=32, null=False)
|
user_id = CharField(max_length=32, null=False, index=True)
|
||||||
tenant_id = CharField(max_length=32, null=False)
|
tenant_id = CharField(max_length=32, null=False, index=True)
|
||||||
role = CharField(max_length=32, null=False, help_text="UserTenantRole")
|
role = CharField(max_length=32, null=False, help_text="UserTenantRole", index=True)
|
||||||
invited_by = CharField(max_length=32, null=False)
|
invited_by = CharField(max_length=32, null=False, index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "user_tenant"
|
db_table = "user_tenant"
|
||||||
@ -474,15 +552,16 @@ class UserTenant(DataBaseModel):
|
|||||||
|
|
||||||
class InvitationCode(DataBaseModel):
|
class InvitationCode(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
code = CharField(max_length=32, null=False)
|
code = CharField(max_length=32, null=False, index=True)
|
||||||
visit_time = DateTimeField(null=True)
|
visit_time = DateTimeField(null=True, index=True)
|
||||||
user_id = CharField(max_length=32, null=True)
|
user_id = CharField(max_length=32, null=True, index=True)
|
||||||
tenant_id = CharField(max_length=32, null=True)
|
tenant_id = CharField(max_length=32, null=True, index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "invitation_code"
|
db_table = "invitation_code"
|
||||||
@ -498,12 +577,14 @@ class LLMFactories(DataBaseModel):
|
|||||||
tags = CharField(
|
tags = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="LLM, Text Embedding, Image2Text, ASR")
|
help_text="LLM, Text Embedding, Image2Text, ASR",
|
||||||
|
index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
@ -518,49 +599,57 @@ class LLM(DataBaseModel):
|
|||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="LLM name",
|
help_text="LLM name",
|
||||||
index=True,
|
index=True)
|
||||||
primary_key=True)
|
|
||||||
model_type = CharField(
|
model_type = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="LLM, Text Embedding, Image2Text, ASR")
|
help_text="LLM, Text Embedding, Image2Text, ASR",
|
||||||
fid = CharField(max_length=128, null=False, help_text="LLM factory id")
|
index=True)
|
||||||
|
fid = CharField(max_length=128, null=False, help_text="LLM factory id", index=True)
|
||||||
max_tokens = IntegerField(default=0)
|
max_tokens = IntegerField(default=0)
|
||||||
|
|
||||||
tags = CharField(
|
tags = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="LLM, Text Embedding, Image2Text, Chat, 32k...")
|
help_text="LLM, Text Embedding, Image2Text, Chat, 32k...",
|
||||||
|
index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.llm_name
|
return self.llm_name
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
|
primary_key = CompositeKey('fid', 'llm_name')
|
||||||
db_table = "llm"
|
db_table = "llm"
|
||||||
|
|
||||||
|
|
||||||
class TenantLLM(DataBaseModel):
|
class TenantLLM(DataBaseModel):
|
||||||
tenant_id = CharField(max_length=32, null=False)
|
tenant_id = CharField(max_length=32, null=False, index=True)
|
||||||
llm_factory = CharField(
|
llm_factory = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="LLM factory name")
|
help_text="LLM factory name",
|
||||||
|
index=True)
|
||||||
model_type = CharField(
|
model_type = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="LLM, Text Embedding, Image2Text, ASR")
|
help_text="LLM, Text Embedding, Image2Text, ASR",
|
||||||
|
index=True)
|
||||||
llm_name = CharField(
|
llm_name = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="LLM name",
|
help_text="LLM name",
|
||||||
default="")
|
default="",
|
||||||
api_key = CharField(max_length=255, null=True, help_text="API KEY")
|
index=True)
|
||||||
|
api_key = CharField(max_length=1024, null=True, help_text="API KEY", index=True)
|
||||||
api_base = CharField(max_length=255, null=True, help_text="API Base")
|
api_base = CharField(max_length=255, null=True, help_text="API Base")
|
||||||
used_tokens = IntegerField(default=0)
|
|
||||||
|
used_tokens = IntegerField(default=0, index=True)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.llm_name
|
return self.llm_name
|
||||||
@ -573,7 +662,7 @@ class TenantLLM(DataBaseModel):
|
|||||||
class Knowledgebase(DataBaseModel):
|
class Knowledgebase(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
avatar = TextField(null=True, help_text="avatar base64 string")
|
avatar = TextField(null=True, help_text="avatar base64 string")
|
||||||
tenant_id = CharField(max_length=32, null=False)
|
tenant_id = CharField(max_length=32, null=False, index=True)
|
||||||
name = CharField(
|
name = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
@ -583,35 +672,40 @@ class Knowledgebase(DataBaseModel):
|
|||||||
max_length=32,
|
max_length=32,
|
||||||
null=True,
|
null=True,
|
||||||
default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
|
default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
|
||||||
help_text="English|Chinese")
|
help_text="English|Chinese",
|
||||||
|
index=True)
|
||||||
description = TextField(null=True, help_text="KB description")
|
description = TextField(null=True, help_text="KB description")
|
||||||
embd_id = CharField(
|
embd_id = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default embedding model ID")
|
help_text="default embedding model ID",
|
||||||
|
index=True)
|
||||||
permission = CharField(
|
permission = CharField(
|
||||||
max_length=16,
|
max_length=16,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="me|team",
|
help_text="me|team",
|
||||||
default="me")
|
default="me",
|
||||||
created_by = CharField(max_length=32, null=False)
|
index=True)
|
||||||
doc_num = IntegerField(default=0)
|
created_by = CharField(max_length=32, null=False, index=True)
|
||||||
token_num = IntegerField(default=0)
|
doc_num = IntegerField(default=0, index=True)
|
||||||
chunk_num = IntegerField(default=0)
|
token_num = IntegerField(default=0, index=True)
|
||||||
similarity_threshold = FloatField(default=0.2)
|
chunk_num = IntegerField(default=0, index=True)
|
||||||
vector_similarity_weight = FloatField(default=0.3)
|
similarity_threshold = FloatField(default=0.2, index=True)
|
||||||
|
vector_similarity_weight = FloatField(default=0.3, index=True)
|
||||||
|
|
||||||
parser_id = CharField(
|
parser_id = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default parser ID",
|
help_text="default parser ID",
|
||||||
default=ParserType.NAIVE.value)
|
default=ParserType.NAIVE.value,
|
||||||
|
index=True)
|
||||||
parser_config = JSONField(null=False, default={"pages": [[1, 1000000]]})
|
parser_config = JSONField(null=False, default={"pages": [[1, 1000000]]})
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.name
|
return self.name
|
||||||
@ -627,18 +721,22 @@ class Document(DataBaseModel):
|
|||||||
parser_id = CharField(
|
parser_id = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="default parser ID")
|
help_text="default parser ID",
|
||||||
|
index=True)
|
||||||
parser_config = JSONField(null=False, default={"pages": [[1, 1000000]]})
|
parser_config = JSONField(null=False, default={"pages": [[1, 1000000]]})
|
||||||
source_type = CharField(
|
source_type = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
default="local",
|
default="local",
|
||||||
help_text="where dose this document come from")
|
help_text="where dose this document come from",
|
||||||
type = CharField(max_length=32, null=False, help_text="file extension")
|
index=True)
|
||||||
|
type = CharField(max_length=32, null=False, help_text="file extension",
|
||||||
|
index=True)
|
||||||
created_by = CharField(
|
created_by = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="who created it")
|
help_text="who created it",
|
||||||
|
index=True)
|
||||||
name = CharField(
|
name = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=True,
|
null=True,
|
||||||
@ -647,27 +745,31 @@ class Document(DataBaseModel):
|
|||||||
location = CharField(
|
location = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="where dose it store")
|
help_text="where dose it store",
|
||||||
size = IntegerField(default=0)
|
index=True)
|
||||||
token_num = IntegerField(default=0)
|
size = IntegerField(default=0, index=True)
|
||||||
chunk_num = IntegerField(default=0)
|
token_num = IntegerField(default=0, index=True)
|
||||||
progress = FloatField(default=0)
|
chunk_num = IntegerField(default=0, index=True)
|
||||||
|
progress = FloatField(default=0, index=True)
|
||||||
progress_msg = TextField(
|
progress_msg = TextField(
|
||||||
null=True,
|
null=True,
|
||||||
help_text="process message",
|
help_text="process message",
|
||||||
default="")
|
default="")
|
||||||
process_begin_at = DateTimeField(null=True)
|
process_begin_at = DateTimeField(null=True, index=True)
|
||||||
process_duation = FloatField(default=0)
|
process_duation = FloatField(default=0)
|
||||||
|
|
||||||
run = CharField(
|
run = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="start to run processing or cancel.(1: run it; 2: cancel)",
|
help_text="start to run processing or cancel.(1: run it; 2: cancel)",
|
||||||
default="0")
|
default="0",
|
||||||
|
index=True)
|
||||||
status = CharField(
|
status = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "document"
|
db_table = "document"
|
||||||
@ -676,8 +778,7 @@ class Document(DataBaseModel):
|
|||||||
class File(DataBaseModel):
|
class File(DataBaseModel):
|
||||||
id = CharField(
|
id = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
primary_key=True,
|
primary_key=True)
|
||||||
)
|
|
||||||
parent_id = CharField(
|
parent_id = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=False,
|
null=False,
|
||||||
@ -691,7 +792,8 @@ class File(DataBaseModel):
|
|||||||
created_by = CharField(
|
created_by = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="who created it")
|
help_text="who created it",
|
||||||
|
index=True)
|
||||||
name = CharField(
|
name = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=False,
|
null=False,
|
||||||
@ -700,14 +802,15 @@ class File(DataBaseModel):
|
|||||||
location = CharField(
|
location = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="where dose it store")
|
help_text="where dose it store",
|
||||||
size = IntegerField(default=0)
|
index=True)
|
||||||
type = CharField(max_length=32, null=False, help_text="file extension")
|
size = IntegerField(default=0, index=True)
|
||||||
|
type = CharField(max_length=32, null=False, help_text="file extension", index=True)
|
||||||
source_type = CharField(
|
source_type = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
default="",
|
default="",
|
||||||
help_text="where dose this document come from")
|
help_text="where dose this document come from", index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "file"
|
db_table = "file"
|
||||||
@ -716,8 +819,7 @@ class File(DataBaseModel):
|
|||||||
class File2Document(DataBaseModel):
|
class File2Document(DataBaseModel):
|
||||||
id = CharField(
|
id = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
primary_key=True,
|
primary_key=True)
|
||||||
)
|
|
||||||
file_id = CharField(
|
file_id = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=True,
|
null=True,
|
||||||
@ -737,50 +839,62 @@ class Task(DataBaseModel):
|
|||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
doc_id = CharField(max_length=32, null=False, index=True)
|
doc_id = CharField(max_length=32, null=False, index=True)
|
||||||
from_page = IntegerField(default=0)
|
from_page = IntegerField(default=0)
|
||||||
|
|
||||||
to_page = IntegerField(default=-1)
|
to_page = IntegerField(default=-1)
|
||||||
begin_at = DateTimeField(null=True)
|
|
||||||
|
begin_at = DateTimeField(null=True, index=True)
|
||||||
process_duation = FloatField(default=0)
|
process_duation = FloatField(default=0)
|
||||||
progress = FloatField(default=0)
|
|
||||||
|
progress = FloatField(default=0, index=True)
|
||||||
progress_msg = TextField(
|
progress_msg = TextField(
|
||||||
null=True,
|
null=True,
|
||||||
help_text="process message",
|
help_text="process message",
|
||||||
default="")
|
default="")
|
||||||
|
retry_count = IntegerField(default=0)
|
||||||
|
|
||||||
|
|
||||||
class Dialog(DataBaseModel):
|
class Dialog(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
tenant_id = CharField(max_length=32, null=False)
|
tenant_id = CharField(max_length=32, null=False, index=True)
|
||||||
name = CharField(
|
name = CharField(
|
||||||
max_length=255,
|
max_length=255,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="dialog application name")
|
help_text="dialog application name",
|
||||||
|
index=True)
|
||||||
description = TextField(null=True, help_text="Dialog description")
|
description = TextField(null=True, help_text="Dialog description")
|
||||||
icon = TextField(null=True, help_text="icon base64 string")
|
icon = TextField(null=True, help_text="icon base64 string")
|
||||||
language = CharField(
|
language = CharField(
|
||||||
max_length=32,
|
max_length=32,
|
||||||
null=True,
|
null=True,
|
||||||
default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
|
default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
|
||||||
help_text="English|Chinese")
|
help_text="English|Chinese",
|
||||||
|
index=True)
|
||||||
llm_id = CharField(max_length=128, null=False, help_text="default llm ID")
|
llm_id = CharField(max_length=128, null=False, help_text="default llm ID")
|
||||||
|
|
||||||
llm_setting = JSONField(null=False, default={"temperature": 0.1, "top_p": 0.3, "frequency_penalty": 0.7,
|
llm_setting = JSONField(null=False, default={"temperature": 0.1, "top_p": 0.3, "frequency_penalty": 0.7,
|
||||||
"presence_penalty": 0.4, "max_tokens": 512})
|
"presence_penalty": 0.4, "max_tokens": 512})
|
||||||
prompt_type = CharField(
|
prompt_type = CharField(
|
||||||
max_length=16,
|
max_length=16,
|
||||||
null=False,
|
null=False,
|
||||||
default="simple",
|
default="simple",
|
||||||
help_text="simple|advanced")
|
help_text="simple|advanced",
|
||||||
|
index=True)
|
||||||
prompt_config = JSONField(null=False, default={"system": "", "prologue": "您好,我是您的助手小樱,长得可爱又善良,can I help you?",
|
prompt_config = JSONField(null=False, default={"system": "", "prologue": "您好,我是您的助手小樱,长得可爱又善良,can I help you?",
|
||||||
"parameters": [], "empty_response": "Sorry! 知识库中未找到相关内容!"})
|
"parameters": [], "empty_response": "Sorry! 知识库中未找到相关内容!"})
|
||||||
|
|
||||||
similarity_threshold = FloatField(default=0.2)
|
similarity_threshold = FloatField(default=0.2)
|
||||||
vector_similarity_weight = FloatField(default=0.3)
|
vector_similarity_weight = FloatField(default=0.3)
|
||||||
|
|
||||||
top_n = IntegerField(default=6)
|
top_n = IntegerField(default=6)
|
||||||
|
|
||||||
top_k = IntegerField(default=1024)
|
top_k = IntegerField(default=1024)
|
||||||
|
|
||||||
do_refer = CharField(
|
do_refer = CharField(
|
||||||
max_length=1,
|
max_length=1,
|
||||||
null=False,
|
null=False,
|
||||||
help_text="it needs to insert reference index into answer or not",
|
default="1",
|
||||||
default="1")
|
help_text="it needs to insert reference index into answer or not")
|
||||||
|
|
||||||
rerank_id = CharField(
|
rerank_id = CharField(
|
||||||
max_length=128,
|
max_length=128,
|
||||||
null=False,
|
null=False,
|
||||||
@ -791,7 +905,8 @@ class Dialog(DataBaseModel):
|
|||||||
max_length=1,
|
max_length=1,
|
||||||
null=True,
|
null=True,
|
||||||
help_text="is it validate(0: wasted,1: validate)",
|
help_text="is it validate(0: wasted,1: validate)",
|
||||||
default="1")
|
default="1",
|
||||||
|
index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "dialog"
|
db_table = "dialog"
|
||||||
@ -800,7 +915,7 @@ class Dialog(DataBaseModel):
|
|||||||
class Conversation(DataBaseModel):
|
class Conversation(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
dialog_id = CharField(max_length=32, null=False, index=True)
|
dialog_id = CharField(max_length=32, null=False, index=True)
|
||||||
name = CharField(max_length=255, null=True, help_text="converastion name")
|
name = CharField(max_length=255, null=True, help_text="converastion name", index=True)
|
||||||
message = JSONField(null=True)
|
message = JSONField(null=True)
|
||||||
reference = JSONField(null=True, default=[])
|
reference = JSONField(null=True, default=[])
|
||||||
|
|
||||||
@ -809,9 +924,10 @@ class Conversation(DataBaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class APIToken(DataBaseModel):
|
class APIToken(DataBaseModel):
|
||||||
tenant_id = CharField(max_length=32, null=False)
|
tenant_id = CharField(max_length=32, null=False, index=True)
|
||||||
token = CharField(max_length=255, null=False)
|
token = CharField(max_length=255, null=False, index=True)
|
||||||
dialog_id = CharField(max_length=32, null=False, index=True)
|
dialog_id = CharField(max_length=32, null=False, index=True)
|
||||||
|
source = CharField(max_length=16, null=True, help_text="none|agent|dialog", index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "api_token"
|
db_table = "api_token"
|
||||||
@ -821,13 +937,15 @@ class APIToken(DataBaseModel):
|
|||||||
class API4Conversation(DataBaseModel):
|
class API4Conversation(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
dialog_id = CharField(max_length=32, null=False, index=True)
|
dialog_id = CharField(max_length=32, null=False, index=True)
|
||||||
user_id = CharField(max_length=255, null=False, help_text="user_id")
|
user_id = CharField(max_length=255, null=False, help_text="user_id", index=True)
|
||||||
message = JSONField(null=True)
|
message = JSONField(null=True)
|
||||||
reference = JSONField(null=True, default=[])
|
reference = JSONField(null=True, default=[])
|
||||||
tokens = IntegerField(default=0)
|
tokens = IntegerField(default=0)
|
||||||
duration = FloatField(default=0)
|
source = CharField(max_length=16, null=True, help_text="none|agent|dialog", index=True)
|
||||||
round = IntegerField(default=0)
|
|
||||||
thumb_up = IntegerField(default=0)
|
duration = FloatField(default=0, index=True)
|
||||||
|
round = IntegerField(default=0, index=True)
|
||||||
|
thumb_up = IntegerField(default=0, index=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "api_4_conversation"
|
db_table = "api_4_conversation"
|
||||||
@ -836,10 +954,11 @@ class API4Conversation(DataBaseModel):
|
|||||||
class UserCanvas(DataBaseModel):
|
class UserCanvas(DataBaseModel):
|
||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
avatar = TextField(null=True, help_text="avatar base64 string")
|
avatar = TextField(null=True, help_text="avatar base64 string")
|
||||||
user_id = CharField(max_length=255, null=False, help_text="user_id")
|
user_id = CharField(max_length=255, null=False, help_text="user_id", index=True)
|
||||||
title = CharField(max_length=255, null=True, help_text="Canvas title")
|
title = CharField(max_length=255, null=True, help_text="Canvas title")
|
||||||
|
|
||||||
description = TextField(null=True, help_text="Canvas description")
|
description = TextField(null=True, help_text="Canvas description")
|
||||||
canvas_type = CharField(max_length=32, null=True, help_text="Canvas type")
|
canvas_type = CharField(max_length=32, null=True, help_text="Canvas type", index=True)
|
||||||
dsl = JSONField(null=True, default={})
|
dsl = JSONField(null=True, default={})
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
@ -850,8 +969,9 @@ class CanvasTemplate(DataBaseModel):
|
|||||||
id = CharField(max_length=32, primary_key=True)
|
id = CharField(max_length=32, primary_key=True)
|
||||||
avatar = TextField(null=True, help_text="avatar base64 string")
|
avatar = TextField(null=True, help_text="avatar base64 string")
|
||||||
title = CharField(max_length=255, null=True, help_text="Canvas title")
|
title = CharField(max_length=255, null=True, help_text="Canvas title")
|
||||||
|
|
||||||
description = TextField(null=True, help_text="Canvas description")
|
description = TextField(null=True, help_text="Canvas description")
|
||||||
canvas_type = CharField(max_length=32, null=True, help_text="Canvas type")
|
canvas_type = CharField(max_length=32, null=True, help_text="Canvas type", index=True)
|
||||||
dsl = JSONField(null=True, default={})
|
dsl = JSONField(null=True, default={})
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
@ -859,29 +979,77 @@ class CanvasTemplate(DataBaseModel):
|
|||||||
|
|
||||||
|
|
||||||
def migrate_db():
|
def migrate_db():
|
||||||
with DB.transaction():
|
with DB.transaction():
|
||||||
migrator = MySQLMigrator(DB)
|
migrator = DatabaseMigrator[DATABASE_TYPE.upper()].value(DB)
|
||||||
try:
|
try:
|
||||||
migrate(
|
migrate(
|
||||||
migrator.add_column('file', 'source_type', CharField(max_length=128, null=False, default="", help_text="where dose this document come from"))
|
migrator.add_column('file', 'source_type', CharField(max_length=128, null=False, default="",
|
||||||
)
|
help_text="where dose this document come from",
|
||||||
except Exception as e:
|
index=True))
|
||||||
pass
|
)
|
||||||
try:
|
except Exception as e:
|
||||||
migrate(
|
pass
|
||||||
migrator.add_column('tenant', 'rerank_id', CharField(max_length=128, null=False, default="BAAI/bge-reranker-v2-m3", help_text="default rerank model ID"))
|
try:
|
||||||
)
|
migrate(
|
||||||
except Exception as e:
|
migrator.add_column('tenant', 'rerank_id',
|
||||||
pass
|
CharField(max_length=128, null=False, default="BAAI/bge-reranker-v2-m3",
|
||||||
try:
|
help_text="default rerank model ID"))
|
||||||
migrate(
|
|
||||||
migrator.add_column('dialog', 'rerank_id', CharField(max_length=128, null=False, default="", help_text="default rerank model ID"))
|
)
|
||||||
)
|
except Exception as e:
|
||||||
except Exception as e:
|
pass
|
||||||
pass
|
try:
|
||||||
try:
|
migrate(
|
||||||
migrate(
|
migrator.add_column('dialog', 'rerank_id', CharField(max_length=128, null=False, default="",
|
||||||
migrator.add_column('dialog', 'top_k', IntegerField(default=1024))
|
help_text="default rerank model ID"))
|
||||||
)
|
|
||||||
except Exception as e:
|
)
|
||||||
pass
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
migrate(
|
||||||
|
migrator.add_column('dialog', 'top_k', IntegerField(default=1024))
|
||||||
|
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
migrate(
|
||||||
|
migrator.alter_column_type('tenant_llm', 'api_key',
|
||||||
|
CharField(max_length=1024, null=True, help_text="API KEY", index=True))
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
migrate(
|
||||||
|
migrator.add_column('api_token', 'source',
|
||||||
|
CharField(max_length=16, null=True, help_text="none|agent|dialog", index=True))
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
migrate(
|
||||||
|
migrator.add_column("tenant","tts_id",
|
||||||
|
CharField(max_length=256,null=True,help_text="default tts model ID",index=True))
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
migrate(
|
||||||
|
migrator.add_column('api_4_conversation', 'source',
|
||||||
|
CharField(max_length=16, null=True, help_text="none|agent|dialog", index=True))
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
DB.execute_sql('ALTER TABLE llm DROP PRIMARY KEY;')
|
||||||
|
DB.execute_sql('ALTER TABLE llm ADD PRIMARY KEY (llm_name,fid);')
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
migrate(
|
||||||
|
migrator.add_column('task', 'retry_count', IntegerField(default=0))
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|||||||
@ -17,6 +17,8 @@ import operator
|
|||||||
from functools import reduce
|
from functools import reduce
|
||||||
from typing import Dict, Type, Union
|
from typing import Dict, Type, Union
|
||||||
|
|
||||||
|
from playhouse.pool import PooledMySQLDatabase
|
||||||
|
|
||||||
from api.utils import current_timestamp, timestamp_to_date
|
from api.utils import current_timestamp, timestamp_to_date
|
||||||
|
|
||||||
from api.db.db_models import DB, DataBaseModel
|
from api.db.db_models import DB, DataBaseModel
|
||||||
@ -49,7 +51,10 @@ def bulk_insert_into_db(model, data_source, replace_on_conflict=False):
|
|||||||
with DB.atomic():
|
with DB.atomic():
|
||||||
query = model.insert_many(data_source[i:i + batch_size])
|
query = model.insert_many(data_source[i:i + batch_size])
|
||||||
if replace_on_conflict:
|
if replace_on_conflict:
|
||||||
query = query.on_conflict(preserve=preserve)
|
if isinstance(DB, PooledMySQLDatabase):
|
||||||
|
query = query.on_conflict(preserve=preserve)
|
||||||
|
else:
|
||||||
|
query = query.on_conflict(conflict_target="id", preserve=preserve)
|
||||||
query.execute()
|
query.execute()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -13,6 +13,7 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
|
import base64
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
@ -31,10 +32,15 @@ from api.settings import CHAT_MDL, EMBEDDING_MDL, ASR_MDL, IMAGE2TEXT_MDL, PARSE
|
|||||||
from api.utils.file_utils import get_project_base_directory
|
from api.utils.file_utils import get_project_base_directory
|
||||||
|
|
||||||
|
|
||||||
|
def encode_to_base64(input_string):
|
||||||
|
base64_encoded = base64.b64encode(input_string.encode('utf-8'))
|
||||||
|
return base64_encoded.decode('utf-8')
|
||||||
|
|
||||||
|
|
||||||
def init_superuser():
|
def init_superuser():
|
||||||
user_info = {
|
user_info = {
|
||||||
"id": uuid.uuid1().hex,
|
"id": uuid.uuid1().hex,
|
||||||
"password": "admin",
|
"password": encode_to_base64("admin"),
|
||||||
"nickname": "admin",
|
"nickname": "admin",
|
||||||
"is_superuser": True,
|
"is_superuser": True,
|
||||||
"email": "admin@ragflow.io",
|
"email": "admin@ragflow.io",
|
||||||
@ -89,835 +95,42 @@ def init_superuser():
|
|||||||
tenant["embd_id"]))
|
tenant["embd_id"]))
|
||||||
|
|
||||||
|
|
||||||
factory_infos = [{
|
|
||||||
"name": "OpenAI",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
}, {
|
|
||||||
"name": "Tongyi-Qianwen",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
}, {
|
|
||||||
"name": "ZHIPU-AI",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Ollama",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
}, {
|
|
||||||
"name": "Moonshot",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
}, {
|
|
||||||
"name": "FastEmbed",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
}, {
|
|
||||||
"name": "Xinference",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "Youdao",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "DeepSeek",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "VolcEngine",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM, TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "BaiChuan",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "Jina",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "TEXT EMBEDDING, TEXT RE-RANK",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "BAAI",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "TEXT EMBEDDING, TEXT RE-RANK",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "MiniMax",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "Mistral",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "Azure-OpenAI",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
"status": "1",
|
|
||||||
},{
|
|
||||||
"name": "Bedrock",
|
|
||||||
"logo": "",
|
|
||||||
"tags": "LLM,TEXT EMBEDDING",
|
|
||||||
"status": "1",
|
|
||||||
}
|
|
||||||
# {
|
|
||||||
# "name": "文心一言",
|
|
||||||
# "logo": "",
|
|
||||||
# "tags": "LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION",
|
|
||||||
# "status": "1",
|
|
||||||
# },
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def init_llm_factory():
|
def init_llm_factory():
|
||||||
llm_infos = [
|
try:
|
||||||
# ---------------------- OpenAI ------------------------
|
LLMService.filter_delete([(LLM.fid == "MiniMax" or LLM.fid == "Minimax")])
|
||||||
{
|
except Exception as e:
|
||||||
"fid": factory_infos[0]["name"],
|
pass
|
||||||
"llm_name": "gpt-4o",
|
|
||||||
"tags": "LLM,CHAT,128K",
|
factory_llm_infos = json.load(
|
||||||
"max_tokens": 128000,
|
open(
|
||||||
"model_type": LLMType.CHAT.value + "," + LLMType.IMAGE2TEXT.value
|
os.path.join(get_project_base_directory(), "conf", "llm_factories.json"),
|
||||||
}, {
|
"r",
|
||||||
"fid": factory_infos[0]["name"],
|
)
|
||||||
"llm_name": "gpt-3.5-turbo",
|
)
|
||||||
"tags": "LLM,CHAT,4K",
|
for factory_llm_info in factory_llm_infos["factory_llm_infos"]:
|
||||||
"max_tokens": 4096,
|
llm_infos = factory_llm_info.pop("llm")
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "gpt-3.5-turbo-16k-0613",
|
|
||||||
"tags": "LLM,CHAT,16k",
|
|
||||||
"max_tokens": 16385,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "text-embedding-ada-002",
|
|
||||||
"tags": "TEXT EMBEDDING,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "text-embedding-3-small",
|
|
||||||
"tags": "TEXT EMBEDDING,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "text-embedding-3-large",
|
|
||||||
"tags": "TEXT EMBEDDING,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "whisper-1",
|
|
||||||
"tags": "SPEECH2TEXT",
|
|
||||||
"max_tokens": 25 * 1024 * 1024,
|
|
||||||
"model_type": LLMType.SPEECH2TEXT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "gpt-4",
|
|
||||||
"tags": "LLM,CHAT,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "gpt-4-turbo",
|
|
||||||
"tags": "LLM,CHAT,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},{
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "gpt-4-32k",
|
|
||||||
"tags": "LLM,CHAT,32K",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[0]["name"],
|
|
||||||
"llm_name": "gpt-4-vision-preview",
|
|
||||||
"tags": "LLM,CHAT,IMAGE2TEXT",
|
|
||||||
"max_tokens": 765,
|
|
||||||
"model_type": LLMType.IMAGE2TEXT.value
|
|
||||||
},
|
|
||||||
# ----------------------- Qwen -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[1]["name"],
|
|
||||||
"llm_name": "qwen-turbo",
|
|
||||||
"tags": "LLM,CHAT,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[1]["name"],
|
|
||||||
"llm_name": "qwen-plus",
|
|
||||||
"tags": "LLM,CHAT,32K",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[1]["name"],
|
|
||||||
"llm_name": "qwen-max-1201",
|
|
||||||
"tags": "LLM,CHAT,6K",
|
|
||||||
"max_tokens": 5899,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[1]["name"],
|
|
||||||
"llm_name": "text-embedding-v2",
|
|
||||||
"tags": "TEXT EMBEDDING,2K",
|
|
||||||
"max_tokens": 2048,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[1]["name"],
|
|
||||||
"llm_name": "paraformer-realtime-8k-v1",
|
|
||||||
"tags": "SPEECH2TEXT",
|
|
||||||
"max_tokens": 25 * 1024 * 1024,
|
|
||||||
"model_type": LLMType.SPEECH2TEXT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[1]["name"],
|
|
||||||
"llm_name": "qwen-vl-max",
|
|
||||||
"tags": "LLM,CHAT,IMAGE2TEXT",
|
|
||||||
"max_tokens": 765,
|
|
||||||
"model_type": LLMType.IMAGE2TEXT.value
|
|
||||||
},
|
|
||||||
# ---------------------- ZhipuAI ----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[2]["name"],
|
|
||||||
"llm_name": "glm-3-turbo",
|
|
||||||
"tags": "LLM,CHAT,",
|
|
||||||
"max_tokens": 128 * 1000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[2]["name"],
|
|
||||||
"llm_name": "glm-4",
|
|
||||||
"tags": "LLM,CHAT,",
|
|
||||||
"max_tokens": 128 * 1000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[2]["name"],
|
|
||||||
"llm_name": "glm-4v",
|
|
||||||
"tags": "LLM,CHAT,IMAGE2TEXT",
|
|
||||||
"max_tokens": 2000,
|
|
||||||
"model_type": LLMType.IMAGE2TEXT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[2]["name"],
|
|
||||||
"llm_name": "embedding-2",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
# ------------------------ Moonshot -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[4]["name"],
|
|
||||||
"llm_name": "moonshot-v1-8k",
|
|
||||||
"tags": "LLM,CHAT,",
|
|
||||||
"max_tokens": 7900,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[4]["name"],
|
|
||||||
"llm_name": "moonshot-v1-32k",
|
|
||||||
"tags": "LLM,CHAT,",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[4]["name"],
|
|
||||||
"llm_name": "moonshot-v1-128k",
|
|
||||||
"tags": "LLM,CHAT",
|
|
||||||
"max_tokens": 128 * 1000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
# ------------------------ FastEmbed -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "BAAI/bge-small-en-v1.5",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "BAAI/bge-small-zh-v1.5",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "BAAI/bge-base-en-v1.5",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "BAAI/bge-large-en-v1.5",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "sentence-transformers/all-MiniLM-L6-v2",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "nomic-ai/nomic-embed-text-v1.5",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "jinaai/jina-embeddings-v2-small-en",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 2147483648,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[5]["name"],
|
|
||||||
"llm_name": "jinaai/jina-embeddings-v2-base-en",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 2147483648,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
# ------------------------ Youdao -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[7]["name"],
|
|
||||||
"llm_name": "maidalun1020/bce-embedding-base_v1",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[7]["name"],
|
|
||||||
"llm_name": "maidalun1020/bce-reranker-base_v1",
|
|
||||||
"tags": "RE-RANK, 512",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.RERANK.value
|
|
||||||
},
|
|
||||||
# ------------------------ DeepSeek -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[8]["name"],
|
|
||||||
"llm_name": "deepseek-chat",
|
|
||||||
"tags": "LLM,CHAT,",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[8]["name"],
|
|
||||||
"llm_name": "deepseek-coder",
|
|
||||||
"tags": "LLM,CHAT,",
|
|
||||||
"max_tokens": 16385,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
# ------------------------ VolcEngine -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[9]["name"],
|
|
||||||
"llm_name": "Skylark2-pro-32k",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[9]["name"],
|
|
||||||
"llm_name": "Skylark2-pro-4k",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
# ------------------------ BaiChuan -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[10]["name"],
|
|
||||||
"llm_name": "Baichuan2-Turbo",
|
|
||||||
"tags": "LLM,CHAT,32K",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[10]["name"],
|
|
||||||
"llm_name": "Baichuan2-Turbo-192k",
|
|
||||||
"tags": "LLM,CHAT,192K",
|
|
||||||
"max_tokens": 196608,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[10]["name"],
|
|
||||||
"llm_name": "Baichuan3-Turbo",
|
|
||||||
"tags": "LLM,CHAT,32K",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[10]["name"],
|
|
||||||
"llm_name": "Baichuan3-Turbo-128k",
|
|
||||||
"tags": "LLM,CHAT,128K",
|
|
||||||
"max_tokens": 131072,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[10]["name"],
|
|
||||||
"llm_name": "Baichuan4",
|
|
||||||
"tags": "LLM,CHAT,128K",
|
|
||||||
"max_tokens": 131072,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[10]["name"],
|
|
||||||
"llm_name": "Baichuan-Text-Embedding",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 512,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
# ------------------------ Jina -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-reranker-v1-base-en",
|
|
||||||
"tags": "RE-RANK,8k",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.RERANK.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-reranker-v1-turbo-en",
|
|
||||||
"tags": "RE-RANK,8k",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.RERANK.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-reranker-v1-tiny-en",
|
|
||||||
"tags": "RE-RANK,8k",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.RERANK.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-colbert-v1-en",
|
|
||||||
"tags": "RE-RANK,8k",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.RERANK.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-embeddings-v2-base-en",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-embeddings-v2-base-de",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-embeddings-v2-base-es",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-embeddings-v2-base-code",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[11]["name"],
|
|
||||||
"llm_name": "jina-embeddings-v2-base-zh",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 8196,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
# ------------------------ BAAI -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[12]["name"],
|
|
||||||
"llm_name": "BAAI/bge-large-zh-v1.5",
|
|
||||||
"tags": "TEXT EMBEDDING,",
|
|
||||||
"max_tokens": 1024,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[12]["name"],
|
|
||||||
"llm_name": "BAAI/bge-reranker-v2-m3",
|
|
||||||
"tags": "RE-RANK,2k",
|
|
||||||
"max_tokens": 2048,
|
|
||||||
"model_type": LLMType.RERANK.value
|
|
||||||
},
|
|
||||||
# ------------------------ Minimax -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[13]["name"],
|
|
||||||
"llm_name": "abab6.5-chat",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[13]["name"],
|
|
||||||
"llm_name": "abab6.5s-chat",
|
|
||||||
"tags": "LLM,CHAT,245k",
|
|
||||||
"max_tokens": 245760,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[13]["name"],
|
|
||||||
"llm_name": "abab6.5t-chat",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[13]["name"],
|
|
||||||
"llm_name": "abab6.5g-chat",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[13]["name"],
|
|
||||||
"llm_name": "abab5.5-chat",
|
|
||||||
"tags": "LLM,CHAT,16k",
|
|
||||||
"max_tokens": 16384,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[13]["name"],
|
|
||||||
"llm_name": "abab5.5s-chat",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
# ------------------------ Mistral -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "open-mixtral-8x22b",
|
|
||||||
"tags": "LLM,CHAT,64k",
|
|
||||||
"max_tokens": 64000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "open-mixtral-8x7b",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "open-mistral-7b",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "mistral-large-latest",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "mistral-small-latest",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "mistral-medium-latest",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "codestral-latest",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[14]["name"],
|
|
||||||
"llm_name": "mistral-embed",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.EMBEDDING
|
|
||||||
},
|
|
||||||
# ------------------------ Azure OpenAI -----------------------
|
|
||||||
# Please ensure the llm_name is the same as the name in Azure
|
|
||||||
# OpenAI deployment name (e.g., azure-gpt-4o). And the llm_name
|
|
||||||
# must different from the OpenAI llm_name
|
|
||||||
#
|
|
||||||
# Each model must be deployed in the Azure OpenAI service, otherwise,
|
|
||||||
# you will receive an error message 'The API deployment for
|
|
||||||
# this resource does not exist'
|
|
||||||
{
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-4o",
|
|
||||||
"tags": "LLM,CHAT,128K",
|
|
||||||
"max_tokens": 128000,
|
|
||||||
"model_type": LLMType.CHAT.value + "," + LLMType.IMAGE2TEXT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-35-turbo",
|
|
||||||
"tags": "LLM,CHAT,4K",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-35-turbo-16k",
|
|
||||||
"tags": "LLM,CHAT,16k",
|
|
||||||
"max_tokens": 16385,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-text-embedding-ada-002",
|
|
||||||
"tags": "TEXT EMBEDDING,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-text-embedding-3-small",
|
|
||||||
"tags": "TEXT EMBEDDING,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-text-embedding-3-large",
|
|
||||||
"tags": "TEXT EMBEDDING,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},{
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-whisper-1",
|
|
||||||
"tags": "SPEECH2TEXT",
|
|
||||||
"max_tokens": 25 * 1024 * 1024,
|
|
||||||
"model_type": LLMType.SPEECH2TEXT.value
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-4",
|
|
||||||
"tags": "LLM,CHAT,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-4-turbo",
|
|
||||||
"tags": "LLM,CHAT,8K",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-4-32k",
|
|
||||||
"tags": "LLM,CHAT,32K",
|
|
||||||
"max_tokens": 32768,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[15]["name"],
|
|
||||||
"llm_name": "azure-gpt-4-vision-preview",
|
|
||||||
"tags": "LLM,CHAT,IMAGE2TEXT",
|
|
||||||
"max_tokens": 765,
|
|
||||||
"model_type": LLMType.IMAGE2TEXT.value
|
|
||||||
},
|
|
||||||
# ------------------------ Bedrock -----------------------
|
|
||||||
{
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "ai21.j2-ultra-v1",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "ai21.j2-mid-v1",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8191,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "cohere.command-text-v14",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "cohere.command-light-text-v14",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "cohere.command-r-v1:0",
|
|
||||||
"tags": "LLM,CHAT,128k",
|
|
||||||
"max_tokens": 128 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "cohere.command-r-plus-v1:0",
|
|
||||||
"tags": "LLM,CHAT,128k",
|
|
||||||
"max_tokens": 128000,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-v2",
|
|
||||||
"tags": "LLM,CHAT,100k",
|
|
||||||
"max_tokens": 100 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-v2:1",
|
|
||||||
"tags": "LLM,CHAT,200k",
|
|
||||||
"max_tokens": 200 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-3-sonnet-20240229-v1:0",
|
|
||||||
"tags": "LLM,CHAT,200k",
|
|
||||||
"max_tokens": 200 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-3-5-sonnet-20240620-v1:0",
|
|
||||||
"tags": "LLM,CHAT,200k",
|
|
||||||
"max_tokens": 200 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-3-haiku-20240307-v1:0",
|
|
||||||
"tags": "LLM,CHAT,200k",
|
|
||||||
"max_tokens": 200 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-3-opus-20240229-v1:0",
|
|
||||||
"tags": "LLM,CHAT,200k",
|
|
||||||
"max_tokens": 200 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "anthropic.claude-instant-v1",
|
|
||||||
"tags": "LLM,CHAT,100k",
|
|
||||||
"max_tokens": 100 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "amazon.titan-text-express-v1",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "amazon.titan-text-premier-v1:0",
|
|
||||||
"tags": "LLM,CHAT,32k",
|
|
||||||
"max_tokens": 32 * 1024,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "amazon.titan-text-lite-v1",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "meta.llama2-13b-chat-v1",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "meta.llama2-70b-chat-v1",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "meta.llama3-8b-instruct-v1:0",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "meta.llama3-70b-instruct-v1:0",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "mistral.mistral-7b-instruct-v0:2",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "mistral.mixtral-8x7b-instruct-v0:1",
|
|
||||||
"tags": "LLM,CHAT,4k",
|
|
||||||
"max_tokens": 4096,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "mistral.mistral-large-2402-v1:0",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "mistral.mistral-small-2402-v1:0",
|
|
||||||
"tags": "LLM,CHAT,8k",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.CHAT.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "amazon.titan-embed-text-v2:0",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 8192,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "cohere.embed-english-v3",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 2048,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
}, {
|
|
||||||
"fid": factory_infos[16]["name"],
|
|
||||||
"llm_name": "cohere.embed-multilingual-v3",
|
|
||||||
"tags": "TEXT EMBEDDING",
|
|
||||||
"max_tokens": 2048,
|
|
||||||
"model_type": LLMType.EMBEDDING.value
|
|
||||||
},
|
|
||||||
]
|
|
||||||
for info in factory_infos:
|
|
||||||
try:
|
try:
|
||||||
LLMFactoriesService.save(**info)
|
LLMFactoriesService.save(**factory_llm_info)
|
||||||
except Exception as e:
|
|
||||||
pass
|
|
||||||
for info in llm_infos:
|
|
||||||
try:
|
|
||||||
LLMService.save(**info)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
|
LLMService.filter_delete([LLM.fid == factory_llm_info["name"]])
|
||||||
|
for llm_info in llm_infos:
|
||||||
|
llm_info["fid"] = factory_llm_info["name"]
|
||||||
|
try:
|
||||||
|
LLMService.save(**llm_info)
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
|
||||||
LLMFactoriesService.filter_delete([LLMFactories.name == "Local"])
|
LLMFactoriesService.filter_delete([LLMFactories.name == "Local"])
|
||||||
LLMService.filter_delete([LLM.fid == "Local"])
|
LLMService.filter_delete([LLM.fid == "Local"])
|
||||||
|
LLMService.filter_delete([LLM.llm_name == "qwen-vl-max"])
|
||||||
LLMService.filter_delete([LLM.fid == "Moonshot", LLM.llm_name == "flag-embedding"])
|
LLMService.filter_delete([LLM.fid == "Moonshot", LLM.llm_name == "flag-embedding"])
|
||||||
TenantLLMService.filter_delete([TenantLLM.llm_factory == "Moonshot", TenantLLM.llm_name == "flag-embedding"])
|
TenantLLMService.filter_delete([TenantLLM.llm_factory == "Moonshot", TenantLLM.llm_name == "flag-embedding"])
|
||||||
LLMFactoriesService.filter_delete([LLMFactoriesService.model.name == "QAnything"])
|
LLMFactoriesService.filter_delete([LLMFactoriesService.model.name == "QAnything"])
|
||||||
LLMService.filter_delete([LLMService.model.fid == "QAnything"])
|
LLMService.filter_delete([LLMService.model.fid == "QAnything"])
|
||||||
TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "QAnything"], {"llm_factory": "Youdao"})
|
TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "QAnything"], {"llm_factory": "Youdao"})
|
||||||
|
TenantService.filter_update([1 == 1], {
|
||||||
|
"parser_ids": "naive:General,qa:Q&A,resume:Resume,manual:Manual,table:Table,paper:Paper,book:Book,laws:Laws,presentation:Presentation,picture:Picture,one:One,audio:Audio,knowledge_graph:Knowledge Graph,email:Email"})
|
||||||
## insert openai two embedding models to the current openai user.
|
## insert openai two embedding models to the current openai user.
|
||||||
print("Start to insert 2 OpenAI embedding models...")
|
print("Start to insert 2 OpenAI embedding models...")
|
||||||
tenant_ids = set([row["tenant_id"] for row in TenantLLMService.get_openai_models()])
|
tenant_ids = set([row["tenant_id"] for row in TenantLLMService.get_openai_models()])
|
||||||
@ -940,7 +153,7 @@ def init_llm_factory():
|
|||||||
"""
|
"""
|
||||||
drop table llm;
|
drop table llm;
|
||||||
drop table llm_factories;
|
drop table llm_factories;
|
||||||
update tenant set parser_ids='naive:General,qa:Q&A,resume:Resume,manual:Manual,table:Table,paper:Paper,book:Book,laws:Laws,presentation:Presentation,picture:Picture,one:One';
|
update tenant set parser_ids='naive:General,qa:Q&A,resume:Resume,manual:Manual,table:Table,paper:Paper,book:Book,laws:Laws,presentation:Presentation,picture:Picture,one:One,audio:Audio,knowledge_graph:Knowledge Graph';
|
||||||
alter table knowledgebase modify avatar longtext;
|
alter table knowledgebase modify avatar longtext;
|
||||||
alter table user modify avatar longtext;
|
alter table user modify avatar longtext;
|
||||||
alter table dialog modify icon longtext;
|
alter table dialog modify icon longtext;
|
||||||
@ -948,7 +161,7 @@ def init_llm_factory():
|
|||||||
|
|
||||||
|
|
||||||
def add_graph_templates():
|
def add_graph_templates():
|
||||||
dir = os.path.join(get_project_base_directory(), "graph", "templates")
|
dir = os.path.join(get_project_base_directory(), "agent", "templates")
|
||||||
for fnm in os.listdir(dir):
|
for fnm in os.listdir(dir):
|
||||||
try:
|
try:
|
||||||
cnvs = json.load(open(os.path.join(dir, fnm), "r"))
|
cnvs = json.load(open(os.path.join(dir, fnm), "r"))
|
||||||
@ -965,8 +178,8 @@ def init_web_data():
|
|||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
|
||||||
init_llm_factory()
|
init_llm_factory()
|
||||||
if not UserService.get_all().count():
|
#if not UserService.get_all().count():
|
||||||
init_superuser()
|
# init_superuser()
|
||||||
|
|
||||||
add_graph_templates()
|
add_graph_templates()
|
||||||
print("init web data success:{}".format(time.time() - start_time))
|
print("init web data success:{}".format(time.time() - start_time))
|
||||||
|
|||||||
@ -14,7 +14,9 @@
|
|||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
import peewee
|
import peewee
|
||||||
|
|
||||||
from api.db.db_models import DB, API4Conversation, APIToken, Dialog
|
from api.db.db_models import DB, API4Conversation, APIToken, Dialog
|
||||||
from api.db.services.common_service import CommonService
|
from api.db.services.common_service import CommonService
|
||||||
from api.utils import current_timestamp, datetime_format
|
from api.utils import current_timestamp, datetime_format
|
||||||
@ -41,11 +43,12 @@ class API4ConversationService(CommonService):
|
|||||||
@DB.connection_context()
|
@DB.connection_context()
|
||||||
def append_message(cls, id, conversation):
|
def append_message(cls, id, conversation):
|
||||||
cls.update_by_id(id, conversation)
|
cls.update_by_id(id, conversation)
|
||||||
return cls.model.update(round=cls.model.round + 1).where(cls.model.id==id).execute()
|
return cls.model.update(round=cls.model.round + 1).where(cls.model.id == id).execute()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@DB.connection_context()
|
@DB.connection_context()
|
||||||
def stats(cls, tenant_id, from_date, to_date):
|
def stats(cls, tenant_id, from_date, to_date, source=None):
|
||||||
|
if len(to_date) == 10: to_date += " 23:59:59"
|
||||||
return cls.model.select(
|
return cls.model.select(
|
||||||
cls.model.create_date.truncate("day").alias("dt"),
|
cls.model.create_date.truncate("day").alias("dt"),
|
||||||
peewee.fn.COUNT(
|
peewee.fn.COUNT(
|
||||||
@ -60,7 +63,8 @@ class API4ConversationService(CommonService):
|
|||||||
cls.model.round).alias("round"),
|
cls.model.round).alias("round"),
|
||||||
peewee.fn.SUM(
|
peewee.fn.SUM(
|
||||||
cls.model.thumb_up).alias("thumb_up")
|
cls.model.thumb_up).alias("thumb_up")
|
||||||
).join(Dialog, on=(cls.model.dialog_id == Dialog.id & Dialog.tenant_id == tenant_id)).where(
|
).join(Dialog, on=((cls.model.dialog_id == Dialog.id) & (Dialog.tenant_id == tenant_id))).where(
|
||||||
cls.model.create_date >= from_date,
|
cls.model.create_date >= from_date,
|
||||||
cls.model.create_date <= to_date
|
cls.model.create_date <= to_date,
|
||||||
|
cls.model.source == source
|
||||||
).group_by(cls.model.create_date.truncate("day")).dicts()
|
).group_by(cls.model.create_date.truncate("day")).dicts()
|
||||||
|
|||||||
@ -13,19 +13,23 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
|
import binascii
|
||||||
|
import os
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
from timeit import default_timer as timer
|
||||||
from api.db import LLMType
|
from api.db import LLMType, ParserType
|
||||||
from api.db.db_models import Dialog, Conversation
|
from api.db.db_models import Dialog, Conversation
|
||||||
from api.db.services.common_service import CommonService
|
from api.db.services.common_service import CommonService
|
||||||
from api.db.services.knowledgebase_service import KnowledgebaseService
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
||||||
from api.db.services.llm_service import LLMService, TenantLLMService, LLMBundle
|
from api.db.services.llm_service import LLMService, TenantLLMService, LLMBundle
|
||||||
from api.settings import chat_logger, retrievaler
|
from api.settings import chat_logger, retrievaler, kg_retrievaler
|
||||||
from rag.app.resume import forbidden_select_fields4resume
|
from rag.app.resume import forbidden_select_fields4resume
|
||||||
from rag.nlp import keyword_extraction
|
from rag.nlp import keyword_extraction
|
||||||
from rag.nlp.search import index_name
|
from rag.nlp.search import index_name
|
||||||
from rag.utils import rmSpace, num_tokens_from_string, encoder
|
from rag.utils import rmSpace, num_tokens_from_string, encoder
|
||||||
|
from api.utils.file_utils import get_project_base_directory
|
||||||
|
|
||||||
|
|
||||||
class DialogService(CommonService):
|
class DialogService(CommonService):
|
||||||
@ -73,14 +77,31 @@ def message_fit_in(msg, max_length=4000):
|
|||||||
return max_length, msg
|
return max_length, msg
|
||||||
|
|
||||||
|
|
||||||
|
def llm_id2llm_type(llm_id):
|
||||||
|
llm_id = llm_id.split("@")[0]
|
||||||
|
fnm = os.path.join(get_project_base_directory(), "conf")
|
||||||
|
llm_factories = json.load(open(os.path.join(fnm, "llm_factories.json"), "r"))
|
||||||
|
for llm_factory in llm_factories["factory_llm_infos"]:
|
||||||
|
for llm in llm_factory["llm"]:
|
||||||
|
if llm_id == llm["llm_name"]:
|
||||||
|
return llm["model_type"].strip(",")[-1]
|
||||||
|
|
||||||
|
|
||||||
def chat(dialog, messages, stream=True, **kwargs):
|
def chat(dialog, messages, stream=True, **kwargs):
|
||||||
assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
|
assert messages[-1]["role"] == "user", "The last content of this conversation is not from user."
|
||||||
llm = LLMService.query(llm_name=dialog.llm_id)
|
st = timer()
|
||||||
|
tmp = dialog.llm_id.split("@")
|
||||||
|
fid = None
|
||||||
|
llm_id = tmp[0]
|
||||||
|
if len(tmp)>1: fid = tmp[1]
|
||||||
|
|
||||||
|
llm = LLMService.query(llm_name=llm_id) if not fid else LLMService.query(llm_name=llm_id, fid=fid)
|
||||||
if not llm:
|
if not llm:
|
||||||
llm = TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=dialog.llm_id)
|
llm = TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=llm_id) if not fid else \
|
||||||
|
TenantLLMService.query(tenant_id=dialog.tenant_id, llm_name=llm_id, llm_factory=fid)
|
||||||
if not llm:
|
if not llm:
|
||||||
raise LookupError("LLM(%s) not found" % dialog.llm_id)
|
raise LookupError("LLM(%s) not found" % dialog.llm_id)
|
||||||
max_tokens = 1024
|
max_tokens = 8192
|
||||||
else:
|
else:
|
||||||
max_tokens = llm[0].max_tokens
|
max_tokens = llm[0].max_tokens
|
||||||
kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
|
kbs = KnowledgebaseService.get_by_ids(dialog.kb_ids)
|
||||||
@ -89,12 +110,28 @@ def chat(dialog, messages, stream=True, **kwargs):
|
|||||||
yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
|
yield {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
|
||||||
return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
|
return {"answer": "**ERROR**: Knowledge bases use different embedding models.", "reference": []}
|
||||||
|
|
||||||
questions = [m["content"] for m in messages if m["role"] == "user"]
|
is_kg = all([kb.parser_id == ParserType.KG for kb in kbs])
|
||||||
|
retr = retrievaler if not is_kg else kg_retrievaler
|
||||||
|
|
||||||
|
questions = [m["content"] for m in messages if m["role"] == "user"][-3:]
|
||||||
|
attachments = kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None
|
||||||
|
if "doc_ids" in messages[-1]:
|
||||||
|
attachments = messages[-1]["doc_ids"]
|
||||||
|
for m in messages[:-1]:
|
||||||
|
if "doc_ids" in m:
|
||||||
|
attachments.extend(m["doc_ids"])
|
||||||
|
|
||||||
embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embd_nms[0])
|
embd_mdl = LLMBundle(dialog.tenant_id, LLMType.EMBEDDING, embd_nms[0])
|
||||||
chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
|
if llm_id2llm_type(dialog.llm_id) == "image2text":
|
||||||
|
chat_mdl = LLMBundle(dialog.tenant_id, LLMType.IMAGE2TEXT, dialog.llm_id)
|
||||||
|
else:
|
||||||
|
chat_mdl = LLMBundle(dialog.tenant_id, LLMType.CHAT, dialog.llm_id)
|
||||||
|
|
||||||
prompt_config = dialog.prompt_config
|
prompt_config = dialog.prompt_config
|
||||||
field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
|
field_map = KnowledgebaseService.get_field_map(dialog.kb_ids)
|
||||||
|
tts_mdl = None
|
||||||
|
if prompt_config.get("tts"):
|
||||||
|
tts_mdl = LLMBundle(dialog.tenant_id, LLMType.TTS)
|
||||||
# try to use sql if field mapping is good to go
|
# try to use sql if field mapping is good to go
|
||||||
if field_map:
|
if field_map:
|
||||||
chat_logger.info("Use SQL to retrieval:{}".format(questions[-1]))
|
chat_logger.info("Use SQL to retrieval:{}".format(questions[-1]))
|
||||||
@ -112,6 +149,11 @@ def chat(dialog, messages, stream=True, **kwargs):
|
|||||||
prompt_config["system"] = prompt_config["system"].replace(
|
prompt_config["system"] = prompt_config["system"].replace(
|
||||||
"{%s}" % p["key"], " ")
|
"{%s}" % p["key"], " ")
|
||||||
|
|
||||||
|
if len(questions) > 1 and prompt_config.get("refine_multiturn"):
|
||||||
|
questions = [full_question(dialog.tenant_id, dialog.llm_id, messages)]
|
||||||
|
else:
|
||||||
|
questions = questions[-1:]
|
||||||
|
|
||||||
rerank_mdl = None
|
rerank_mdl = None
|
||||||
if dialog.rerank_id:
|
if dialog.rerank_id:
|
||||||
rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
|
rerank_mdl = LLMBundle(dialog.tenant_id, LLMType.RERANK, dialog.rerank_id)
|
||||||
@ -123,37 +165,30 @@ def chat(dialog, messages, stream=True, **kwargs):
|
|||||||
else:
|
else:
|
||||||
if prompt_config.get("keyword", False):
|
if prompt_config.get("keyword", False):
|
||||||
questions[-1] += keyword_extraction(chat_mdl, questions[-1])
|
questions[-1] += keyword_extraction(chat_mdl, questions[-1])
|
||||||
kbinfos = retrievaler.retrieval(" ".join(questions), embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n,
|
kbinfos = retr.retrieval(" ".join(questions), embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n,
|
||||||
dialog.similarity_threshold,
|
dialog.similarity_threshold,
|
||||||
dialog.vector_similarity_weight,
|
dialog.vector_similarity_weight,
|
||||||
doc_ids=kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None,
|
doc_ids=attachments,
|
||||||
top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl)
|
top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl)
|
||||||
knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
|
knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
|
||||||
#self-rag
|
|
||||||
if dialog.prompt_config.get("self_rag") and not relevant(dialog.tenant_id, dialog.llm_id, questions[-1], knowledges):
|
|
||||||
questions[-1] = rewrite(dialog.tenant_id, dialog.llm_id, questions[-1])
|
|
||||||
kbinfos = retrievaler.retrieval(" ".join(questions), embd_mdl, dialog.tenant_id, dialog.kb_ids, 1, dialog.top_n,
|
|
||||||
dialog.similarity_threshold,
|
|
||||||
dialog.vector_similarity_weight,
|
|
||||||
doc_ids=kwargs["doc_ids"].split(",") if "doc_ids" in kwargs else None,
|
|
||||||
top=dialog.top_k, aggs=False, rerank_mdl=rerank_mdl)
|
|
||||||
knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
|
|
||||||
|
|
||||||
chat_logger.info(
|
chat_logger.info(
|
||||||
"{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
|
"{}->{}".format(" ".join(questions), "\n->".join(knowledges)))
|
||||||
|
retrieval_tm = timer()
|
||||||
|
|
||||||
if not knowledges and prompt_config.get("empty_response"):
|
if not knowledges and prompt_config.get("empty_response"):
|
||||||
yield {"answer": prompt_config["empty_response"], "reference": kbinfos}
|
empty_res = prompt_config["empty_response"]
|
||||||
|
yield {"answer": empty_res, "reference": kbinfos, "audio_binary": tts(tts_mdl, empty_res)}
|
||||||
return {"answer": prompt_config["empty_response"], "reference": kbinfos}
|
return {"answer": prompt_config["empty_response"], "reference": kbinfos}
|
||||||
|
|
||||||
kwargs["knowledge"] = "\n".join(knowledges)
|
kwargs["knowledge"] = "\n\n------\n\n".join(knowledges)
|
||||||
gen_conf = dialog.llm_setting
|
gen_conf = dialog.llm_setting
|
||||||
|
|
||||||
msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
|
msg = [{"role": "system", "content": prompt_config["system"].format(**kwargs)}]
|
||||||
msg.extend([{"role": m["role"], "content": m["content"]}
|
msg.extend([{"role": m["role"], "content": re.sub(r"##\d+\$\$", "", m["content"])}
|
||||||
for m in messages if m["role"] != "system"])
|
for m in messages if m["role"] != "system"])
|
||||||
used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
|
used_token_count, msg = message_fit_in(msg, int(max_tokens * 0.97))
|
||||||
assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
|
assert len(msg) >= 2, f"message_fit_in has bug: {msg}"
|
||||||
|
prompt = msg[0]["content"]
|
||||||
|
|
||||||
if "max_tokens" in gen_conf:
|
if "max_tokens" in gen_conf:
|
||||||
gen_conf["max_tokens"] = min(
|
gen_conf["max_tokens"] = min(
|
||||||
@ -161,9 +196,10 @@ def chat(dialog, messages, stream=True, **kwargs):
|
|||||||
max_tokens - used_token_count)
|
max_tokens - used_token_count)
|
||||||
|
|
||||||
def decorate_answer(answer):
|
def decorate_answer(answer):
|
||||||
nonlocal prompt_config, knowledges, kwargs, kbinfos
|
nonlocal prompt_config, knowledges, kwargs, kbinfos, prompt, retrieval_tm
|
||||||
|
refs = []
|
||||||
if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
|
if knowledges and (prompt_config.get("quote", True) and kwargs.get("quote", True)):
|
||||||
answer, idx = retrievaler.insert_citations(answer,
|
answer, idx = retr.insert_citations(answer,
|
||||||
[ck["content_ltks"]
|
[ck["content_ltks"]
|
||||||
for ck in kbinfos["chunks"]],
|
for ck in kbinfos["chunks"]],
|
||||||
[ck["vector"]
|
[ck["vector"]
|
||||||
@ -177,26 +213,38 @@ def chat(dialog, messages, stream=True, **kwargs):
|
|||||||
if not recall_docs: recall_docs = kbinfos["doc_aggs"]
|
if not recall_docs: recall_docs = kbinfos["doc_aggs"]
|
||||||
kbinfos["doc_aggs"] = recall_docs
|
kbinfos["doc_aggs"] = recall_docs
|
||||||
|
|
||||||
refs = deepcopy(kbinfos)
|
refs = deepcopy(kbinfos)
|
||||||
for c in refs["chunks"]:
|
for c in refs["chunks"]:
|
||||||
if c.get("vector"):
|
if c.get("vector"):
|
||||||
del c["vector"]
|
del c["vector"]
|
||||||
|
|
||||||
if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
|
if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
|
||||||
answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
|
answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
|
||||||
return {"answer": answer, "reference": refs}
|
done_tm = timer()
|
||||||
|
prompt += "\n\n### Elapsed\n - Retrieval: %.1f ms\n - LLM: %.1f ms"%((retrieval_tm-st)*1000, (done_tm-st)*1000)
|
||||||
|
return {"answer": answer, "reference": refs, "prompt": prompt}
|
||||||
|
|
||||||
if stream:
|
if stream:
|
||||||
|
last_ans = ""
|
||||||
answer = ""
|
answer = ""
|
||||||
for ans in chat_mdl.chat_streamly(msg[0]["content"], msg[1:], gen_conf):
|
for ans in chat_mdl.chat_streamly(prompt, msg[1:], gen_conf):
|
||||||
answer = ans
|
answer = ans
|
||||||
yield {"answer": answer, "reference": {}}
|
delta_ans = ans[len(last_ans):]
|
||||||
|
if num_tokens_from_string(delta_ans) < 16:
|
||||||
|
continue
|
||||||
|
last_ans = answer
|
||||||
|
yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
|
||||||
|
delta_ans = answer[len(last_ans):]
|
||||||
|
if delta_ans:
|
||||||
|
yield {"answer": answer, "reference": {}, "audio_binary": tts(tts_mdl, delta_ans)}
|
||||||
yield decorate_answer(answer)
|
yield decorate_answer(answer)
|
||||||
else:
|
else:
|
||||||
answer = chat_mdl.chat(
|
answer = chat_mdl.chat(prompt, msg[1:], gen_conf)
|
||||||
msg[0]["content"], msg[1:], gen_conf)
|
|
||||||
chat_logger.info("User: {}|Assistant: {}".format(
|
chat_logger.info("User: {}|Assistant: {}".format(
|
||||||
msg[-1]["content"], answer))
|
msg[-1]["content"], answer))
|
||||||
yield decorate_answer(answer)
|
res = decorate_answer(answer)
|
||||||
|
res["audio_binary"] = tts(tts_mdl, answer)
|
||||||
|
yield res
|
||||||
|
|
||||||
|
|
||||||
def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
|
def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
|
||||||
@ -307,7 +355,8 @@ def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
|
|||||||
chat_logger.warning("SQL missing field: " + sql)
|
chat_logger.warning("SQL missing field: " + sql)
|
||||||
return {
|
return {
|
||||||
"answer": "\n".join([clmns, line, rows]),
|
"answer": "\n".join([clmns, line, rows]),
|
||||||
"reference": {"chunks": [], "doc_aggs": []}
|
"reference": {"chunks": [], "doc_aggs": []},
|
||||||
|
"prompt": sys_prompt
|
||||||
}
|
}
|
||||||
|
|
||||||
docid_idx = list(docid_idx)[0]
|
docid_idx = list(docid_idx)[0]
|
||||||
@ -321,12 +370,16 @@ def use_sql(question, field_map, tenant_id, chat_mdl, quota=True):
|
|||||||
"answer": "\n".join([clmns, line, rows]),
|
"answer": "\n".join([clmns, line, rows]),
|
||||||
"reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]],
|
"reference": {"chunks": [{"doc_id": r[docid_idx], "docnm_kwd": r[docnm_idx]} for r in tbl["rows"]],
|
||||||
"doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in
|
"doc_aggs": [{"doc_id": did, "doc_name": d["doc_name"], "count": d["count"]} for did, d in
|
||||||
doc_aggs.items()]}
|
doc_aggs.items()]},
|
||||||
|
"prompt": sys_prompt
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def relevant(tenant_id, llm_id, question, contents: list):
|
def relevant(tenant_id, llm_id, question, contents: list):
|
||||||
chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
|
if llm_id2llm_type(llm_id) == "image2text":
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
|
||||||
|
else:
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
|
||||||
prompt = """
|
prompt = """
|
||||||
You are a grader assessing relevance of a retrieved document to a user question.
|
You are a grader assessing relevance of a retrieved document to a user question.
|
||||||
It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
|
It does not need to be a stringent test. The goal is to filter out erroneous retrievals.
|
||||||
@ -345,7 +398,10 @@ def relevant(tenant_id, llm_id, question, contents: list):
|
|||||||
|
|
||||||
|
|
||||||
def rewrite(tenant_id, llm_id, question):
|
def rewrite(tenant_id, llm_id, question):
|
||||||
chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
|
if llm_id2llm_type(llm_id) == "image2text":
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
|
||||||
|
else:
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
|
||||||
prompt = """
|
prompt = """
|
||||||
You are an expert at query expansion to generate a paraphrasing of a question.
|
You are an expert at query expansion to generate a paraphrasing of a question.
|
||||||
I can't retrieval relevant information from the knowledge base by using user's question directly.
|
I can't retrieval relevant information from the knowledge base by using user's question directly.
|
||||||
@ -357,3 +413,134 @@ def rewrite(tenant_id, llm_id, question):
|
|||||||
"""
|
"""
|
||||||
ans = chat_mdl.chat(prompt, [{"role": "user", "content": question}], {"temperature": 0.8})
|
ans = chat_mdl.chat(prompt, [{"role": "user", "content": question}], {"temperature": 0.8})
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
|
|
||||||
|
def full_question(tenant_id, llm_id, messages):
|
||||||
|
if llm_id2llm_type(llm_id) == "image2text":
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.IMAGE2TEXT, llm_id)
|
||||||
|
else:
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.CHAT, llm_id)
|
||||||
|
conv = []
|
||||||
|
for m in messages:
|
||||||
|
if m["role"] not in ["user", "assistant"]: continue
|
||||||
|
conv.append("{}: {}".format(m["role"].upper(), m["content"]))
|
||||||
|
conv = "\n".join(conv)
|
||||||
|
prompt = f"""
|
||||||
|
Role: A helpful assistant
|
||||||
|
Task: Generate a full user question that would follow the conversation.
|
||||||
|
Requirements & Restrictions:
|
||||||
|
- Text generated MUST be in the same language of the original user's question.
|
||||||
|
- If the user's latest question is completely, don't do anything, just return the original question.
|
||||||
|
- DON'T generate anything except a refined question.
|
||||||
|
|
||||||
|
######################
|
||||||
|
-Examples-
|
||||||
|
######################
|
||||||
|
|
||||||
|
# Example 1
|
||||||
|
## Conversation
|
||||||
|
USER: What is the name of Donald Trump's father?
|
||||||
|
ASSISTANT: Fred Trump.
|
||||||
|
USER: And his mother?
|
||||||
|
###############
|
||||||
|
Output: What's the name of Donald Trump's mother?
|
||||||
|
|
||||||
|
------------
|
||||||
|
# Example 2
|
||||||
|
## Conversation
|
||||||
|
USER: What is the name of Donald Trump's father?
|
||||||
|
ASSISTANT: Fred Trump.
|
||||||
|
USER: And his mother?
|
||||||
|
ASSISTANT: Mary Trump.
|
||||||
|
User: What's her full name?
|
||||||
|
###############
|
||||||
|
Output: What's the full name of Donald Trump's mother Mary Trump?
|
||||||
|
|
||||||
|
######################
|
||||||
|
|
||||||
|
# Real Data
|
||||||
|
## Conversation
|
||||||
|
{conv}
|
||||||
|
###############
|
||||||
|
"""
|
||||||
|
ans = chat_mdl.chat(prompt, [{"role": "user", "content": "Output: "}], {"temperature": 0.2})
|
||||||
|
return ans if ans.find("**ERROR**") < 0 else messages[-1]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
def tts(tts_mdl, text):
|
||||||
|
if not tts_mdl or not text: return
|
||||||
|
bin = b""
|
||||||
|
for chunk in tts_mdl.tts(text):
|
||||||
|
bin += chunk
|
||||||
|
return binascii.hexlify(bin).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def ask(question, kb_ids, tenant_id):
|
||||||
|
kbs = KnowledgebaseService.get_by_ids(kb_ids)
|
||||||
|
embd_nms = list(set([kb.embd_id for kb in kbs]))
|
||||||
|
|
||||||
|
is_kg = all([kb.parser_id == ParserType.KG for kb in kbs])
|
||||||
|
retr = retrievaler if not is_kg else kg_retrievaler
|
||||||
|
|
||||||
|
embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embd_nms[0])
|
||||||
|
chat_mdl = LLMBundle(tenant_id, LLMType.CHAT)
|
||||||
|
max_tokens = chat_mdl.max_length
|
||||||
|
|
||||||
|
kbinfos = retr.retrieval(question, embd_mdl, tenant_id, kb_ids, 1, 12, 0.1, 0.3, aggs=False)
|
||||||
|
knowledges = [ck["content_with_weight"] for ck in kbinfos["chunks"]]
|
||||||
|
|
||||||
|
used_token_count = 0
|
||||||
|
for i, c in enumerate(knowledges):
|
||||||
|
used_token_count += num_tokens_from_string(c)
|
||||||
|
if max_tokens * 0.97 < used_token_count:
|
||||||
|
knowledges = knowledges[:i]
|
||||||
|
break
|
||||||
|
|
||||||
|
prompt = """
|
||||||
|
Role: You're a smart assistant. Your name is Miss R.
|
||||||
|
Task: Summarize the information from knowledge bases and answer user's question.
|
||||||
|
Requirements and restriction:
|
||||||
|
- DO NOT make things up, especially for numbers.
|
||||||
|
- If the information from knowledge is irrelevant with user's question, JUST SAY: Sorry, no relevant information provided.
|
||||||
|
- Answer with markdown format text.
|
||||||
|
- Answer in language of user's question.
|
||||||
|
- DO NOT make things up, especially for numbers.
|
||||||
|
|
||||||
|
### Information from knowledge bases
|
||||||
|
%s
|
||||||
|
|
||||||
|
The above is information from knowledge bases.
|
||||||
|
|
||||||
|
"""%"\n".join(knowledges)
|
||||||
|
msg = [{"role": "user", "content": question}]
|
||||||
|
|
||||||
|
def decorate_answer(answer):
|
||||||
|
nonlocal knowledges, kbinfos, prompt
|
||||||
|
answer, idx = retr.insert_citations(answer,
|
||||||
|
[ck["content_ltks"]
|
||||||
|
for ck in kbinfos["chunks"]],
|
||||||
|
[ck["vector"]
|
||||||
|
for ck in kbinfos["chunks"]],
|
||||||
|
embd_mdl,
|
||||||
|
tkweight=0.7,
|
||||||
|
vtweight=0.3)
|
||||||
|
idx = set([kbinfos["chunks"][int(i)]["doc_id"] for i in idx])
|
||||||
|
recall_docs = [
|
||||||
|
d for d in kbinfos["doc_aggs"] if d["doc_id"] in idx]
|
||||||
|
if not recall_docs: recall_docs = kbinfos["doc_aggs"]
|
||||||
|
kbinfos["doc_aggs"] = recall_docs
|
||||||
|
refs = deepcopy(kbinfos)
|
||||||
|
for c in refs["chunks"]:
|
||||||
|
if c.get("vector"):
|
||||||
|
del c["vector"]
|
||||||
|
|
||||||
|
if answer.lower().find("invalid key") >= 0 or answer.lower().find("invalid api") >= 0:
|
||||||
|
answer += " Please set LLM API-Key in 'User Setting -> Model Providers -> API-Key'"
|
||||||
|
return {"answer": answer, "reference": refs}
|
||||||
|
|
||||||
|
answer = ""
|
||||||
|
for ans in chat_mdl.chat_streamly(prompt, msg, {"temperature": 0.1}):
|
||||||
|
answer = ans
|
||||||
|
yield {"answer": answer, "reference": {}}
|
||||||
|
yield decorate_answer(answer)
|
||||||
|
|
||||||
|
|||||||
@ -13,20 +13,31 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
#
|
#
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
import random
|
import random
|
||||||
|
import re
|
||||||
|
import traceback
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from copy import deepcopy
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
from elasticsearch_dsl import Q
|
from elasticsearch_dsl import Q
|
||||||
from peewee import fn
|
from peewee import fn
|
||||||
|
|
||||||
from api.db.db_utils import bulk_insert_into_db
|
from api.db.db_utils import bulk_insert_into_db
|
||||||
from api.settings import stat_logger
|
from api.settings import stat_logger
|
||||||
from api.utils import current_timestamp, get_format_time, get_uuid
|
from api.utils import current_timestamp, get_format_time, get_uuid
|
||||||
|
from api.utils.file_utils import get_project_base_directory
|
||||||
|
from graphrag.mind_map_extractor import MindMapExtractor
|
||||||
from rag.settings import SVR_QUEUE_NAME
|
from rag.settings import SVR_QUEUE_NAME
|
||||||
from rag.utils.es_conn import ELASTICSEARCH
|
from rag.utils.es_conn import ELASTICSEARCH
|
||||||
from rag.utils.minio_conn import MINIO
|
from rag.utils.storage_factory import STORAGE_IMPL
|
||||||
from rag.nlp import search
|
from rag.nlp import search, rag_tokenizer
|
||||||
|
|
||||||
from api.db import FileType, TaskStatus
|
from api.db import FileType, TaskStatus, ParserType, LLMType
|
||||||
from api.db.db_models import DB, Knowledgebase, Tenant, Task
|
from api.db.db_models import DB, Knowledgebase, Tenant, Task
|
||||||
from api.db.db_models import Document
|
from api.db.db_models import Document
|
||||||
from api.db.services.common_service import CommonService
|
from api.db.services.common_service import CommonService
|
||||||
@ -142,7 +153,7 @@ class DocumentService(CommonService):
|
|||||||
@classmethod
|
@classmethod
|
||||||
@DB.connection_context()
|
@DB.connection_context()
|
||||||
def get_unfinished_docs(cls):
|
def get_unfinished_docs(cls):
|
||||||
fields = [cls.model.id, cls.model.process_begin_at, cls.model.parser_config, cls.model.progress_msg]
|
fields = [cls.model.id, cls.model.process_begin_at, cls.model.parser_config, cls.model.progress_msg, cls.model.run]
|
||||||
docs = cls.model.select(*fields) \
|
docs = cls.model.select(*fields) \
|
||||||
.where(
|
.where(
|
||||||
cls.model.status == StatusEnum.VALID.value,
|
cls.model.status == StatusEnum.VALID.value,
|
||||||
@ -169,6 +180,25 @@ class DocumentService(CommonService):
|
|||||||
Knowledgebase.id == kb_id).execute()
|
Knowledgebase.id == kb_id).execute()
|
||||||
return num
|
return num
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
@DB.connection_context()
|
||||||
|
def decrement_chunk_num(cls, doc_id, kb_id, token_num, chunk_num, duation):
|
||||||
|
num = cls.model.update(token_num=cls.model.token_num - token_num,
|
||||||
|
chunk_num=cls.model.chunk_num - chunk_num,
|
||||||
|
process_duation=cls.model.process_duation + duation).where(
|
||||||
|
cls.model.id == doc_id).execute()
|
||||||
|
if num == 0:
|
||||||
|
raise LookupError(
|
||||||
|
"Document not found which is supposed to be there")
|
||||||
|
num = Knowledgebase.update(
|
||||||
|
token_num=Knowledgebase.token_num -
|
||||||
|
token_num,
|
||||||
|
chunk_num=Knowledgebase.chunk_num -
|
||||||
|
chunk_num
|
||||||
|
).where(
|
||||||
|
Knowledgebase.id == kb_id).execute()
|
||||||
|
return num
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@DB.connection_context()
|
@DB.connection_context()
|
||||||
def clear_chunk_num(cls, doc_id):
|
def clear_chunk_num(cls, doc_id):
|
||||||
@ -292,12 +322,14 @@ class DocumentService(CommonService):
|
|||||||
prg = 0
|
prg = 0
|
||||||
finished = True
|
finished = True
|
||||||
bad = 0
|
bad = 0
|
||||||
status = TaskStatus.RUNNING.value
|
e, doc = DocumentService.get_by_id(d["id"])
|
||||||
|
status = doc.run#TaskStatus.RUNNING.value
|
||||||
for t in tsks:
|
for t in tsks:
|
||||||
if 0 <= t.progress < 1:
|
if 0 <= t.progress < 1:
|
||||||
finished = False
|
finished = False
|
||||||
prg += t.progress if t.progress >= 0 else 0
|
prg += t.progress if t.progress >= 0 else 0
|
||||||
msg.append(t.progress_msg)
|
if t.progress_msg not in msg:
|
||||||
|
msg.append(t.progress_msg)
|
||||||
if t.progress == -1:
|
if t.progress == -1:
|
||||||
bad += 1
|
bad += 1
|
||||||
prg /= len(tsks)
|
prg /= len(tsks)
|
||||||
@ -333,6 +365,17 @@ class DocumentService(CommonService):
|
|||||||
cls.model.kb_id == kb_id).dicts())
|
cls.model.kb_id == kb_id).dicts())
|
||||||
|
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
@DB.connection_context()
|
||||||
|
def do_cancel(cls, doc_id):
|
||||||
|
try:
|
||||||
|
_, doc = DocumentService.get_by_id(doc_id)
|
||||||
|
return doc.run == TaskStatus.CANCEL.value or doc.progress < 0
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def queue_raptor_tasks(doc):
|
def queue_raptor_tasks(doc):
|
||||||
def new_task():
|
def new_task():
|
||||||
nonlocal doc
|
nonlocal doc
|
||||||
@ -348,3 +391,142 @@ def queue_raptor_tasks(doc):
|
|||||||
bulk_insert_into_db(Task, [task], True)
|
bulk_insert_into_db(Task, [task], True)
|
||||||
task["type"] = "raptor"
|
task["type"] = "raptor"
|
||||||
assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=task), "Can't access Redis. Please check the Redis' status."
|
assert REDIS_CONN.queue_product(SVR_QUEUE_NAME, message=task), "Can't access Redis. Please check the Redis' status."
|
||||||
|
|
||||||
|
|
||||||
|
def doc_upload_and_parse(conversation_id, file_objs, user_id):
|
||||||
|
from rag.app import presentation, picture, naive, audio, email
|
||||||
|
from api.db.services.dialog_service import ConversationService, DialogService
|
||||||
|
from api.db.services.file_service import FileService
|
||||||
|
from api.db.services.llm_service import LLMBundle
|
||||||
|
from api.db.services.user_service import TenantService
|
||||||
|
from api.db.services.api_service import API4ConversationService
|
||||||
|
|
||||||
|
e, conv = ConversationService.get_by_id(conversation_id)
|
||||||
|
if not e:
|
||||||
|
e, conv = API4ConversationService.get_by_id(conversation_id)
|
||||||
|
assert e, "Conversation not found!"
|
||||||
|
|
||||||
|
e, dia = DialogService.get_by_id(conv.dialog_id)
|
||||||
|
kb_id = dia.kb_ids[0]
|
||||||
|
e, kb = KnowledgebaseService.get_by_id(kb_id)
|
||||||
|
if not e:
|
||||||
|
raise LookupError("Can't find this knowledgebase!")
|
||||||
|
|
||||||
|
idxnm = search.index_name(kb.tenant_id)
|
||||||
|
if not ELASTICSEARCH.indexExist(idxnm):
|
||||||
|
ELASTICSEARCH.createIdx(idxnm, json.load(
|
||||||
|
open(os.path.join(get_project_base_directory(), "conf", "mapping.json"), "r")))
|
||||||
|
|
||||||
|
embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id, lang=kb.language)
|
||||||
|
|
||||||
|
err, files = FileService.upload_document(kb, file_objs, user_id)
|
||||||
|
assert not err, "\n".join(err)
|
||||||
|
|
||||||
|
def dummy(prog=None, msg=""):
|
||||||
|
pass
|
||||||
|
|
||||||
|
FACTORY = {
|
||||||
|
ParserType.PRESENTATION.value: presentation,
|
||||||
|
ParserType.PICTURE.value: picture,
|
||||||
|
ParserType.AUDIO.value: audio,
|
||||||
|
ParserType.EMAIL.value: email
|
||||||
|
}
|
||||||
|
parser_config = {"chunk_token_num": 4096, "delimiter": "\n!?;。;!?", "layout_recognize": False}
|
||||||
|
exe = ThreadPoolExecutor(max_workers=12)
|
||||||
|
threads = []
|
||||||
|
doc_nm = {}
|
||||||
|
for d, blob in files:
|
||||||
|
doc_nm[d["id"]] = d["name"]
|
||||||
|
for d, blob in files:
|
||||||
|
kwargs = {
|
||||||
|
"callback": dummy,
|
||||||
|
"parser_config": parser_config,
|
||||||
|
"from_page": 0,
|
||||||
|
"to_page": 100000,
|
||||||
|
"tenant_id": kb.tenant_id,
|
||||||
|
"lang": kb.language
|
||||||
|
}
|
||||||
|
threads.append(exe.submit(FACTORY.get(d["parser_id"], naive).chunk, d["name"], blob, **kwargs))
|
||||||
|
|
||||||
|
for (docinfo, _), th in zip(files, threads):
|
||||||
|
docs = []
|
||||||
|
doc = {
|
||||||
|
"doc_id": docinfo["id"],
|
||||||
|
"kb_id": [kb.id]
|
||||||
|
}
|
||||||
|
for ck in th.result():
|
||||||
|
d = deepcopy(doc)
|
||||||
|
d.update(ck)
|
||||||
|
md5 = hashlib.md5()
|
||||||
|
md5.update((ck["content_with_weight"] +
|
||||||
|
str(d["doc_id"])).encode("utf-8"))
|
||||||
|
d["_id"] = md5.hexdigest()
|
||||||
|
d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
|
||||||
|
d["create_timestamp_flt"] = datetime.now().timestamp()
|
||||||
|
if not d.get("image"):
|
||||||
|
docs.append(d)
|
||||||
|
continue
|
||||||
|
|
||||||
|
output_buffer = BytesIO()
|
||||||
|
if isinstance(d["image"], bytes):
|
||||||
|
output_buffer = BytesIO(d["image"])
|
||||||
|
else:
|
||||||
|
d["image"].save(output_buffer, format='JPEG')
|
||||||
|
|
||||||
|
STORAGE_IMPL.put(kb.id, d["_id"], output_buffer.getvalue())
|
||||||
|
d["img_id"] = "{}-{}".format(kb.id, d["_id"])
|
||||||
|
del d["image"]
|
||||||
|
docs.append(d)
|
||||||
|
|
||||||
|
parser_ids = {d["id"]: d["parser_id"] for d, _ in files}
|
||||||
|
docids = [d["id"] for d, _ in files]
|
||||||
|
chunk_counts = {id: 0 for id in docids}
|
||||||
|
token_counts = {id: 0 for id in docids}
|
||||||
|
es_bulk_size = 64
|
||||||
|
|
||||||
|
def embedding(doc_id, cnts, batch_size=16):
|
||||||
|
nonlocal embd_mdl, chunk_counts, token_counts
|
||||||
|
vects = []
|
||||||
|
for i in range(0, len(cnts), batch_size):
|
||||||
|
vts, c = embd_mdl.encode(cnts[i: i + batch_size])
|
||||||
|
vects.extend(vts.tolist())
|
||||||
|
chunk_counts[doc_id] += len(cnts[i:i + batch_size])
|
||||||
|
token_counts[doc_id] += c
|
||||||
|
return vects
|
||||||
|
|
||||||
|
_, tenant = TenantService.get_by_id(kb.tenant_id)
|
||||||
|
llm_bdl = LLMBundle(kb.tenant_id, LLMType.CHAT, tenant.llm_id)
|
||||||
|
for doc_id in docids:
|
||||||
|
cks = [c for c in docs if c["doc_id"] == doc_id]
|
||||||
|
|
||||||
|
if parser_ids[doc_id] != ParserType.PICTURE.value:
|
||||||
|
mindmap = MindMapExtractor(llm_bdl)
|
||||||
|
try:
|
||||||
|
mind_map = json.dumps(mindmap([c["content_with_weight"] for c in docs if c["doc_id"] == doc_id]).output,
|
||||||
|
ensure_ascii=False, indent=2)
|
||||||
|
if len(mind_map) < 32: raise Exception("Few content: " + mind_map)
|
||||||
|
cks.append({
|
||||||
|
"id": get_uuid(),
|
||||||
|
"doc_id": doc_id,
|
||||||
|
"kb_id": [kb.id],
|
||||||
|
"docnm_kwd": doc_nm[doc_id],
|
||||||
|
"title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc_nm[doc_id])),
|
||||||
|
"content_ltks": "",
|
||||||
|
"content_with_weight": mind_map,
|
||||||
|
"knowledge_graph_kwd": "mind_map"
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
stat_logger.error("Mind map generation error:", traceback.format_exc())
|
||||||
|
|
||||||
|
vects = embedding(doc_id, [c["content_with_weight"] for c in cks])
|
||||||
|
assert len(cks) == len(vects)
|
||||||
|
for i, d in enumerate(cks):
|
||||||
|
v = vects[i]
|
||||||
|
d["q_%d_vec" % len(v)] = v
|
||||||
|
for b in range(0, len(cks), es_bulk_size):
|
||||||
|
ELASTICSEARCH.bulk(cks[b:b + es_bulk_size], idxnm)
|
||||||
|
|
||||||
|
DocumentService.increment_chunk_num(
|
||||||
|
doc_id, kb.id, token_counts[doc_id], chunk_counts[doc_id], 0)
|
||||||
|
|
||||||
|
return [d["id"] for d,_ in files]
|
||||||
@ -69,14 +69,14 @@ class File2DocumentService(CommonService):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@DB.connection_context()
|
@DB.connection_context()
|
||||||
def get_minio_address(cls, doc_id=None, file_id=None):
|
def get_storage_address(cls, doc_id=None, file_id=None):
|
||||||
if doc_id:
|
if doc_id:
|
||||||
f2d = cls.get_by_document_id(doc_id)
|
f2d = cls.get_by_document_id(doc_id)
|
||||||
else:
|
else:
|
||||||
f2d = cls.get_by_file_id(file_id)
|
f2d = cls.get_by_file_id(file_id)
|
||||||
if f2d:
|
if f2d:
|
||||||
file = File.get_by_id(f2d[0].file_id)
|
file = File.get_by_id(f2d[0].file_id)
|
||||||
if file.source_type == FileSource.LOCAL:
|
if not file.source_type or file.source_type == FileSource.LOCAL:
|
||||||
return file.parent_id, file.location
|
return file.parent_id, file.location
|
||||||
doc_id = f2d[0].document_id
|
doc_id = f2d[0].document_id
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user