You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset_service.py 154KB

пре 2 година
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
пре 8 месеци
пре 1 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
пре 8 месеци
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 9 месеци
пре 9 месеци
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
пре 8 месеци
пре 3 месеци
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
пре 8 месеци
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
пре 8 месеци
пре 1 година
пре 3 месеци
пре 3 месеци
Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
пре 8 месеци
пре 3 месеци
пре 3 месеци
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401
  1. import copy
  2. import datetime
  3. import json
  4. import logging
  5. import secrets
  6. import time
  7. import uuid
  8. from collections import Counter
  9. from collections.abc import Sequence
  10. from typing import Any, Literal
  11. import sqlalchemy as sa
  12. from sqlalchemy import exists, func, select
  13. from sqlalchemy.orm import Session
  14. from werkzeug.exceptions import NotFound
  15. from configs import dify_config
  16. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  17. from core.helper.name_generator import generate_incremental_name
  18. from core.model_manager import ModelManager
  19. from core.model_runtime.entities.model_entities import ModelType
  20. from core.rag.index_processor.constant.built_in_field import BuiltInField
  21. from core.rag.index_processor.constant.index_type import IndexType
  22. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  23. from events.dataset_event import dataset_was_deleted
  24. from events.document_event import document_was_deleted
  25. from extensions.ext_database import db
  26. from extensions.ext_redis import redis_client
  27. from libs import helper
  28. from libs.datetime_utils import naive_utc_now
  29. from libs.login import current_user
  30. from models.account import Account, TenantAccountRole
  31. from models.dataset import (
  32. AppDatasetJoin,
  33. ChildChunk,
  34. Dataset,
  35. DatasetAutoDisableLog,
  36. DatasetCollectionBinding,
  37. DatasetPermission,
  38. DatasetPermissionEnum,
  39. DatasetProcessRule,
  40. DatasetQuery,
  41. Document,
  42. DocumentSegment,
  43. ExternalKnowledgeBindings,
  44. Pipeline,
  45. )
  46. from models.model import UploadFile
  47. from models.provider_ids import ModelProviderID
  48. from models.source import DataSourceOauthBinding
  49. from models.workflow import Workflow
  50. from services.entities.knowledge_entities.knowledge_entities import (
  51. ChildChunkUpdateArgs,
  52. KnowledgeConfig,
  53. RerankingModel,
  54. RetrievalModel,
  55. SegmentUpdateArgs,
  56. )
  57. from services.entities.knowledge_entities.rag_pipeline_entities import (
  58. KnowledgeConfiguration,
  59. RagPipelineDatasetCreateEntity,
  60. )
  61. from services.errors.account import NoPermissionError
  62. from services.errors.chunk import ChildChunkDeleteIndexError, ChildChunkIndexingError
  63. from services.errors.dataset import DatasetNameDuplicateError
  64. from services.errors.document import DocumentIndexingError
  65. from services.errors.file import FileNotExistsError
  66. from services.external_knowledge_service import ExternalDatasetService
  67. from services.feature_service import FeatureModel, FeatureService
  68. from services.rag_pipeline.rag_pipeline import RagPipelineService
  69. from services.tag_service import TagService
  70. from services.vector_service import VectorService
  71. from tasks.add_document_to_index_task import add_document_to_index_task
  72. from tasks.batch_clean_document_task import batch_clean_document_task
  73. from tasks.clean_notion_document_task import clean_notion_document_task
  74. from tasks.deal_dataset_index_update_task import deal_dataset_index_update_task
  75. from tasks.deal_dataset_vector_index_task import deal_dataset_vector_index_task
  76. from tasks.delete_segment_from_index_task import delete_segment_from_index_task
  77. from tasks.disable_segment_from_index_task import disable_segment_from_index_task
  78. from tasks.disable_segments_from_index_task import disable_segments_from_index_task
  79. from tasks.document_indexing_task import document_indexing_task
  80. from tasks.document_indexing_update_task import document_indexing_update_task
  81. from tasks.duplicate_document_indexing_task import duplicate_document_indexing_task
  82. from tasks.enable_segments_to_index_task import enable_segments_to_index_task
  83. from tasks.recover_document_indexing_task import recover_document_indexing_task
  84. from tasks.remove_document_from_index_task import remove_document_from_index_task
  85. from tasks.retry_document_indexing_task import retry_document_indexing_task
  86. from tasks.sync_website_document_indexing_task import sync_website_document_indexing_task
  87. logger = logging.getLogger(__name__)
  88. class DatasetService:
  89. @staticmethod
  90. def get_datasets(page, per_page, tenant_id=None, user=None, search=None, tag_ids=None, include_all=False):
  91. query = select(Dataset).where(Dataset.tenant_id == tenant_id).order_by(Dataset.created_at.desc())
  92. if user:
  93. # get permitted dataset ids
  94. dataset_permission = (
  95. db.session.query(DatasetPermission).filter_by(account_id=user.id, tenant_id=tenant_id).all()
  96. )
  97. permitted_dataset_ids = {dp.dataset_id for dp in dataset_permission} if dataset_permission else None
  98. if user.current_role == TenantAccountRole.DATASET_OPERATOR:
  99. # only show datasets that the user has permission to access
  100. # Check if permitted_dataset_ids is not empty to avoid WHERE false condition
  101. if permitted_dataset_ids and len(permitted_dataset_ids) > 0:
  102. query = query.where(Dataset.id.in_(permitted_dataset_ids))
  103. else:
  104. return [], 0
  105. else:
  106. if user.current_role != TenantAccountRole.OWNER or not include_all:
  107. # show all datasets that the user has permission to access
  108. # Check if permitted_dataset_ids is not empty to avoid WHERE false condition
  109. if permitted_dataset_ids and len(permitted_dataset_ids) > 0:
  110. query = query.where(
  111. sa.or_(
  112. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  113. sa.and_(
  114. Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id
  115. ),
  116. sa.and_(
  117. Dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM,
  118. Dataset.id.in_(permitted_dataset_ids),
  119. ),
  120. )
  121. )
  122. else:
  123. query = query.where(
  124. sa.or_(
  125. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  126. sa.and_(
  127. Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id
  128. ),
  129. )
  130. )
  131. else:
  132. # if no user, only show datasets that are shared with all team members
  133. query = query.where(Dataset.permission == DatasetPermissionEnum.ALL_TEAM)
  134. if search:
  135. query = query.where(Dataset.name.ilike(f"%{search}%"))
  136. # Check if tag_ids is not empty to avoid WHERE false condition
  137. if tag_ids and len(tag_ids) > 0:
  138. if tenant_id is not None:
  139. target_ids = TagService.get_target_ids_by_tag_ids(
  140. "knowledge",
  141. tenant_id,
  142. tag_ids,
  143. )
  144. else:
  145. target_ids = []
  146. if target_ids and len(target_ids) > 0:
  147. query = query.where(Dataset.id.in_(target_ids))
  148. else:
  149. return [], 0
  150. datasets = db.paginate(select=query, page=page, per_page=per_page, max_per_page=100, error_out=False)
  151. return datasets.items, datasets.total
  152. @staticmethod
  153. def get_process_rules(dataset_id):
  154. # get the latest process rule
  155. dataset_process_rule = (
  156. db.session.query(DatasetProcessRule)
  157. .where(DatasetProcessRule.dataset_id == dataset_id)
  158. .order_by(DatasetProcessRule.created_at.desc())
  159. .limit(1)
  160. .one_or_none()
  161. )
  162. if dataset_process_rule:
  163. mode = dataset_process_rule.mode
  164. rules = dataset_process_rule.rules_dict
  165. else:
  166. mode = DocumentService.DEFAULT_RULES["mode"]
  167. rules = DocumentService.DEFAULT_RULES["rules"]
  168. return {"mode": mode, "rules": rules}
  169. @staticmethod
  170. def get_datasets_by_ids(ids, tenant_id):
  171. # Check if ids is not empty to avoid WHERE false condition
  172. if not ids or len(ids) == 0:
  173. return [], 0
  174. stmt = select(Dataset).where(Dataset.id.in_(ids), Dataset.tenant_id == tenant_id)
  175. datasets = db.paginate(select=stmt, page=1, per_page=len(ids), max_per_page=len(ids), error_out=False)
  176. return datasets.items, datasets.total
  177. @staticmethod
  178. def create_empty_dataset(
  179. tenant_id: str,
  180. name: str,
  181. description: str | None,
  182. indexing_technique: str | None,
  183. account: Account,
  184. permission: str | None = None,
  185. provider: str = "vendor",
  186. external_knowledge_api_id: str | None = None,
  187. external_knowledge_id: str | None = None,
  188. embedding_model_provider: str | None = None,
  189. embedding_model_name: str | None = None,
  190. retrieval_model: RetrievalModel | None = None,
  191. ):
  192. # check if dataset name already exists
  193. if db.session.query(Dataset).filter_by(name=name, tenant_id=tenant_id).first():
  194. raise DatasetNameDuplicateError(f"Dataset with name {name} already exists.")
  195. embedding_model = None
  196. if indexing_technique == "high_quality":
  197. model_manager = ModelManager()
  198. if embedding_model_provider and embedding_model_name:
  199. # check if embedding model setting is valid
  200. DatasetService.check_embedding_model_setting(tenant_id, embedding_model_provider, embedding_model_name)
  201. embedding_model = model_manager.get_model_instance(
  202. tenant_id=tenant_id,
  203. provider=embedding_model_provider,
  204. model_type=ModelType.TEXT_EMBEDDING,
  205. model=embedding_model_name,
  206. )
  207. else:
  208. embedding_model = model_manager.get_default_model_instance(
  209. tenant_id=tenant_id, model_type=ModelType.TEXT_EMBEDDING
  210. )
  211. if retrieval_model and retrieval_model.reranking_model:
  212. if (
  213. retrieval_model.reranking_model.reranking_provider_name
  214. and retrieval_model.reranking_model.reranking_model_name
  215. ):
  216. # check if reranking model setting is valid
  217. DatasetService.check_reranking_model_setting(
  218. tenant_id,
  219. retrieval_model.reranking_model.reranking_provider_name,
  220. retrieval_model.reranking_model.reranking_model_name,
  221. )
  222. dataset = Dataset(name=name, indexing_technique=indexing_technique)
  223. # dataset = Dataset(name=name, provider=provider, config=config)
  224. dataset.description = description
  225. dataset.created_by = account.id
  226. dataset.updated_by = account.id
  227. dataset.tenant_id = tenant_id
  228. dataset.embedding_model_provider = embedding_model.provider if embedding_model else None # type: ignore
  229. dataset.embedding_model = embedding_model.model if embedding_model else None # type: ignore
  230. dataset.retrieval_model = retrieval_model.model_dump() if retrieval_model else None # type: ignore
  231. dataset.permission = permission or DatasetPermissionEnum.ONLY_ME
  232. dataset.provider = provider
  233. db.session.add(dataset)
  234. db.session.flush()
  235. if provider == "external" and external_knowledge_api_id:
  236. external_knowledge_api = ExternalDatasetService.get_external_knowledge_api(external_knowledge_api_id)
  237. if not external_knowledge_api:
  238. raise ValueError("External API template not found.")
  239. external_knowledge_binding = ExternalKnowledgeBindings(
  240. tenant_id=tenant_id,
  241. dataset_id=dataset.id,
  242. external_knowledge_api_id=external_knowledge_api_id,
  243. external_knowledge_id=external_knowledge_id,
  244. created_by=account.id,
  245. )
  246. db.session.add(external_knowledge_binding)
  247. db.session.commit()
  248. return dataset
  249. @staticmethod
  250. def create_empty_rag_pipeline_dataset(
  251. tenant_id: str,
  252. rag_pipeline_dataset_create_entity: RagPipelineDatasetCreateEntity,
  253. ):
  254. if rag_pipeline_dataset_create_entity.name:
  255. # check if dataset name already exists
  256. if (
  257. db.session.query(Dataset)
  258. .filter_by(name=rag_pipeline_dataset_create_entity.name, tenant_id=tenant_id)
  259. .first()
  260. ):
  261. raise DatasetNameDuplicateError(
  262. f"Dataset with name {rag_pipeline_dataset_create_entity.name} already exists."
  263. )
  264. else:
  265. # generate a random name as Untitled 1 2 3 ...
  266. datasets = db.session.query(Dataset).filter_by(tenant_id=tenant_id).all()
  267. names = [dataset.name for dataset in datasets]
  268. rag_pipeline_dataset_create_entity.name = generate_incremental_name(
  269. names,
  270. "Untitled",
  271. )
  272. if not current_user or not current_user.id:
  273. raise ValueError("Current user or current user id not found")
  274. pipeline = Pipeline(
  275. tenant_id=tenant_id,
  276. name=rag_pipeline_dataset_create_entity.name,
  277. description=rag_pipeline_dataset_create_entity.description,
  278. created_by=current_user.id,
  279. )
  280. db.session.add(pipeline)
  281. db.session.flush()
  282. dataset = Dataset(
  283. tenant_id=tenant_id,
  284. name=rag_pipeline_dataset_create_entity.name,
  285. description=rag_pipeline_dataset_create_entity.description,
  286. permission=rag_pipeline_dataset_create_entity.permission,
  287. provider="vendor",
  288. runtime_mode="rag_pipeline",
  289. icon_info=rag_pipeline_dataset_create_entity.icon_info.model_dump(),
  290. created_by=current_user.id,
  291. pipeline_id=pipeline.id,
  292. )
  293. db.session.add(dataset)
  294. db.session.commit()
  295. return dataset
  296. @staticmethod
  297. def get_dataset(dataset_id) -> Dataset | None:
  298. dataset: Dataset | None = db.session.query(Dataset).filter_by(id=dataset_id).first()
  299. return dataset
  300. @staticmethod
  301. def check_doc_form(dataset: Dataset, doc_form: str):
  302. if dataset.doc_form and doc_form != dataset.doc_form:
  303. raise ValueError("doc_form is different from the dataset doc_form.")
  304. @staticmethod
  305. def check_dataset_model_setting(dataset):
  306. if dataset.indexing_technique == "high_quality":
  307. try:
  308. model_manager = ModelManager()
  309. model_manager.get_model_instance(
  310. tenant_id=dataset.tenant_id,
  311. provider=dataset.embedding_model_provider,
  312. model_type=ModelType.TEXT_EMBEDDING,
  313. model=dataset.embedding_model,
  314. )
  315. except LLMBadRequestError:
  316. raise ValueError(
  317. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  318. )
  319. except ProviderTokenNotInitError as ex:
  320. raise ValueError(f"The dataset is unavailable, due to: {ex.description}")
  321. @staticmethod
  322. def check_embedding_model_setting(tenant_id: str, embedding_model_provider: str, embedding_model: str):
  323. try:
  324. model_manager = ModelManager()
  325. model_manager.get_model_instance(
  326. tenant_id=tenant_id,
  327. provider=embedding_model_provider,
  328. model_type=ModelType.TEXT_EMBEDDING,
  329. model=embedding_model,
  330. )
  331. except LLMBadRequestError:
  332. raise ValueError(
  333. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  334. )
  335. except ProviderTokenNotInitError as ex:
  336. raise ValueError(ex.description)
  337. @staticmethod
  338. def check_reranking_model_setting(tenant_id: str, reranking_model_provider: str, reranking_model: str):
  339. try:
  340. model_manager = ModelManager()
  341. model_manager.get_model_instance(
  342. tenant_id=tenant_id,
  343. provider=reranking_model_provider,
  344. model_type=ModelType.RERANK,
  345. model=reranking_model,
  346. )
  347. except LLMBadRequestError:
  348. raise ValueError(
  349. "No Rerank Model available. Please configure a valid provider in the Settings -> Model Provider."
  350. )
  351. except ProviderTokenNotInitError as ex:
  352. raise ValueError(ex.description)
  353. @staticmethod
  354. def update_dataset(dataset_id, data, user):
  355. """
  356. Update dataset configuration and settings.
  357. Args:
  358. dataset_id: The unique identifier of the dataset to update
  359. data: Dictionary containing the update data
  360. user: The user performing the update operation
  361. Returns:
  362. Dataset: The updated dataset object
  363. Raises:
  364. ValueError: If dataset not found or validation fails
  365. NoPermissionError: If user lacks permission to update the dataset
  366. """
  367. # Retrieve and validate dataset existence
  368. dataset = DatasetService.get_dataset(dataset_id)
  369. if not dataset:
  370. raise ValueError("Dataset not found")
  371. # check if dataset name is exists
  372. if DatasetService._has_dataset_same_name(
  373. tenant_id=dataset.tenant_id,
  374. dataset_id=dataset_id,
  375. name=data.get("name", dataset.name),
  376. ):
  377. raise ValueError("Dataset name already exists")
  378. # Verify user has permission to update this dataset
  379. DatasetService.check_dataset_permission(dataset, user)
  380. # Handle external dataset updates
  381. if dataset.provider == "external":
  382. return DatasetService._update_external_dataset(dataset, data, user)
  383. else:
  384. return DatasetService._update_internal_dataset(dataset, data, user)
  385. @staticmethod
  386. def _has_dataset_same_name(tenant_id: str, dataset_id: str, name: str):
  387. dataset = (
  388. db.session.query(Dataset)
  389. .where(
  390. Dataset.id != dataset_id,
  391. Dataset.name == name,
  392. Dataset.tenant_id == tenant_id,
  393. )
  394. .first()
  395. )
  396. return dataset is not None
  397. @staticmethod
  398. def _update_external_dataset(dataset, data, user):
  399. """
  400. Update external dataset configuration.
  401. Args:
  402. dataset: The dataset object to update
  403. data: Update data dictionary
  404. user: User performing the update
  405. Returns:
  406. Dataset: Updated dataset object
  407. """
  408. # Update retrieval model if provided
  409. external_retrieval_model = data.get("external_retrieval_model", None)
  410. if external_retrieval_model:
  411. dataset.retrieval_model = external_retrieval_model
  412. # Update basic dataset properties
  413. dataset.name = data.get("name", dataset.name)
  414. dataset.description = data.get("description", dataset.description)
  415. # Update permission if provided
  416. permission = data.get("permission")
  417. if permission:
  418. dataset.permission = permission
  419. # Validate and update external knowledge configuration
  420. external_knowledge_id = data.get("external_knowledge_id", None)
  421. external_knowledge_api_id = data.get("external_knowledge_api_id", None)
  422. if not external_knowledge_id:
  423. raise ValueError("External knowledge id is required.")
  424. if not external_knowledge_api_id:
  425. raise ValueError("External knowledge api id is required.")
  426. # Update metadata fields
  427. dataset.updated_by = user.id if user else None
  428. dataset.updated_at = naive_utc_now()
  429. db.session.add(dataset)
  430. # Update external knowledge binding
  431. DatasetService._update_external_knowledge_binding(dataset.id, external_knowledge_id, external_knowledge_api_id)
  432. # Commit changes to database
  433. db.session.commit()
  434. return dataset
  435. @staticmethod
  436. def _update_external_knowledge_binding(dataset_id, external_knowledge_id, external_knowledge_api_id):
  437. """
  438. Update external knowledge binding configuration.
  439. Args:
  440. dataset_id: Dataset identifier
  441. external_knowledge_id: External knowledge identifier
  442. external_knowledge_api_id: External knowledge API identifier
  443. """
  444. with Session(db.engine) as session:
  445. external_knowledge_binding = (
  446. session.query(ExternalKnowledgeBindings).filter_by(dataset_id=dataset_id).first()
  447. )
  448. if not external_knowledge_binding:
  449. raise ValueError("External knowledge binding not found.")
  450. # Update binding if values have changed
  451. if (
  452. external_knowledge_binding.external_knowledge_id != external_knowledge_id
  453. or external_knowledge_binding.external_knowledge_api_id != external_knowledge_api_id
  454. ):
  455. external_knowledge_binding.external_knowledge_id = external_knowledge_id
  456. external_knowledge_binding.external_knowledge_api_id = external_knowledge_api_id
  457. db.session.add(external_knowledge_binding)
  458. @staticmethod
  459. def _update_internal_dataset(dataset, data, user):
  460. """
  461. Update internal dataset configuration.
  462. Args:
  463. dataset: The dataset object to update
  464. data: Update data dictionary
  465. user: User performing the update
  466. Returns:
  467. Dataset: Updated dataset object
  468. """
  469. # Remove external-specific fields from update data
  470. data.pop("partial_member_list", None)
  471. data.pop("external_knowledge_api_id", None)
  472. data.pop("external_knowledge_id", None)
  473. data.pop("external_retrieval_model", None)
  474. # Filter out None values except for description field
  475. filtered_data = {k: v for k, v in data.items() if v is not None or k == "description"}
  476. # Handle indexing technique changes and embedding model updates
  477. action = DatasetService._handle_indexing_technique_change(dataset, data, filtered_data)
  478. # Add metadata fields
  479. filtered_data["updated_by"] = user.id
  480. filtered_data["updated_at"] = naive_utc_now()
  481. # update Retrieval model
  482. if data.get("retrieval_model"):
  483. filtered_data["retrieval_model"] = data["retrieval_model"]
  484. # update icon info
  485. if data.get("icon_info"):
  486. filtered_data["icon_info"] = data.get("icon_info")
  487. # Update dataset in database
  488. db.session.query(Dataset).filter_by(id=dataset.id).update(filtered_data)
  489. db.session.commit()
  490. # update pipeline knowledge base node data
  491. DatasetService._update_pipeline_knowledge_base_node_data(dataset, user.id)
  492. # Trigger vector index task if indexing technique changed
  493. if action:
  494. deal_dataset_vector_index_task.delay(dataset.id, action)
  495. return dataset
  496. @staticmethod
  497. def _update_pipeline_knowledge_base_node_data(dataset: Dataset, updata_user_id: str):
  498. """
  499. Update pipeline knowledge base node data.
  500. """
  501. if dataset.runtime_mode != "rag_pipeline":
  502. return
  503. pipeline = db.session.query(Pipeline).filter_by(id=dataset.pipeline_id).first()
  504. if not pipeline:
  505. return
  506. try:
  507. rag_pipeline_service = RagPipelineService()
  508. published_workflow = rag_pipeline_service.get_published_workflow(pipeline)
  509. draft_workflow = rag_pipeline_service.get_draft_workflow(pipeline)
  510. # update knowledge nodes
  511. def update_knowledge_nodes(workflow_graph: str) -> str:
  512. """Update knowledge-index nodes in workflow graph."""
  513. data: dict[str, Any] = json.loads(workflow_graph)
  514. nodes = data.get("nodes", [])
  515. updated = False
  516. for node in nodes:
  517. if node.get("data", {}).get("type") == "knowledge-index":
  518. try:
  519. knowledge_index_node_data = node.get("data", {})
  520. knowledge_index_node_data["embedding_model"] = dataset.embedding_model
  521. knowledge_index_node_data["embedding_model_provider"] = dataset.embedding_model_provider
  522. knowledge_index_node_data["retrieval_model"] = dataset.retrieval_model
  523. knowledge_index_node_data["chunk_structure"] = dataset.chunk_structure
  524. knowledge_index_node_data["indexing_technique"] = dataset.indexing_technique # pyright: ignore[reportAttributeAccessIssue]
  525. knowledge_index_node_data["keyword_number"] = dataset.keyword_number
  526. node["data"] = knowledge_index_node_data
  527. updated = True
  528. except Exception:
  529. logging.exception("Failed to update knowledge node")
  530. continue
  531. if updated:
  532. data["nodes"] = nodes
  533. return json.dumps(data)
  534. return workflow_graph
  535. # Update published workflow
  536. if published_workflow:
  537. updated_graph = update_knowledge_nodes(published_workflow.graph)
  538. if updated_graph != published_workflow.graph:
  539. # Create new workflow version
  540. workflow = Workflow.new(
  541. tenant_id=pipeline.tenant_id,
  542. app_id=pipeline.id,
  543. type=published_workflow.type,
  544. version=str(datetime.datetime.now(datetime.UTC).replace(tzinfo=None)),
  545. graph=updated_graph,
  546. features=published_workflow.features,
  547. created_by=updata_user_id,
  548. environment_variables=published_workflow.environment_variables,
  549. conversation_variables=published_workflow.conversation_variables,
  550. rag_pipeline_variables=published_workflow.rag_pipeline_variables,
  551. marked_name="",
  552. marked_comment="",
  553. )
  554. db.session.add(workflow)
  555. # Update draft workflow
  556. if draft_workflow:
  557. updated_graph = update_knowledge_nodes(draft_workflow.graph)
  558. if updated_graph != draft_workflow.graph:
  559. draft_workflow.graph = updated_graph
  560. db.session.add(draft_workflow)
  561. # Commit all changes in one transaction
  562. db.session.commit()
  563. except Exception:
  564. logging.exception("Failed to update pipeline knowledge base node data")
  565. db.session.rollback()
  566. raise
  567. @staticmethod
  568. def _handle_indexing_technique_change(dataset, data, filtered_data):
  569. """
  570. Handle changes in indexing technique and configure embedding models accordingly.
  571. Args:
  572. dataset: Current dataset object
  573. data: Update data dictionary
  574. filtered_data: Filtered update data
  575. Returns:
  576. str: Action to perform ('add', 'remove', 'update', or None)
  577. """
  578. if dataset.indexing_technique != data["indexing_technique"]:
  579. if data["indexing_technique"] == "economy":
  580. # Remove embedding model configuration for economy mode
  581. filtered_data["embedding_model"] = None
  582. filtered_data["embedding_model_provider"] = None
  583. filtered_data["collection_binding_id"] = None
  584. return "remove"
  585. elif data["indexing_technique"] == "high_quality":
  586. # Configure embedding model for high quality mode
  587. DatasetService._configure_embedding_model_for_high_quality(data, filtered_data)
  588. return "add"
  589. else:
  590. # Handle embedding model updates when indexing technique remains the same
  591. return DatasetService._handle_embedding_model_update_when_technique_unchanged(dataset, data, filtered_data)
  592. return None
  593. @staticmethod
  594. def _configure_embedding_model_for_high_quality(data, filtered_data):
  595. """
  596. Configure embedding model settings for high quality indexing.
  597. Args:
  598. data: Update data dictionary
  599. filtered_data: Filtered update data to modify
  600. """
  601. # assert isinstance(current_user, Account) and current_user.current_tenant_id is not None
  602. try:
  603. model_manager = ModelManager()
  604. assert isinstance(current_user, Account)
  605. assert current_user.current_tenant_id is not None
  606. embedding_model = model_manager.get_model_instance(
  607. tenant_id=current_user.current_tenant_id,
  608. provider=data["embedding_model_provider"],
  609. model_type=ModelType.TEXT_EMBEDDING,
  610. model=data["embedding_model"],
  611. )
  612. filtered_data["embedding_model"] = embedding_model.model
  613. filtered_data["embedding_model_provider"] = embedding_model.provider
  614. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  615. embedding_model.provider, embedding_model.model
  616. )
  617. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  618. except LLMBadRequestError:
  619. raise ValueError(
  620. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  621. )
  622. except ProviderTokenNotInitError as ex:
  623. raise ValueError(ex.description)
  624. @staticmethod
  625. def _handle_embedding_model_update_when_technique_unchanged(dataset, data, filtered_data):
  626. """
  627. Handle embedding model updates when indexing technique remains the same.
  628. Args:
  629. dataset: Current dataset object
  630. data: Update data dictionary
  631. filtered_data: Filtered update data to modify
  632. Returns:
  633. str: Action to perform ('update' or None)
  634. """
  635. # Skip embedding model checks if not provided in the update request
  636. if (
  637. "embedding_model_provider" not in data
  638. or "embedding_model" not in data
  639. or not data.get("embedding_model_provider")
  640. or not data.get("embedding_model")
  641. ):
  642. DatasetService._preserve_existing_embedding_settings(dataset, filtered_data)
  643. return None
  644. else:
  645. return DatasetService._update_embedding_model_settings(dataset, data, filtered_data)
  646. @staticmethod
  647. def _preserve_existing_embedding_settings(dataset, filtered_data):
  648. """
  649. Preserve existing embedding model settings when not provided in update.
  650. Args:
  651. dataset: Current dataset object
  652. filtered_data: Filtered update data to modify
  653. """
  654. # If the dataset already has embedding model settings, use those
  655. if dataset.embedding_model_provider and dataset.embedding_model:
  656. filtered_data["embedding_model_provider"] = dataset.embedding_model_provider
  657. filtered_data["embedding_model"] = dataset.embedding_model
  658. # If collection_binding_id exists, keep it too
  659. if dataset.collection_binding_id:
  660. filtered_data["collection_binding_id"] = dataset.collection_binding_id
  661. # Otherwise, don't try to update embedding model settings at all
  662. # Remove these fields from filtered_data if they exist but are None/empty
  663. if "embedding_model_provider" in filtered_data and not filtered_data["embedding_model_provider"]:
  664. del filtered_data["embedding_model_provider"]
  665. if "embedding_model" in filtered_data and not filtered_data["embedding_model"]:
  666. del filtered_data["embedding_model"]
  667. @staticmethod
  668. def _update_embedding_model_settings(dataset, data, filtered_data):
  669. """
  670. Update embedding model settings with new values.
  671. Args:
  672. dataset: Current dataset object
  673. data: Update data dictionary
  674. filtered_data: Filtered update data to modify
  675. Returns:
  676. str: Action to perform ('update' or None)
  677. """
  678. try:
  679. # Compare current and new model provider settings
  680. current_provider_str = (
  681. str(ModelProviderID(dataset.embedding_model_provider)) if dataset.embedding_model_provider else None
  682. )
  683. new_provider_str = (
  684. str(ModelProviderID(data["embedding_model_provider"])) if data["embedding_model_provider"] else None
  685. )
  686. # Only update if values are different
  687. if current_provider_str != new_provider_str or data["embedding_model"] != dataset.embedding_model:
  688. DatasetService._apply_new_embedding_settings(dataset, data, filtered_data)
  689. return "update"
  690. except LLMBadRequestError:
  691. raise ValueError(
  692. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  693. )
  694. except ProviderTokenNotInitError as ex:
  695. raise ValueError(ex.description)
  696. return None
  697. @staticmethod
  698. def _apply_new_embedding_settings(dataset, data, filtered_data):
  699. """
  700. Apply new embedding model settings to the dataset.
  701. Args:
  702. dataset: Current dataset object
  703. data: Update data dictionary
  704. filtered_data: Filtered update data to modify
  705. """
  706. # assert isinstance(current_user, Account) and current_user.current_tenant_id is not None
  707. model_manager = ModelManager()
  708. try:
  709. assert isinstance(current_user, Account)
  710. assert current_user.current_tenant_id is not None
  711. embedding_model = model_manager.get_model_instance(
  712. tenant_id=current_user.current_tenant_id,
  713. provider=data["embedding_model_provider"],
  714. model_type=ModelType.TEXT_EMBEDDING,
  715. model=data["embedding_model"],
  716. )
  717. except ProviderTokenNotInitError:
  718. # If we can't get the embedding model, preserve existing settings
  719. logger.warning(
  720. "Failed to initialize embedding model %s/%s, preserving existing settings",
  721. data["embedding_model_provider"],
  722. data["embedding_model"],
  723. )
  724. if dataset.embedding_model_provider and dataset.embedding_model:
  725. filtered_data["embedding_model_provider"] = dataset.embedding_model_provider
  726. filtered_data["embedding_model"] = dataset.embedding_model
  727. if dataset.collection_binding_id:
  728. filtered_data["collection_binding_id"] = dataset.collection_binding_id
  729. # Skip the rest of the embedding model update
  730. return
  731. # Apply new embedding model settings
  732. filtered_data["embedding_model"] = embedding_model.model
  733. filtered_data["embedding_model_provider"] = embedding_model.provider
  734. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  735. embedding_model.provider, embedding_model.model
  736. )
  737. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  738. @staticmethod
  739. def update_rag_pipeline_dataset_settings(
  740. session: Session, dataset: Dataset, knowledge_configuration: KnowledgeConfiguration, has_published: bool = False
  741. ):
  742. if not current_user or not current_user.current_tenant_id:
  743. raise ValueError("Current user or current tenant not found")
  744. dataset = session.merge(dataset)
  745. if not has_published:
  746. dataset.chunk_structure = knowledge_configuration.chunk_structure
  747. dataset.indexing_technique = knowledge_configuration.indexing_technique
  748. if knowledge_configuration.indexing_technique == "high_quality":
  749. model_manager = ModelManager()
  750. embedding_model = model_manager.get_model_instance(
  751. tenant_id=current_user.current_tenant_id, # ignore type error
  752. provider=knowledge_configuration.embedding_model_provider or "",
  753. model_type=ModelType.TEXT_EMBEDDING,
  754. model=knowledge_configuration.embedding_model or "",
  755. )
  756. dataset.embedding_model = embedding_model.model
  757. dataset.embedding_model_provider = embedding_model.provider
  758. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  759. embedding_model.provider, embedding_model.model
  760. )
  761. dataset.collection_binding_id = dataset_collection_binding.id
  762. elif knowledge_configuration.indexing_technique == "economy":
  763. dataset.keyword_number = knowledge_configuration.keyword_number
  764. else:
  765. raise ValueError("Invalid index method")
  766. dataset.retrieval_model = knowledge_configuration.retrieval_model.model_dump()
  767. session.add(dataset)
  768. else:
  769. if dataset.chunk_structure and dataset.chunk_structure != knowledge_configuration.chunk_structure:
  770. raise ValueError("Chunk structure is not allowed to be updated.")
  771. action = None
  772. if dataset.indexing_technique != knowledge_configuration.indexing_technique:
  773. # if update indexing_technique
  774. if knowledge_configuration.indexing_technique == "economy":
  775. raise ValueError("Knowledge base indexing technique is not allowed to be updated to economy.")
  776. elif knowledge_configuration.indexing_technique == "high_quality":
  777. action = "add"
  778. # get embedding model setting
  779. try:
  780. model_manager = ModelManager()
  781. embedding_model = model_manager.get_model_instance(
  782. tenant_id=current_user.current_tenant_id,
  783. provider=knowledge_configuration.embedding_model_provider,
  784. model_type=ModelType.TEXT_EMBEDDING,
  785. model=knowledge_configuration.embedding_model,
  786. )
  787. dataset.embedding_model = embedding_model.model
  788. dataset.embedding_model_provider = embedding_model.provider
  789. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  790. embedding_model.provider, embedding_model.model
  791. )
  792. dataset.collection_binding_id = dataset_collection_binding.id
  793. dataset.indexing_technique = knowledge_configuration.indexing_technique
  794. except LLMBadRequestError:
  795. raise ValueError(
  796. "No Embedding Model available. Please configure a valid provider "
  797. "in the Settings -> Model Provider."
  798. )
  799. except ProviderTokenNotInitError as ex:
  800. raise ValueError(ex.description)
  801. else:
  802. # add default plugin id to both setting sets, to make sure the plugin model provider is consistent
  803. # Skip embedding model checks if not provided in the update request
  804. if dataset.indexing_technique == "high_quality":
  805. skip_embedding_update = False
  806. try:
  807. # Handle existing model provider
  808. plugin_model_provider = dataset.embedding_model_provider
  809. plugin_model_provider_str = None
  810. if plugin_model_provider:
  811. plugin_model_provider_str = str(ModelProviderID(plugin_model_provider))
  812. # Handle new model provider from request
  813. new_plugin_model_provider = knowledge_configuration.embedding_model_provider
  814. new_plugin_model_provider_str = None
  815. if new_plugin_model_provider:
  816. new_plugin_model_provider_str = str(ModelProviderID(new_plugin_model_provider))
  817. # Only update embedding model if both values are provided and different from current
  818. if (
  819. plugin_model_provider_str != new_plugin_model_provider_str
  820. or knowledge_configuration.embedding_model != dataset.embedding_model
  821. ):
  822. action = "update"
  823. model_manager = ModelManager()
  824. embedding_model = None
  825. try:
  826. embedding_model = model_manager.get_model_instance(
  827. tenant_id=current_user.current_tenant_id,
  828. provider=knowledge_configuration.embedding_model_provider,
  829. model_type=ModelType.TEXT_EMBEDDING,
  830. model=knowledge_configuration.embedding_model,
  831. )
  832. except ProviderTokenNotInitError:
  833. # If we can't get the embedding model, skip updating it
  834. # and keep the existing settings if available
  835. # Skip the rest of the embedding model update
  836. skip_embedding_update = True
  837. if not skip_embedding_update:
  838. if embedding_model:
  839. dataset.embedding_model = embedding_model.model
  840. dataset.embedding_model_provider = embedding_model.provider
  841. dataset_collection_binding = (
  842. DatasetCollectionBindingService.get_dataset_collection_binding(
  843. embedding_model.provider, embedding_model.model
  844. )
  845. )
  846. dataset.collection_binding_id = dataset_collection_binding.id
  847. except LLMBadRequestError:
  848. raise ValueError(
  849. "No Embedding Model available. Please configure a valid provider "
  850. "in the Settings -> Model Provider."
  851. )
  852. except ProviderTokenNotInitError as ex:
  853. raise ValueError(ex.description)
  854. elif dataset.indexing_technique == "economy":
  855. if dataset.keyword_number != knowledge_configuration.keyword_number:
  856. dataset.keyword_number = knowledge_configuration.keyword_number
  857. dataset.retrieval_model = knowledge_configuration.retrieval_model.model_dump()
  858. session.add(dataset)
  859. session.commit()
  860. if action:
  861. deal_dataset_index_update_task.delay(dataset.id, action)
  862. @staticmethod
  863. def delete_dataset(dataset_id, user):
  864. dataset = DatasetService.get_dataset(dataset_id)
  865. if dataset is None:
  866. return False
  867. DatasetService.check_dataset_permission(dataset, user)
  868. dataset_was_deleted.send(dataset)
  869. db.session.delete(dataset)
  870. db.session.commit()
  871. return True
  872. @staticmethod
  873. def dataset_use_check(dataset_id) -> bool:
  874. stmt = select(exists().where(AppDatasetJoin.dataset_id == dataset_id))
  875. return db.session.execute(stmt).scalar_one()
  876. @staticmethod
  877. def check_dataset_permission(dataset, user):
  878. if dataset.tenant_id != user.current_tenant_id:
  879. logger.debug("User %s does not have permission to access dataset %s", user.id, dataset.id)
  880. raise NoPermissionError("You do not have permission to access this dataset.")
  881. if user.current_role != TenantAccountRole.OWNER:
  882. if dataset.permission == DatasetPermissionEnum.ONLY_ME and dataset.created_by != user.id:
  883. logger.debug("User %s does not have permission to access dataset %s", user.id, dataset.id)
  884. raise NoPermissionError("You do not have permission to access this dataset.")
  885. if dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:
  886. # For partial team permission, user needs explicit permission or be the creator
  887. if dataset.created_by != user.id:
  888. user_permission = (
  889. db.session.query(DatasetPermission).filter_by(dataset_id=dataset.id, account_id=user.id).first()
  890. )
  891. if not user_permission:
  892. logger.debug("User %s does not have permission to access dataset %s", user.id, dataset.id)
  893. raise NoPermissionError("You do not have permission to access this dataset.")
  894. @staticmethod
  895. def check_dataset_operator_permission(user: Account | None = None, dataset: Dataset | None = None):
  896. if not dataset:
  897. raise ValueError("Dataset not found")
  898. if not user:
  899. raise ValueError("User not found")
  900. if user.current_role != TenantAccountRole.OWNER:
  901. if dataset.permission == DatasetPermissionEnum.ONLY_ME:
  902. if dataset.created_by != user.id:
  903. raise NoPermissionError("You do not have permission to access this dataset.")
  904. elif dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:
  905. if not any(
  906. dp.dataset_id == dataset.id
  907. for dp in db.session.query(DatasetPermission).filter_by(account_id=user.id).all()
  908. ):
  909. raise NoPermissionError("You do not have permission to access this dataset.")
  910. @staticmethod
  911. def get_dataset_queries(dataset_id: str, page: int, per_page: int):
  912. stmt = select(DatasetQuery).filter_by(dataset_id=dataset_id).order_by(db.desc(DatasetQuery.created_at))
  913. dataset_queries = db.paginate(select=stmt, page=page, per_page=per_page, max_per_page=100, error_out=False)
  914. return dataset_queries.items, dataset_queries.total
  915. @staticmethod
  916. def get_related_apps(dataset_id: str):
  917. return (
  918. db.session.query(AppDatasetJoin)
  919. .where(AppDatasetJoin.dataset_id == dataset_id)
  920. .order_by(db.desc(AppDatasetJoin.created_at))
  921. .all()
  922. )
  923. @staticmethod
  924. def update_dataset_api_status(dataset_id: str, status: bool):
  925. dataset = DatasetService.get_dataset(dataset_id)
  926. if dataset is None:
  927. raise NotFound("Dataset not found.")
  928. dataset.enable_api = status
  929. if not current_user or not current_user.id:
  930. raise ValueError("Current user or current user id not found")
  931. dataset.updated_by = current_user.id
  932. dataset.updated_at = naive_utc_now()
  933. db.session.commit()
  934. @staticmethod
  935. def get_dataset_auto_disable_logs(dataset_id: str):
  936. assert isinstance(current_user, Account)
  937. assert current_user.current_tenant_id is not None
  938. features = FeatureService.get_features(current_user.current_tenant_id)
  939. if not features.billing.enabled or features.billing.subscription.plan == "sandbox":
  940. return {
  941. "document_ids": [],
  942. "count": 0,
  943. }
  944. # get recent 30 days auto disable logs
  945. start_date = datetime.datetime.now() - datetime.timedelta(days=30)
  946. dataset_auto_disable_logs = db.session.scalars(
  947. select(DatasetAutoDisableLog).where(
  948. DatasetAutoDisableLog.dataset_id == dataset_id,
  949. DatasetAutoDisableLog.created_at >= start_date,
  950. )
  951. ).all()
  952. if dataset_auto_disable_logs:
  953. return {
  954. "document_ids": [log.document_id for log in dataset_auto_disable_logs],
  955. "count": len(dataset_auto_disable_logs),
  956. }
  957. return {
  958. "document_ids": [],
  959. "count": 0,
  960. }
  961. class DocumentService:
  962. DEFAULT_RULES: dict[str, Any] = {
  963. "mode": "custom",
  964. "rules": {
  965. "pre_processing_rules": [
  966. {"id": "remove_extra_spaces", "enabled": True},
  967. {"id": "remove_urls_emails", "enabled": False},
  968. ],
  969. "segmentation": {"delimiter": "\n", "max_tokens": 1024, "chunk_overlap": 50},
  970. },
  971. "limits": {
  972. "indexing_max_segmentation_tokens_length": dify_config.INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH,
  973. },
  974. }
  975. DOCUMENT_METADATA_SCHEMA: dict[str, Any] = {
  976. "book": {
  977. "title": str,
  978. "language": str,
  979. "author": str,
  980. "publisher": str,
  981. "publication_date": str,
  982. "isbn": str,
  983. "category": str,
  984. },
  985. "web_page": {
  986. "title": str,
  987. "url": str,
  988. "language": str,
  989. "publish_date": str,
  990. "author/publisher": str,
  991. "topic/keywords": str,
  992. "description": str,
  993. },
  994. "paper": {
  995. "title": str,
  996. "language": str,
  997. "author": str,
  998. "publish_date": str,
  999. "journal/conference_name": str,
  1000. "volume/issue/page_numbers": str,
  1001. "doi": str,
  1002. "topic/keywords": str,
  1003. "abstract": str,
  1004. },
  1005. "social_media_post": {
  1006. "platform": str,
  1007. "author/username": str,
  1008. "publish_date": str,
  1009. "post_url": str,
  1010. "topic/tags": str,
  1011. },
  1012. "wikipedia_entry": {
  1013. "title": str,
  1014. "language": str,
  1015. "web_page_url": str,
  1016. "last_edit_date": str,
  1017. "editor/contributor": str,
  1018. "summary/introduction": str,
  1019. },
  1020. "personal_document": {
  1021. "title": str,
  1022. "author": str,
  1023. "creation_date": str,
  1024. "last_modified_date": str,
  1025. "document_type": str,
  1026. "tags/category": str,
  1027. },
  1028. "business_document": {
  1029. "title": str,
  1030. "author": str,
  1031. "creation_date": str,
  1032. "last_modified_date": str,
  1033. "document_type": str,
  1034. "department/team": str,
  1035. },
  1036. "im_chat_log": {
  1037. "chat_platform": str,
  1038. "chat_participants/group_name": str,
  1039. "start_date": str,
  1040. "end_date": str,
  1041. "summary": str,
  1042. },
  1043. "synced_from_notion": {
  1044. "title": str,
  1045. "language": str,
  1046. "author/creator": str,
  1047. "creation_date": str,
  1048. "last_modified_date": str,
  1049. "notion_page_link": str,
  1050. "category/tags": str,
  1051. "description": str,
  1052. },
  1053. "synced_from_github": {
  1054. "repository_name": str,
  1055. "repository_description": str,
  1056. "repository_owner/organization": str,
  1057. "code_filename": str,
  1058. "code_file_path": str,
  1059. "programming_language": str,
  1060. "github_link": str,
  1061. "open_source_license": str,
  1062. "commit_date": str,
  1063. "commit_author": str,
  1064. },
  1065. "others": dict,
  1066. }
  1067. @staticmethod
  1068. def get_document(dataset_id: str, document_id: str | None = None) -> Document | None:
  1069. if document_id:
  1070. document = (
  1071. db.session.query(Document).where(Document.id == document_id, Document.dataset_id == dataset_id).first()
  1072. )
  1073. return document
  1074. else:
  1075. return None
  1076. @staticmethod
  1077. def get_document_by_id(document_id: str) -> Document | None:
  1078. document = db.session.query(Document).where(Document.id == document_id).first()
  1079. return document
  1080. @staticmethod
  1081. def get_document_by_ids(document_ids: list[str]) -> Sequence[Document]:
  1082. documents = db.session.scalars(
  1083. select(Document).where(
  1084. Document.id.in_(document_ids),
  1085. Document.enabled == True,
  1086. Document.indexing_status == "completed",
  1087. Document.archived == False,
  1088. )
  1089. ).all()
  1090. return documents
  1091. @staticmethod
  1092. def get_document_by_dataset_id(dataset_id: str) -> Sequence[Document]:
  1093. documents = db.session.scalars(
  1094. select(Document).where(
  1095. Document.dataset_id == dataset_id,
  1096. Document.enabled == True,
  1097. )
  1098. ).all()
  1099. return documents
  1100. @staticmethod
  1101. def get_working_documents_by_dataset_id(dataset_id: str) -> Sequence[Document]:
  1102. documents = db.session.scalars(
  1103. select(Document).where(
  1104. Document.dataset_id == dataset_id,
  1105. Document.enabled == True,
  1106. Document.indexing_status == "completed",
  1107. Document.archived == False,
  1108. )
  1109. ).all()
  1110. return documents
  1111. @staticmethod
  1112. def get_error_documents_by_dataset_id(dataset_id: str) -> Sequence[Document]:
  1113. documents = db.session.scalars(
  1114. select(Document).where(Document.dataset_id == dataset_id, Document.indexing_status.in_(["error", "paused"]))
  1115. ).all()
  1116. return documents
  1117. @staticmethod
  1118. def get_batch_documents(dataset_id: str, batch: str) -> Sequence[Document]:
  1119. assert isinstance(current_user, Account)
  1120. documents = db.session.scalars(
  1121. select(Document).where(
  1122. Document.batch == batch,
  1123. Document.dataset_id == dataset_id,
  1124. Document.tenant_id == current_user.current_tenant_id,
  1125. )
  1126. ).all()
  1127. return documents
  1128. @staticmethod
  1129. def get_document_file_detail(file_id: str):
  1130. file_detail = db.session.query(UploadFile).where(UploadFile.id == file_id).one_or_none()
  1131. return file_detail
  1132. @staticmethod
  1133. def check_archived(document):
  1134. if document.archived:
  1135. return True
  1136. else:
  1137. return False
  1138. @staticmethod
  1139. def delete_document(document):
  1140. # trigger document_was_deleted signal
  1141. file_id = None
  1142. if document.data_source_type == "upload_file":
  1143. if document.data_source_info:
  1144. data_source_info = document.data_source_info_dict
  1145. if data_source_info and "upload_file_id" in data_source_info:
  1146. file_id = data_source_info["upload_file_id"]
  1147. document_was_deleted.send(
  1148. document.id, dataset_id=document.dataset_id, doc_form=document.doc_form, file_id=file_id
  1149. )
  1150. db.session.delete(document)
  1151. db.session.commit()
  1152. @staticmethod
  1153. def delete_documents(dataset: Dataset, document_ids: list[str]):
  1154. # Check if document_ids is not empty to avoid WHERE false condition
  1155. if not document_ids or len(document_ids) == 0:
  1156. return
  1157. documents = db.session.scalars(select(Document).where(Document.id.in_(document_ids))).all()
  1158. file_ids = [
  1159. document.data_source_info_dict.get("upload_file_id", "")
  1160. for document in documents
  1161. if document.data_source_type == "upload_file" and document.data_source_info_dict
  1162. ]
  1163. if dataset.doc_form is not None:
  1164. batch_clean_document_task.delay(document_ids, dataset.id, dataset.doc_form, file_ids)
  1165. for document in documents:
  1166. db.session.delete(document)
  1167. db.session.commit()
  1168. @staticmethod
  1169. def rename_document(dataset_id: str, document_id: str, name: str) -> Document:
  1170. assert isinstance(current_user, Account)
  1171. dataset = DatasetService.get_dataset(dataset_id)
  1172. if not dataset:
  1173. raise ValueError("Dataset not found.")
  1174. document = DocumentService.get_document(dataset_id, document_id)
  1175. if not document:
  1176. raise ValueError("Document not found.")
  1177. if document.tenant_id != current_user.current_tenant_id:
  1178. raise ValueError("No permission.")
  1179. if dataset.built_in_field_enabled:
  1180. if document.doc_metadata:
  1181. doc_metadata = copy.deepcopy(document.doc_metadata)
  1182. doc_metadata[BuiltInField.document_name] = name
  1183. document.doc_metadata = doc_metadata
  1184. document.name = name
  1185. db.session.add(document)
  1186. db.session.commit()
  1187. return document
  1188. @staticmethod
  1189. def pause_document(document):
  1190. if document.indexing_status not in {"waiting", "parsing", "cleaning", "splitting", "indexing"}:
  1191. raise DocumentIndexingError()
  1192. # update document to be paused
  1193. assert current_user is not None
  1194. document.is_paused = True
  1195. document.paused_by = current_user.id
  1196. document.paused_at = naive_utc_now()
  1197. db.session.add(document)
  1198. db.session.commit()
  1199. # set document paused flag
  1200. indexing_cache_key = f"document_{document.id}_is_paused"
  1201. redis_client.setnx(indexing_cache_key, "True")
  1202. @staticmethod
  1203. def recover_document(document):
  1204. if not document.is_paused:
  1205. raise DocumentIndexingError()
  1206. # update document to be recover
  1207. document.is_paused = False
  1208. document.paused_by = None
  1209. document.paused_at = None
  1210. db.session.add(document)
  1211. db.session.commit()
  1212. # delete paused flag
  1213. indexing_cache_key = f"document_{document.id}_is_paused"
  1214. redis_client.delete(indexing_cache_key)
  1215. # trigger async task
  1216. recover_document_indexing_task.delay(document.dataset_id, document.id)
  1217. @staticmethod
  1218. def retry_document(dataset_id: str, documents: list[Document]):
  1219. for document in documents:
  1220. # add retry flag
  1221. retry_indexing_cache_key = f"document_{document.id}_is_retried"
  1222. cache_result = redis_client.get(retry_indexing_cache_key)
  1223. if cache_result is not None:
  1224. raise ValueError("Document is being retried, please try again later")
  1225. # retry document indexing
  1226. document.indexing_status = "waiting"
  1227. db.session.add(document)
  1228. db.session.commit()
  1229. redis_client.setex(retry_indexing_cache_key, 600, 1)
  1230. # trigger async task
  1231. document_ids = [document.id for document in documents]
  1232. if not current_user or not current_user.id:
  1233. raise ValueError("Current user or current user id not found")
  1234. retry_document_indexing_task.delay(dataset_id, document_ids, current_user.id)
  1235. @staticmethod
  1236. def sync_website_document(dataset_id: str, document: Document):
  1237. # add sync flag
  1238. sync_indexing_cache_key = f"document_{document.id}_is_sync"
  1239. cache_result = redis_client.get(sync_indexing_cache_key)
  1240. if cache_result is not None:
  1241. raise ValueError("Document is being synced, please try again later")
  1242. # sync document indexing
  1243. document.indexing_status = "waiting"
  1244. data_source_info = document.data_source_info_dict
  1245. if data_source_info:
  1246. data_source_info["mode"] = "scrape"
  1247. document.data_source_info = json.dumps(data_source_info, ensure_ascii=False)
  1248. db.session.add(document)
  1249. db.session.commit()
  1250. redis_client.setex(sync_indexing_cache_key, 600, 1)
  1251. sync_website_document_indexing_task.delay(dataset_id, document.id)
  1252. @staticmethod
  1253. def get_documents_position(dataset_id):
  1254. document = (
  1255. db.session.query(Document).filter_by(dataset_id=dataset_id).order_by(Document.position.desc()).first()
  1256. )
  1257. if document:
  1258. return document.position + 1
  1259. else:
  1260. return 1
  1261. @staticmethod
  1262. def save_document_with_dataset_id(
  1263. dataset: Dataset,
  1264. knowledge_config: KnowledgeConfig,
  1265. account: Account | Any,
  1266. dataset_process_rule: DatasetProcessRule | None = None,
  1267. created_from: str = "web",
  1268. ) -> tuple[list[Document], str]:
  1269. # check doc_form
  1270. DatasetService.check_doc_form(dataset, knowledge_config.doc_form)
  1271. # check document limit
  1272. assert isinstance(current_user, Account)
  1273. assert current_user.current_tenant_id is not None
  1274. features = FeatureService.get_features(current_user.current_tenant_id)
  1275. if features.billing.enabled:
  1276. if not knowledge_config.original_document_id:
  1277. count = 0
  1278. if knowledge_config.data_source:
  1279. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  1280. upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  1281. count = len(upload_file_list)
  1282. elif knowledge_config.data_source.info_list.data_source_type == "notion_import":
  1283. notion_info_list = knowledge_config.data_source.info_list.notion_info_list
  1284. for notion_info in notion_info_list: # type: ignore
  1285. count = count + len(notion_info.pages)
  1286. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  1287. website_info = knowledge_config.data_source.info_list.website_info_list
  1288. count = len(website_info.urls) # type: ignore
  1289. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  1290. if features.billing.subscription.plan == "sandbox" and count > 1:
  1291. raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
  1292. if count > batch_upload_limit:
  1293. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  1294. DocumentService.check_documents_upload_quota(count, features)
  1295. # if dataset is empty, update dataset data_source_type
  1296. if not dataset.data_source_type:
  1297. dataset.data_source_type = knowledge_config.data_source.info_list.data_source_type # type: ignore
  1298. if not dataset.indexing_technique:
  1299. if knowledge_config.indexing_technique not in Dataset.INDEXING_TECHNIQUE_LIST:
  1300. raise ValueError("Indexing technique is invalid")
  1301. dataset.indexing_technique = knowledge_config.indexing_technique
  1302. if knowledge_config.indexing_technique == "high_quality":
  1303. model_manager = ModelManager()
  1304. if knowledge_config.embedding_model and knowledge_config.embedding_model_provider:
  1305. dataset_embedding_model = knowledge_config.embedding_model
  1306. dataset_embedding_model_provider = knowledge_config.embedding_model_provider
  1307. else:
  1308. embedding_model = model_manager.get_default_model_instance(
  1309. tenant_id=current_user.current_tenant_id, model_type=ModelType.TEXT_EMBEDDING
  1310. )
  1311. dataset_embedding_model = embedding_model.model
  1312. dataset_embedding_model_provider = embedding_model.provider
  1313. dataset.embedding_model = dataset_embedding_model
  1314. dataset.embedding_model_provider = dataset_embedding_model_provider
  1315. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  1316. dataset_embedding_model_provider, dataset_embedding_model
  1317. )
  1318. dataset.collection_binding_id = dataset_collection_binding.id
  1319. if not dataset.retrieval_model:
  1320. default_retrieval_model = {
  1321. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  1322. "reranking_enable": False,
  1323. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  1324. "top_k": 4,
  1325. "score_threshold_enabled": False,
  1326. }
  1327. dataset.retrieval_model = (
  1328. knowledge_config.retrieval_model.model_dump()
  1329. if knowledge_config.retrieval_model
  1330. else default_retrieval_model
  1331. ) # type: ignore
  1332. documents = []
  1333. if knowledge_config.original_document_id:
  1334. document = DocumentService.update_document_with_dataset_id(dataset, knowledge_config, account)
  1335. documents.append(document)
  1336. batch = document.batch
  1337. else:
  1338. batch = time.strftime("%Y%m%d%H%M%S") + str(100000 + secrets.randbelow(exclusive_upper_bound=900000))
  1339. # save process rule
  1340. if not dataset_process_rule:
  1341. process_rule = knowledge_config.process_rule
  1342. if process_rule:
  1343. if process_rule.mode in ("custom", "hierarchical"):
  1344. if process_rule.rules:
  1345. dataset_process_rule = DatasetProcessRule(
  1346. dataset_id=dataset.id,
  1347. mode=process_rule.mode,
  1348. rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  1349. created_by=account.id,
  1350. )
  1351. else:
  1352. dataset_process_rule = dataset.latest_process_rule
  1353. if not dataset_process_rule:
  1354. raise ValueError("No process rule found.")
  1355. elif process_rule.mode == "automatic":
  1356. dataset_process_rule = DatasetProcessRule(
  1357. dataset_id=dataset.id,
  1358. mode=process_rule.mode,
  1359. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  1360. created_by=account.id,
  1361. )
  1362. else:
  1363. logger.warning(
  1364. "Invalid process rule mode: %s, can not find dataset process rule",
  1365. process_rule.mode,
  1366. )
  1367. return [], ""
  1368. db.session.add(dataset_process_rule)
  1369. db.session.flush()
  1370. lock_name = f"add_document_lock_dataset_id_{dataset.id}"
  1371. with redis_client.lock(lock_name, timeout=600):
  1372. position = DocumentService.get_documents_position(dataset.id)
  1373. document_ids = []
  1374. duplicate_document_ids = []
  1375. if knowledge_config.data_source.info_list.data_source_type == "upload_file": # type: ignore
  1376. upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  1377. for file_id in upload_file_list:
  1378. file = (
  1379. db.session.query(UploadFile)
  1380. .where(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  1381. .first()
  1382. )
  1383. # raise error if file not found
  1384. if not file:
  1385. raise FileNotExistsError()
  1386. file_name = file.name
  1387. data_source_info = {
  1388. "upload_file_id": file_id,
  1389. }
  1390. # check duplicate
  1391. if knowledge_config.duplicate:
  1392. document = (
  1393. db.session.query(Document)
  1394. .filter_by(
  1395. dataset_id=dataset.id,
  1396. tenant_id=current_user.current_tenant_id,
  1397. data_source_type="upload_file",
  1398. enabled=True,
  1399. name=file_name,
  1400. )
  1401. .first()
  1402. )
  1403. if document:
  1404. document.dataset_process_rule_id = dataset_process_rule.id # type: ignore
  1405. document.updated_at = naive_utc_now()
  1406. document.created_from = created_from
  1407. document.doc_form = knowledge_config.doc_form
  1408. document.doc_language = knowledge_config.doc_language
  1409. document.data_source_info = json.dumps(data_source_info)
  1410. document.batch = batch
  1411. document.indexing_status = "waiting"
  1412. db.session.add(document)
  1413. documents.append(document)
  1414. duplicate_document_ids.append(document.id)
  1415. continue
  1416. document = DocumentService.build_document(
  1417. dataset,
  1418. dataset_process_rule.id, # type: ignore
  1419. knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1420. knowledge_config.doc_form,
  1421. knowledge_config.doc_language,
  1422. data_source_info,
  1423. created_from,
  1424. position,
  1425. account,
  1426. file_name,
  1427. batch,
  1428. )
  1429. db.session.add(document)
  1430. db.session.flush()
  1431. document_ids.append(document.id)
  1432. documents.append(document)
  1433. position += 1
  1434. elif knowledge_config.data_source.info_list.data_source_type == "notion_import": # type: ignore
  1435. notion_info_list = knowledge_config.data_source.info_list.notion_info_list # type: ignore
  1436. if not notion_info_list:
  1437. raise ValueError("No notion info list found.")
  1438. exist_page_ids = []
  1439. exist_document = {}
  1440. documents = (
  1441. db.session.query(Document)
  1442. .filter_by(
  1443. dataset_id=dataset.id,
  1444. tenant_id=current_user.current_tenant_id,
  1445. data_source_type="notion_import",
  1446. enabled=True,
  1447. )
  1448. .all()
  1449. )
  1450. if documents:
  1451. for document in documents:
  1452. data_source_info = json.loads(document.data_source_info)
  1453. exist_page_ids.append(data_source_info["notion_page_id"])
  1454. exist_document[data_source_info["notion_page_id"]] = document.id
  1455. for notion_info in notion_info_list:
  1456. workspace_id = notion_info.workspace_id
  1457. for page in notion_info.pages:
  1458. if page.page_id not in exist_page_ids:
  1459. data_source_info = {
  1460. "credential_id": notion_info.credential_id,
  1461. "notion_workspace_id": workspace_id,
  1462. "notion_page_id": page.page_id,
  1463. "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None,
  1464. "type": page.type,
  1465. }
  1466. # Truncate page name to 255 characters to prevent DB field length errors
  1467. truncated_page_name = page.page_name[:255] if page.page_name else "nopagename"
  1468. document = DocumentService.build_document(
  1469. dataset,
  1470. dataset_process_rule.id, # type: ignore
  1471. knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1472. knowledge_config.doc_form,
  1473. knowledge_config.doc_language,
  1474. data_source_info,
  1475. created_from,
  1476. position,
  1477. account,
  1478. truncated_page_name,
  1479. batch,
  1480. )
  1481. db.session.add(document)
  1482. db.session.flush()
  1483. document_ids.append(document.id)
  1484. documents.append(document)
  1485. position += 1
  1486. else:
  1487. exist_document.pop(page.page_id)
  1488. # delete not selected documents
  1489. if len(exist_document) > 0:
  1490. clean_notion_document_task.delay(list(exist_document.values()), dataset.id)
  1491. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl": # type: ignore
  1492. website_info = knowledge_config.data_source.info_list.website_info_list # type: ignore
  1493. if not website_info:
  1494. raise ValueError("No website info list found.")
  1495. urls = website_info.urls
  1496. for url in urls:
  1497. data_source_info = {
  1498. "url": url,
  1499. "provider": website_info.provider,
  1500. "job_id": website_info.job_id,
  1501. "only_main_content": website_info.only_main_content,
  1502. "mode": "crawl",
  1503. }
  1504. if len(url) > 255:
  1505. document_name = url[:200] + "..."
  1506. else:
  1507. document_name = url
  1508. document = DocumentService.build_document(
  1509. dataset,
  1510. dataset_process_rule.id, # type: ignore
  1511. knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1512. knowledge_config.doc_form,
  1513. knowledge_config.doc_language,
  1514. data_source_info,
  1515. created_from,
  1516. position,
  1517. account,
  1518. document_name,
  1519. batch,
  1520. )
  1521. db.session.add(document)
  1522. db.session.flush()
  1523. document_ids.append(document.id)
  1524. documents.append(document)
  1525. position += 1
  1526. db.session.commit()
  1527. # trigger async task
  1528. if document_ids:
  1529. document_indexing_task.delay(dataset.id, document_ids)
  1530. if duplicate_document_ids:
  1531. duplicate_document_indexing_task.delay(dataset.id, duplicate_document_ids)
  1532. return documents, batch
  1533. # @staticmethod
  1534. # def save_document_with_dataset_id(
  1535. # dataset: Dataset,
  1536. # knowledge_config: KnowledgeConfig,
  1537. # account: Account | Any,
  1538. # dataset_process_rule: Optional[DatasetProcessRule] = None,
  1539. # created_from: str = "web",
  1540. # ):
  1541. # # check document limit
  1542. # features = FeatureService.get_features(current_user.current_tenant_id)
  1543. # if features.billing.enabled:
  1544. # if not knowledge_config.original_document_id:
  1545. # count = 0
  1546. # if knowledge_config.data_source:
  1547. # if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  1548. # upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids
  1549. # # type: ignore
  1550. # count = len(upload_file_list)
  1551. # elif knowledge_config.data_source.info_list.data_source_type == "notion_import":
  1552. # notion_info_list = knowledge_config.data_source.info_list.notion_info_list
  1553. # for notion_info in notion_info_list: # type: ignore
  1554. # count = count + len(notion_info.pages)
  1555. # elif knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  1556. # website_info = knowledge_config.data_source.info_list.website_info_list
  1557. # count = len(website_info.urls) # type: ignore
  1558. # batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  1559. # if features.billing.subscription.plan == "sandbox" and count > 1:
  1560. # raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
  1561. # if count > batch_upload_limit:
  1562. # raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  1563. # DocumentService.check_documents_upload_quota(count, features)
  1564. # # if dataset is empty, update dataset data_source_type
  1565. # if not dataset.data_source_type:
  1566. # dataset.data_source_type = knowledge_config.data_source.info_list.data_source_type # type: ignore
  1567. # if not dataset.indexing_technique:
  1568. # if knowledge_config.indexing_technique not in Dataset.INDEXING_TECHNIQUE_LIST:
  1569. # raise ValueError("Indexing technique is invalid")
  1570. # dataset.indexing_technique = knowledge_config.indexing_technique
  1571. # if knowledge_config.indexing_technique == "high_quality":
  1572. # model_manager = ModelManager()
  1573. # if knowledge_config.embedding_model and knowledge_config.embedding_model_provider:
  1574. # dataset_embedding_model = knowledge_config.embedding_model
  1575. # dataset_embedding_model_provider = knowledge_config.embedding_model_provider
  1576. # else:
  1577. # embedding_model = model_manager.get_default_model_instance(
  1578. # tenant_id=current_user.current_tenant_id, model_type=ModelType.TEXT_EMBEDDING
  1579. # )
  1580. # dataset_embedding_model = embedding_model.model
  1581. # dataset_embedding_model_provider = embedding_model.provider
  1582. # dataset.embedding_model = dataset_embedding_model
  1583. # dataset.embedding_model_provider = dataset_embedding_model_provider
  1584. # dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  1585. # dataset_embedding_model_provider, dataset_embedding_model
  1586. # )
  1587. # dataset.collection_binding_id = dataset_collection_binding.id
  1588. # if not dataset.retrieval_model:
  1589. # default_retrieval_model = {
  1590. # "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  1591. # "reranking_enable": False,
  1592. # "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  1593. # "top_k": 2,
  1594. # "score_threshold_enabled": False,
  1595. # }
  1596. # dataset.retrieval_model = (
  1597. # knowledge_config.retrieval_model.model_dump()
  1598. # if knowledge_config.retrieval_model
  1599. # else default_retrieval_model
  1600. # ) # type: ignore
  1601. # documents = []
  1602. # if knowledge_config.original_document_id:
  1603. # document = DocumentService.update_document_with_dataset_id(dataset, knowledge_config, account)
  1604. # documents.append(document)
  1605. # batch = document.batch
  1606. # else:
  1607. # batch = time.strftime("%Y%m%d%H%M%S") + str(random.randint(100000, 999999))
  1608. # # save process rule
  1609. # if not dataset_process_rule:
  1610. # process_rule = knowledge_config.process_rule
  1611. # if process_rule:
  1612. # if process_rule.mode in ("custom", "hierarchical"):
  1613. # dataset_process_rule = DatasetProcessRule(
  1614. # dataset_id=dataset.id,
  1615. # mode=process_rule.mode,
  1616. # rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  1617. # created_by=account.id,
  1618. # )
  1619. # elif process_rule.mode == "automatic":
  1620. # dataset_process_rule = DatasetProcessRule(
  1621. # dataset_id=dataset.id,
  1622. # mode=process_rule.mode,
  1623. # rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  1624. # created_by=account.id,
  1625. # )
  1626. # else:
  1627. # logging.warn(
  1628. # f"Invalid process rule mode: {process_rule.mode}, can not find dataset process rule"
  1629. # )
  1630. # return
  1631. # db.session.add(dataset_process_rule)
  1632. # db.session.commit()
  1633. # lock_name = "add_document_lock_dataset_id_{}".format(dataset.id)
  1634. # with redis_client.lock(lock_name, timeout=600):
  1635. # position = DocumentService.get_documents_position(dataset.id)
  1636. # document_ids = []
  1637. # duplicate_document_ids = []
  1638. # if knowledge_config.data_source.info_list.data_source_type == "upload_file": # type: ignore
  1639. # upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  1640. # for file_id in upload_file_list:
  1641. # file = (
  1642. # db.session.query(UploadFile)
  1643. # .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  1644. # .first()
  1645. # )
  1646. # # raise error if file not found
  1647. # if not file:
  1648. # raise FileNotExistsError()
  1649. # file_name = file.name
  1650. # data_source_info = {
  1651. # "upload_file_id": file_id,
  1652. # }
  1653. # # check duplicate
  1654. # if knowledge_config.duplicate:
  1655. # document = Document.query.filter_by(
  1656. # dataset_id=dataset.id,
  1657. # tenant_id=current_user.current_tenant_id,
  1658. # data_source_type="upload_file",
  1659. # enabled=True,
  1660. # name=file_name,
  1661. # ).first()
  1662. # if document:
  1663. # document.dataset_process_rule_id = dataset_process_rule.id # type: ignore
  1664. # document.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1665. # document.created_from = created_from
  1666. # document.doc_form = knowledge_config.doc_form
  1667. # document.doc_language = knowledge_config.doc_language
  1668. # document.data_source_info = json.dumps(data_source_info)
  1669. # document.batch = batch
  1670. # document.indexing_status = "waiting"
  1671. # db.session.add(document)
  1672. # documents.append(document)
  1673. # duplicate_document_ids.append(document.id)
  1674. # continue
  1675. # document = DocumentService.build_document(
  1676. # dataset,
  1677. # dataset_process_rule.id, # type: ignore
  1678. # knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1679. # knowledge_config.doc_form,
  1680. # knowledge_config.doc_language,
  1681. # data_source_info,
  1682. # created_from,
  1683. # position,
  1684. # account,
  1685. # file_name,
  1686. # batch,
  1687. # )
  1688. # db.session.add(document)
  1689. # db.session.flush()
  1690. # document_ids.append(document.id)
  1691. # documents.append(document)
  1692. # position += 1
  1693. # elif knowledge_config.data_source.info_list.data_source_type == "notion_import": # type: ignore
  1694. # notion_info_list = knowledge_config.data_source.info_list.notion_info_list # type: ignore
  1695. # if not notion_info_list:
  1696. # raise ValueError("No notion info list found.")
  1697. # exist_page_ids = []
  1698. # exist_document = {}
  1699. # documents = Document.query.filter_by(
  1700. # dataset_id=dataset.id,
  1701. # tenant_id=current_user.current_tenant_id,
  1702. # data_source_type="notion_import",
  1703. # enabled=True,
  1704. # ).all()
  1705. # if documents:
  1706. # for document in documents:
  1707. # data_source_info = json.loads(document.data_source_info)
  1708. # exist_page_ids.append(data_source_info["notion_page_id"])
  1709. # exist_document[data_source_info["notion_page_id"]] = document.id
  1710. # for notion_info in notion_info_list:
  1711. # workspace_id = notion_info.workspace_id
  1712. # data_source_binding = DataSourceOauthBinding.query.filter(
  1713. # sa.and_(
  1714. # DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  1715. # DataSourceOauthBinding.provider == "notion",
  1716. # DataSourceOauthBinding.disabled == False,
  1717. # DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  1718. # )
  1719. # ).first()
  1720. # if not data_source_binding:
  1721. # raise ValueError("Data source binding not found.")
  1722. # for page in notion_info.pages:
  1723. # if page.page_id not in exist_page_ids:
  1724. # data_source_info = {
  1725. # "notion_workspace_id": workspace_id,
  1726. # "notion_page_id": page.page_id,
  1727. # "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None,
  1728. # "type": page.type,
  1729. # }
  1730. # # Truncate page name to 255 characters to prevent DB field length errors
  1731. # truncated_page_name = page.page_name[:255] if page.page_name else "nopagename"
  1732. # document = DocumentService.build_document(
  1733. # dataset,
  1734. # dataset_process_rule.id, # type: ignore
  1735. # knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1736. # knowledge_config.doc_form,
  1737. # knowledge_config.doc_language,
  1738. # data_source_info,
  1739. # created_from,
  1740. # position,
  1741. # account,
  1742. # truncated_page_name,
  1743. # batch,
  1744. # )
  1745. # db.session.add(document)
  1746. # db.session.flush()
  1747. # document_ids.append(document.id)
  1748. # documents.append(document)
  1749. # position += 1
  1750. # else:
  1751. # exist_document.pop(page.page_id)
  1752. # # delete not selected documents
  1753. # if len(exist_document) > 0:
  1754. # clean_notion_document_task.delay(list(exist_document.values()), dataset.id)
  1755. # elif knowledge_config.data_source.info_list.data_source_type == "website_crawl": # type: ignore
  1756. # website_info = knowledge_config.data_source.info_list.website_info_list # type: ignore
  1757. # if not website_info:
  1758. # raise ValueError("No website info list found.")
  1759. # urls = website_info.urls
  1760. # for url in urls:
  1761. # data_source_info = {
  1762. # "url": url,
  1763. # "provider": website_info.provider,
  1764. # "job_id": website_info.job_id,
  1765. # "only_main_content": website_info.only_main_content,
  1766. # "mode": "crawl",
  1767. # }
  1768. # if len(url) > 255:
  1769. # document_name = url[:200] + "..."
  1770. # else:
  1771. # document_name = url
  1772. # document = DocumentService.build_document(
  1773. # dataset,
  1774. # dataset_process_rule.id, # type: ignore
  1775. # knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1776. # knowledge_config.doc_form,
  1777. # knowledge_config.doc_language,
  1778. # data_source_info,
  1779. # created_from,
  1780. # position,
  1781. # account,
  1782. # document_name,
  1783. # batch,
  1784. # )
  1785. # db.session.add(document)
  1786. # db.session.flush()
  1787. # document_ids.append(document.id)
  1788. # documents.append(document)
  1789. # position += 1
  1790. # db.session.commit()
  1791. # # trigger async task
  1792. # if document_ids:
  1793. # document_indexing_task.delay(dataset.id, document_ids)
  1794. # if duplicate_document_ids:
  1795. # duplicate_document_indexing_task.delay(dataset.id, duplicate_document_ids)
  1796. # return documents, batch
  1797. @staticmethod
  1798. def check_documents_upload_quota(count: int, features: FeatureModel):
  1799. can_upload_size = features.documents_upload_quota.limit - features.documents_upload_quota.size
  1800. if count > can_upload_size:
  1801. raise ValueError(
  1802. f"You have reached the limit of your subscription. Only {can_upload_size} documents can be uploaded."
  1803. )
  1804. @staticmethod
  1805. def build_document(
  1806. dataset: Dataset,
  1807. process_rule_id: str | None,
  1808. data_source_type: str,
  1809. document_form: str,
  1810. document_language: str,
  1811. data_source_info: dict,
  1812. created_from: str,
  1813. position: int,
  1814. account: Account,
  1815. name: str,
  1816. batch: str,
  1817. ):
  1818. document = Document(
  1819. tenant_id=dataset.tenant_id,
  1820. dataset_id=dataset.id,
  1821. position=position,
  1822. data_source_type=data_source_type,
  1823. data_source_info=json.dumps(data_source_info),
  1824. dataset_process_rule_id=process_rule_id,
  1825. batch=batch,
  1826. name=name,
  1827. created_from=created_from,
  1828. created_by=account.id,
  1829. doc_form=document_form,
  1830. doc_language=document_language,
  1831. )
  1832. doc_metadata = {}
  1833. if dataset.built_in_field_enabled:
  1834. doc_metadata = {
  1835. BuiltInField.document_name: name,
  1836. BuiltInField.uploader: account.name,
  1837. BuiltInField.upload_date: datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S"),
  1838. BuiltInField.last_update_date: datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S"),
  1839. BuiltInField.source: data_source_type,
  1840. }
  1841. if doc_metadata:
  1842. document.doc_metadata = doc_metadata
  1843. return document
  1844. @staticmethod
  1845. def get_tenant_documents_count():
  1846. assert isinstance(current_user, Account)
  1847. documents_count = (
  1848. db.session.query(Document)
  1849. .where(
  1850. Document.completed_at.isnot(None),
  1851. Document.enabled == True,
  1852. Document.archived == False,
  1853. Document.tenant_id == current_user.current_tenant_id,
  1854. )
  1855. .count()
  1856. )
  1857. return documents_count
  1858. @staticmethod
  1859. def update_document_with_dataset_id(
  1860. dataset: Dataset,
  1861. document_data: KnowledgeConfig,
  1862. account: Account,
  1863. dataset_process_rule: DatasetProcessRule | None = None,
  1864. created_from: str = "web",
  1865. ):
  1866. assert isinstance(current_user, Account)
  1867. DatasetService.check_dataset_model_setting(dataset)
  1868. document = DocumentService.get_document(dataset.id, document_data.original_document_id)
  1869. if document is None:
  1870. raise NotFound("Document not found")
  1871. if document.display_status != "available":
  1872. raise ValueError("Document is not available")
  1873. # save process rule
  1874. if document_data.process_rule:
  1875. process_rule = document_data.process_rule
  1876. if process_rule.mode in {"custom", "hierarchical"}:
  1877. dataset_process_rule = DatasetProcessRule(
  1878. dataset_id=dataset.id,
  1879. mode=process_rule.mode,
  1880. rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  1881. created_by=account.id,
  1882. )
  1883. elif process_rule.mode == "automatic":
  1884. dataset_process_rule = DatasetProcessRule(
  1885. dataset_id=dataset.id,
  1886. mode=process_rule.mode,
  1887. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  1888. created_by=account.id,
  1889. )
  1890. if dataset_process_rule is not None:
  1891. db.session.add(dataset_process_rule)
  1892. db.session.commit()
  1893. document.dataset_process_rule_id = dataset_process_rule.id
  1894. # update document data source
  1895. if document_data.data_source:
  1896. file_name = ""
  1897. data_source_info = {}
  1898. if document_data.data_source.info_list.data_source_type == "upload_file":
  1899. if not document_data.data_source.info_list.file_info_list:
  1900. raise ValueError("No file info list found.")
  1901. upload_file_list = document_data.data_source.info_list.file_info_list.file_ids
  1902. for file_id in upload_file_list:
  1903. file = (
  1904. db.session.query(UploadFile)
  1905. .where(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  1906. .first()
  1907. )
  1908. # raise error if file not found
  1909. if not file:
  1910. raise FileNotExistsError()
  1911. file_name = file.name
  1912. data_source_info = {
  1913. "upload_file_id": file_id,
  1914. }
  1915. elif document_data.data_source.info_list.data_source_type == "notion_import":
  1916. if not document_data.data_source.info_list.notion_info_list:
  1917. raise ValueError("No notion info list found.")
  1918. notion_info_list = document_data.data_source.info_list.notion_info_list
  1919. for notion_info in notion_info_list:
  1920. workspace_id = notion_info.workspace_id
  1921. data_source_binding = (
  1922. db.session.query(DataSourceOauthBinding)
  1923. .where(
  1924. sa.and_(
  1925. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  1926. DataSourceOauthBinding.provider == "notion",
  1927. DataSourceOauthBinding.disabled == False,
  1928. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  1929. )
  1930. )
  1931. .first()
  1932. )
  1933. if not data_source_binding:
  1934. raise ValueError("Data source binding not found.")
  1935. for page in notion_info.pages:
  1936. data_source_info = {
  1937. "credential_id": notion_info.credential_id,
  1938. "notion_workspace_id": workspace_id,
  1939. "notion_page_id": page.page_id,
  1940. "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None, # type: ignore
  1941. "type": page.type,
  1942. }
  1943. elif document_data.data_source.info_list.data_source_type == "website_crawl":
  1944. website_info = document_data.data_source.info_list.website_info_list
  1945. if website_info:
  1946. urls = website_info.urls
  1947. for url in urls:
  1948. data_source_info = {
  1949. "url": url,
  1950. "provider": website_info.provider,
  1951. "job_id": website_info.job_id,
  1952. "only_main_content": website_info.only_main_content, # type: ignore
  1953. "mode": "crawl",
  1954. }
  1955. document.data_source_type = document_data.data_source.info_list.data_source_type
  1956. document.data_source_info = json.dumps(data_source_info)
  1957. document.name = file_name
  1958. # update document name
  1959. if document_data.name:
  1960. document.name = document_data.name
  1961. # update document to be waiting
  1962. document.indexing_status = "waiting"
  1963. document.completed_at = None
  1964. document.processing_started_at = None
  1965. document.parsing_completed_at = None
  1966. document.cleaning_completed_at = None
  1967. document.splitting_completed_at = None
  1968. document.updated_at = naive_utc_now()
  1969. document.created_from = created_from
  1970. document.doc_form = document_data.doc_form
  1971. db.session.add(document)
  1972. db.session.commit()
  1973. # update document segment
  1974. db.session.query(DocumentSegment).filter_by(document_id=document.id).update(
  1975. {DocumentSegment.status: "re_segment"}
  1976. ) # type: ignore
  1977. db.session.commit()
  1978. # trigger async task
  1979. document_indexing_update_task.delay(document.dataset_id, document.id)
  1980. return document
  1981. @staticmethod
  1982. def save_document_without_dataset_id(tenant_id: str, knowledge_config: KnowledgeConfig, account: Account):
  1983. assert isinstance(current_user, Account)
  1984. assert current_user.current_tenant_id is not None
  1985. features = FeatureService.get_features(current_user.current_tenant_id)
  1986. if features.billing.enabled:
  1987. count = 0
  1988. if knowledge_config.data_source.info_list.data_source_type == "upload_file": # type: ignore
  1989. upload_file_list = (
  1990. knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  1991. if knowledge_config.data_source.info_list.file_info_list # type: ignore
  1992. else []
  1993. )
  1994. count = len(upload_file_list)
  1995. elif knowledge_config.data_source.info_list.data_source_type == "notion_import": # type: ignore
  1996. notion_info_list = knowledge_config.data_source.info_list.notion_info_list # type: ignore
  1997. if notion_info_list:
  1998. for notion_info in notion_info_list:
  1999. count = count + len(notion_info.pages)
  2000. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl": # type: ignore
  2001. website_info = knowledge_config.data_source.info_list.website_info_list # type: ignore
  2002. if website_info:
  2003. count = len(website_info.urls)
  2004. if features.billing.subscription.plan == "sandbox" and count > 1:
  2005. raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
  2006. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  2007. if count > batch_upload_limit:
  2008. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  2009. DocumentService.check_documents_upload_quota(count, features)
  2010. dataset_collection_binding_id = None
  2011. retrieval_model = None
  2012. if knowledge_config.indexing_technique == "high_quality":
  2013. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  2014. knowledge_config.embedding_model_provider, # type: ignore
  2015. knowledge_config.embedding_model, # type: ignore
  2016. )
  2017. dataset_collection_binding_id = dataset_collection_binding.id
  2018. if knowledge_config.retrieval_model:
  2019. retrieval_model = knowledge_config.retrieval_model
  2020. else:
  2021. retrieval_model = RetrievalModel(
  2022. search_method=RetrievalMethod.SEMANTIC_SEARCH.value,
  2023. reranking_enable=False,
  2024. reranking_model=RerankingModel(reranking_provider_name="", reranking_model_name=""),
  2025. top_k=4,
  2026. score_threshold_enabled=False,
  2027. )
  2028. # save dataset
  2029. dataset = Dataset(
  2030. tenant_id=tenant_id,
  2031. name="",
  2032. data_source_type=knowledge_config.data_source.info_list.data_source_type, # type: ignore
  2033. indexing_technique=knowledge_config.indexing_technique,
  2034. created_by=account.id,
  2035. embedding_model=knowledge_config.embedding_model,
  2036. embedding_model_provider=knowledge_config.embedding_model_provider,
  2037. collection_binding_id=dataset_collection_binding_id,
  2038. retrieval_model=retrieval_model.model_dump() if retrieval_model else None,
  2039. )
  2040. db.session.add(dataset) # type: ignore
  2041. db.session.flush()
  2042. documents, batch = DocumentService.save_document_with_dataset_id(dataset, knowledge_config, account)
  2043. cut_length = 18
  2044. cut_name = documents[0].name[:cut_length]
  2045. dataset.name = cut_name + "..."
  2046. dataset.description = "useful for when you want to answer queries about the " + documents[0].name
  2047. db.session.commit()
  2048. return dataset, documents, batch
  2049. @classmethod
  2050. def document_create_args_validate(cls, knowledge_config: KnowledgeConfig):
  2051. if not knowledge_config.data_source and not knowledge_config.process_rule:
  2052. raise ValueError("Data source or Process rule is required")
  2053. else:
  2054. if knowledge_config.data_source:
  2055. DocumentService.data_source_args_validate(knowledge_config)
  2056. if knowledge_config.process_rule:
  2057. DocumentService.process_rule_args_validate(knowledge_config)
  2058. @classmethod
  2059. def data_source_args_validate(cls, knowledge_config: KnowledgeConfig):
  2060. if not knowledge_config.data_source:
  2061. raise ValueError("Data source is required")
  2062. if knowledge_config.data_source.info_list.data_source_type not in Document.DATA_SOURCES:
  2063. raise ValueError("Data source type is invalid")
  2064. if not knowledge_config.data_source.info_list:
  2065. raise ValueError("Data source info is required")
  2066. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  2067. if not knowledge_config.data_source.info_list.file_info_list:
  2068. raise ValueError("File source info is required")
  2069. if knowledge_config.data_source.info_list.data_source_type == "notion_import":
  2070. if not knowledge_config.data_source.info_list.notion_info_list:
  2071. raise ValueError("Notion source info is required")
  2072. if knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  2073. if not knowledge_config.data_source.info_list.website_info_list:
  2074. raise ValueError("Website source info is required")
  2075. @classmethod
  2076. def process_rule_args_validate(cls, knowledge_config: KnowledgeConfig):
  2077. if not knowledge_config.process_rule:
  2078. raise ValueError("Process rule is required")
  2079. if not knowledge_config.process_rule.mode:
  2080. raise ValueError("Process rule mode is required")
  2081. if knowledge_config.process_rule.mode not in DatasetProcessRule.MODES:
  2082. raise ValueError("Process rule mode is invalid")
  2083. if knowledge_config.process_rule.mode == "automatic":
  2084. knowledge_config.process_rule.rules = None
  2085. else:
  2086. if not knowledge_config.process_rule.rules:
  2087. raise ValueError("Process rule rules is required")
  2088. if knowledge_config.process_rule.rules.pre_processing_rules is None:
  2089. raise ValueError("Process rule pre_processing_rules is required")
  2090. unique_pre_processing_rule_dicts = {}
  2091. for pre_processing_rule in knowledge_config.process_rule.rules.pre_processing_rules:
  2092. if not pre_processing_rule.id:
  2093. raise ValueError("Process rule pre_processing_rules id is required")
  2094. if not isinstance(pre_processing_rule.enabled, bool):
  2095. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  2096. unique_pre_processing_rule_dicts[pre_processing_rule.id] = pre_processing_rule
  2097. knowledge_config.process_rule.rules.pre_processing_rules = list(unique_pre_processing_rule_dicts.values())
  2098. if not knowledge_config.process_rule.rules.segmentation:
  2099. raise ValueError("Process rule segmentation is required")
  2100. if not knowledge_config.process_rule.rules.segmentation.separator:
  2101. raise ValueError("Process rule segmentation separator is required")
  2102. if not isinstance(knowledge_config.process_rule.rules.segmentation.separator, str):
  2103. raise ValueError("Process rule segmentation separator is invalid")
  2104. if not (
  2105. knowledge_config.process_rule.mode == "hierarchical"
  2106. and knowledge_config.process_rule.rules.parent_mode == "full-doc"
  2107. ):
  2108. if not knowledge_config.process_rule.rules.segmentation.max_tokens:
  2109. raise ValueError("Process rule segmentation max_tokens is required")
  2110. if not isinstance(knowledge_config.process_rule.rules.segmentation.max_tokens, int):
  2111. raise ValueError("Process rule segmentation max_tokens is invalid")
  2112. @classmethod
  2113. def estimate_args_validate(cls, args: dict):
  2114. if "info_list" not in args or not args["info_list"]:
  2115. raise ValueError("Data source info is required")
  2116. if not isinstance(args["info_list"], dict):
  2117. raise ValueError("Data info is invalid")
  2118. if "process_rule" not in args or not args["process_rule"]:
  2119. raise ValueError("Process rule is required")
  2120. if not isinstance(args["process_rule"], dict):
  2121. raise ValueError("Process rule is invalid")
  2122. if "mode" not in args["process_rule"] or not args["process_rule"]["mode"]:
  2123. raise ValueError("Process rule mode is required")
  2124. if args["process_rule"]["mode"] not in DatasetProcessRule.MODES:
  2125. raise ValueError("Process rule mode is invalid")
  2126. if args["process_rule"]["mode"] == "automatic":
  2127. args["process_rule"]["rules"] = {}
  2128. else:
  2129. if "rules" not in args["process_rule"] or not args["process_rule"]["rules"]:
  2130. raise ValueError("Process rule rules is required")
  2131. if not isinstance(args["process_rule"]["rules"], dict):
  2132. raise ValueError("Process rule rules is invalid")
  2133. if (
  2134. "pre_processing_rules" not in args["process_rule"]["rules"]
  2135. or args["process_rule"]["rules"]["pre_processing_rules"] is None
  2136. ):
  2137. raise ValueError("Process rule pre_processing_rules is required")
  2138. if not isinstance(args["process_rule"]["rules"]["pre_processing_rules"], list):
  2139. raise ValueError("Process rule pre_processing_rules is invalid")
  2140. unique_pre_processing_rule_dicts = {}
  2141. for pre_processing_rule in args["process_rule"]["rules"]["pre_processing_rules"]:
  2142. if "id" not in pre_processing_rule or not pre_processing_rule["id"]:
  2143. raise ValueError("Process rule pre_processing_rules id is required")
  2144. if pre_processing_rule["id"] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  2145. raise ValueError("Process rule pre_processing_rules id is invalid")
  2146. if "enabled" not in pre_processing_rule or pre_processing_rule["enabled"] is None:
  2147. raise ValueError("Process rule pre_processing_rules enabled is required")
  2148. if not isinstance(pre_processing_rule["enabled"], bool):
  2149. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  2150. unique_pre_processing_rule_dicts[pre_processing_rule["id"]] = pre_processing_rule
  2151. args["process_rule"]["rules"]["pre_processing_rules"] = list(unique_pre_processing_rule_dicts.values())
  2152. if (
  2153. "segmentation" not in args["process_rule"]["rules"]
  2154. or args["process_rule"]["rules"]["segmentation"] is None
  2155. ):
  2156. raise ValueError("Process rule segmentation is required")
  2157. if not isinstance(args["process_rule"]["rules"]["segmentation"], dict):
  2158. raise ValueError("Process rule segmentation is invalid")
  2159. if (
  2160. "separator" not in args["process_rule"]["rules"]["segmentation"]
  2161. or not args["process_rule"]["rules"]["segmentation"]["separator"]
  2162. ):
  2163. raise ValueError("Process rule segmentation separator is required")
  2164. if not isinstance(args["process_rule"]["rules"]["segmentation"]["separator"], str):
  2165. raise ValueError("Process rule segmentation separator is invalid")
  2166. if (
  2167. "max_tokens" not in args["process_rule"]["rules"]["segmentation"]
  2168. or not args["process_rule"]["rules"]["segmentation"]["max_tokens"]
  2169. ):
  2170. raise ValueError("Process rule segmentation max_tokens is required")
  2171. if not isinstance(args["process_rule"]["rules"]["segmentation"]["max_tokens"], int):
  2172. raise ValueError("Process rule segmentation max_tokens is invalid")
  2173. @staticmethod
  2174. def batch_update_document_status(
  2175. dataset: Dataset, document_ids: list[str], action: Literal["enable", "disable", "archive", "un_archive"], user
  2176. ):
  2177. """
  2178. Batch update document status.
  2179. Args:
  2180. dataset (Dataset): The dataset object
  2181. document_ids (list[str]): List of document IDs to update
  2182. action (Literal["enable", "disable", "archive", "un_archive"]): Action to perform
  2183. user: Current user performing the action
  2184. Raises:
  2185. DocumentIndexingError: If document is being indexed or not in correct state
  2186. ValueError: If action is invalid
  2187. """
  2188. if not document_ids:
  2189. return
  2190. # Early validation of action parameter
  2191. valid_actions = ["enable", "disable", "archive", "un_archive"]
  2192. if action not in valid_actions:
  2193. raise ValueError(f"Invalid action: {action}. Must be one of {valid_actions}")
  2194. documents_to_update = []
  2195. # First pass: validate all documents and prepare updates
  2196. for document_id in document_ids:
  2197. document = DocumentService.get_document(dataset.id, document_id)
  2198. if not document:
  2199. continue
  2200. # Check if document is being indexed
  2201. indexing_cache_key = f"document_{document.id}_indexing"
  2202. cache_result = redis_client.get(indexing_cache_key)
  2203. if cache_result is not None:
  2204. raise DocumentIndexingError(f"Document:{document.name} is being indexed, please try again later")
  2205. # Prepare update based on action
  2206. update_info = DocumentService._prepare_document_status_update(document, action, user)
  2207. if update_info:
  2208. documents_to_update.append(update_info)
  2209. # Second pass: apply all updates in a single transaction
  2210. if documents_to_update:
  2211. try:
  2212. for update_info in documents_to_update:
  2213. document = update_info["document"]
  2214. updates = update_info["updates"]
  2215. # Apply updates to the document
  2216. for field, value in updates.items():
  2217. setattr(document, field, value)
  2218. db.session.add(document)
  2219. # Batch commit all changes
  2220. db.session.commit()
  2221. except Exception as e:
  2222. # Rollback on any error
  2223. db.session.rollback()
  2224. raise e
  2225. # Execute async tasks and set Redis cache after successful commit
  2226. # propagation_error is used to capture any errors for submitting async task execution
  2227. propagation_error = None
  2228. for update_info in documents_to_update:
  2229. try:
  2230. # Execute async tasks after successful commit
  2231. if update_info["async_task"]:
  2232. task_info = update_info["async_task"]
  2233. task_func = task_info["function"]
  2234. task_args = task_info["args"]
  2235. task_func.delay(*task_args)
  2236. except Exception as e:
  2237. # Log the error but do not rollback the transaction
  2238. logger.exception("Error executing async task for document %s", update_info["document"].id)
  2239. # don't raise the error immediately, but capture it for later
  2240. propagation_error = e
  2241. try:
  2242. # Set Redis cache if needed after successful commit
  2243. if update_info["set_cache"]:
  2244. document = update_info["document"]
  2245. indexing_cache_key = f"document_{document.id}_indexing"
  2246. redis_client.setex(indexing_cache_key, 600, 1)
  2247. except Exception as e:
  2248. # Log the error but do not rollback the transaction
  2249. logger.exception("Error setting cache for document %s", update_info["document"].id)
  2250. # Raise any propagation error after all updates
  2251. if propagation_error:
  2252. raise propagation_error
  2253. @staticmethod
  2254. def _prepare_document_status_update(
  2255. document: Document, action: Literal["enable", "disable", "archive", "un_archive"], user
  2256. ):
  2257. """Prepare document status update information.
  2258. Args:
  2259. document: Document object to update
  2260. action: Action to perform
  2261. user: Current user
  2262. Returns:
  2263. dict: Update information or None if no update needed
  2264. """
  2265. now = naive_utc_now()
  2266. if action == "enable":
  2267. return DocumentService._prepare_enable_update(document, now)
  2268. elif action == "disable":
  2269. return DocumentService._prepare_disable_update(document, user, now)
  2270. elif action == "archive":
  2271. return DocumentService._prepare_archive_update(document, user, now)
  2272. elif action == "un_archive":
  2273. return DocumentService._prepare_unarchive_update(document, now)
  2274. return None
  2275. @staticmethod
  2276. def _prepare_enable_update(document, now):
  2277. """Prepare updates for enabling a document."""
  2278. if document.enabled:
  2279. return None
  2280. return {
  2281. "document": document,
  2282. "updates": {"enabled": True, "disabled_at": None, "disabled_by": None, "updated_at": now},
  2283. "async_task": {"function": add_document_to_index_task, "args": [document.id]},
  2284. "set_cache": True,
  2285. }
  2286. @staticmethod
  2287. def _prepare_disable_update(document, user, now):
  2288. """Prepare updates for disabling a document."""
  2289. if not document.completed_at or document.indexing_status != "completed":
  2290. raise DocumentIndexingError(f"Document: {document.name} is not completed.")
  2291. if not document.enabled:
  2292. return None
  2293. return {
  2294. "document": document,
  2295. "updates": {"enabled": False, "disabled_at": now, "disabled_by": user.id, "updated_at": now},
  2296. "async_task": {"function": remove_document_from_index_task, "args": [document.id]},
  2297. "set_cache": True,
  2298. }
  2299. @staticmethod
  2300. def _prepare_archive_update(document, user, now):
  2301. """Prepare updates for archiving a document."""
  2302. if document.archived:
  2303. return None
  2304. update_info = {
  2305. "document": document,
  2306. "updates": {"archived": True, "archived_at": now, "archived_by": user.id, "updated_at": now},
  2307. "async_task": None,
  2308. "set_cache": False,
  2309. }
  2310. # Only set async task and cache if document is currently enabled
  2311. if document.enabled:
  2312. update_info["async_task"] = {"function": remove_document_from_index_task, "args": [document.id]}
  2313. update_info["set_cache"] = True
  2314. return update_info
  2315. @staticmethod
  2316. def _prepare_unarchive_update(document, now):
  2317. """Prepare updates for unarchiving a document."""
  2318. if not document.archived:
  2319. return None
  2320. update_info = {
  2321. "document": document,
  2322. "updates": {"archived": False, "archived_at": None, "archived_by": None, "updated_at": now},
  2323. "async_task": None,
  2324. "set_cache": False,
  2325. }
  2326. # Only re-index if the document is currently enabled
  2327. if document.enabled:
  2328. update_info["async_task"] = {"function": add_document_to_index_task, "args": [document.id]}
  2329. update_info["set_cache"] = True
  2330. return update_info
  2331. class SegmentService:
  2332. @classmethod
  2333. def segment_create_args_validate(cls, args: dict, document: Document):
  2334. if document.doc_form == "qa_model":
  2335. if "answer" not in args or not args["answer"]:
  2336. raise ValueError("Answer is required")
  2337. if not args["answer"].strip():
  2338. raise ValueError("Answer is empty")
  2339. if "content" not in args or not args["content"] or not args["content"].strip():
  2340. raise ValueError("Content is empty")
  2341. @classmethod
  2342. def create_segment(cls, args: dict, document: Document, dataset: Dataset):
  2343. assert isinstance(current_user, Account)
  2344. assert current_user.current_tenant_id is not None
  2345. content = args["content"]
  2346. doc_id = str(uuid.uuid4())
  2347. segment_hash = helper.generate_text_hash(content)
  2348. tokens = 0
  2349. if dataset.indexing_technique == "high_quality":
  2350. model_manager = ModelManager()
  2351. embedding_model = model_manager.get_model_instance(
  2352. tenant_id=current_user.current_tenant_id,
  2353. provider=dataset.embedding_model_provider,
  2354. model_type=ModelType.TEXT_EMBEDDING,
  2355. model=dataset.embedding_model,
  2356. )
  2357. # calc embedding use tokens
  2358. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])[0]
  2359. lock_name = f"add_segment_lock_document_id_{document.id}"
  2360. with redis_client.lock(lock_name, timeout=600):
  2361. max_position = (
  2362. db.session.query(func.max(DocumentSegment.position))
  2363. .where(DocumentSegment.document_id == document.id)
  2364. .scalar()
  2365. )
  2366. segment_document = DocumentSegment(
  2367. tenant_id=current_user.current_tenant_id,
  2368. dataset_id=document.dataset_id,
  2369. document_id=document.id,
  2370. index_node_id=doc_id,
  2371. index_node_hash=segment_hash,
  2372. position=max_position + 1 if max_position else 1,
  2373. content=content,
  2374. word_count=len(content),
  2375. tokens=tokens,
  2376. status="completed",
  2377. indexing_at=naive_utc_now(),
  2378. completed_at=naive_utc_now(),
  2379. created_by=current_user.id,
  2380. )
  2381. if document.doc_form == "qa_model":
  2382. segment_document.word_count += len(args["answer"])
  2383. segment_document.answer = args["answer"]
  2384. db.session.add(segment_document)
  2385. # update document word count
  2386. assert document.word_count is not None
  2387. document.word_count += segment_document.word_count
  2388. db.session.add(document)
  2389. db.session.commit()
  2390. # save vector index
  2391. try:
  2392. VectorService.create_segments_vector([args["keywords"]], [segment_document], dataset, document.doc_form)
  2393. except Exception as e:
  2394. logger.exception("create segment index failed")
  2395. segment_document.enabled = False
  2396. segment_document.disabled_at = naive_utc_now()
  2397. segment_document.status = "error"
  2398. segment_document.error = str(e)
  2399. db.session.commit()
  2400. segment = db.session.query(DocumentSegment).where(DocumentSegment.id == segment_document.id).first()
  2401. return segment
  2402. @classmethod
  2403. def multi_create_segment(cls, segments: list, document: Document, dataset: Dataset):
  2404. assert isinstance(current_user, Account)
  2405. assert current_user.current_tenant_id is not None
  2406. lock_name = f"multi_add_segment_lock_document_id_{document.id}"
  2407. increment_word_count = 0
  2408. with redis_client.lock(lock_name, timeout=600):
  2409. embedding_model = None
  2410. if dataset.indexing_technique == "high_quality":
  2411. model_manager = ModelManager()
  2412. embedding_model = model_manager.get_model_instance(
  2413. tenant_id=current_user.current_tenant_id,
  2414. provider=dataset.embedding_model_provider,
  2415. model_type=ModelType.TEXT_EMBEDDING,
  2416. model=dataset.embedding_model,
  2417. )
  2418. max_position = (
  2419. db.session.query(func.max(DocumentSegment.position))
  2420. .where(DocumentSegment.document_id == document.id)
  2421. .scalar()
  2422. )
  2423. pre_segment_data_list = []
  2424. segment_data_list = []
  2425. keywords_list = []
  2426. position = max_position + 1 if max_position else 1
  2427. for segment_item in segments:
  2428. content = segment_item["content"]
  2429. doc_id = str(uuid.uuid4())
  2430. segment_hash = helper.generate_text_hash(content)
  2431. tokens = 0
  2432. if dataset.indexing_technique == "high_quality" and embedding_model:
  2433. # calc embedding use tokens
  2434. if document.doc_form == "qa_model":
  2435. tokens = embedding_model.get_text_embedding_num_tokens(
  2436. texts=[content + segment_item["answer"]]
  2437. )[0]
  2438. else:
  2439. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])[0]
  2440. segment_document = DocumentSegment(
  2441. tenant_id=current_user.current_tenant_id,
  2442. dataset_id=document.dataset_id,
  2443. document_id=document.id,
  2444. index_node_id=doc_id,
  2445. index_node_hash=segment_hash,
  2446. position=position,
  2447. content=content,
  2448. word_count=len(content),
  2449. tokens=tokens,
  2450. keywords=segment_item.get("keywords", []),
  2451. status="completed",
  2452. indexing_at=naive_utc_now(),
  2453. completed_at=naive_utc_now(),
  2454. created_by=current_user.id,
  2455. )
  2456. if document.doc_form == "qa_model":
  2457. segment_document.answer = segment_item["answer"]
  2458. segment_document.word_count += len(segment_item["answer"])
  2459. increment_word_count += segment_document.word_count
  2460. db.session.add(segment_document)
  2461. segment_data_list.append(segment_document)
  2462. position += 1
  2463. pre_segment_data_list.append(segment_document)
  2464. if "keywords" in segment_item:
  2465. keywords_list.append(segment_item["keywords"])
  2466. else:
  2467. keywords_list.append(None)
  2468. # update document word count
  2469. assert document.word_count is not None
  2470. document.word_count += increment_word_count
  2471. db.session.add(document)
  2472. try:
  2473. # save vector index
  2474. VectorService.create_segments_vector(keywords_list, pre_segment_data_list, dataset, document.doc_form)
  2475. except Exception as e:
  2476. logger.exception("create segment index failed")
  2477. for segment_document in segment_data_list:
  2478. segment_document.enabled = False
  2479. segment_document.disabled_at = naive_utc_now()
  2480. segment_document.status = "error"
  2481. segment_document.error = str(e)
  2482. db.session.commit()
  2483. return segment_data_list
  2484. @classmethod
  2485. def update_segment(cls, args: SegmentUpdateArgs, segment: DocumentSegment, document: Document, dataset: Dataset):
  2486. assert isinstance(current_user, Account)
  2487. assert current_user.current_tenant_id is not None
  2488. indexing_cache_key = f"segment_{segment.id}_indexing"
  2489. cache_result = redis_client.get(indexing_cache_key)
  2490. if cache_result is not None:
  2491. raise ValueError("Segment is indexing, please try again later")
  2492. if args.enabled is not None:
  2493. action = args.enabled
  2494. if segment.enabled != action:
  2495. if not action:
  2496. segment.enabled = action
  2497. segment.disabled_at = naive_utc_now()
  2498. segment.disabled_by = current_user.id
  2499. db.session.add(segment)
  2500. db.session.commit()
  2501. # Set cache to prevent indexing the same segment multiple times
  2502. redis_client.setex(indexing_cache_key, 600, 1)
  2503. disable_segment_from_index_task.delay(segment.id)
  2504. return segment
  2505. if not segment.enabled:
  2506. if args.enabled is not None:
  2507. if not args.enabled:
  2508. raise ValueError("Can't update disabled segment")
  2509. else:
  2510. raise ValueError("Can't update disabled segment")
  2511. try:
  2512. word_count_change = segment.word_count
  2513. content = args.content or segment.content
  2514. if segment.content == content:
  2515. segment.word_count = len(content)
  2516. if document.doc_form == "qa_model":
  2517. segment.answer = args.answer
  2518. segment.word_count += len(args.answer) if args.answer else 0
  2519. word_count_change = segment.word_count - word_count_change
  2520. keyword_changed = False
  2521. if args.keywords:
  2522. if Counter(segment.keywords) != Counter(args.keywords):
  2523. segment.keywords = args.keywords
  2524. keyword_changed = True
  2525. segment.enabled = True
  2526. segment.disabled_at = None
  2527. segment.disabled_by = None
  2528. db.session.add(segment)
  2529. db.session.commit()
  2530. # update document word count
  2531. if word_count_change != 0:
  2532. assert document.word_count is not None
  2533. document.word_count = max(0, document.word_count + word_count_change)
  2534. db.session.add(document)
  2535. # update segment index task
  2536. if document.doc_form == IndexType.PARENT_CHILD_INDEX and args.regenerate_child_chunks:
  2537. # regenerate child chunks
  2538. # get embedding model instance
  2539. if dataset.indexing_technique == "high_quality":
  2540. # check embedding model setting
  2541. model_manager = ModelManager()
  2542. if dataset.embedding_model_provider:
  2543. embedding_model_instance = model_manager.get_model_instance(
  2544. tenant_id=dataset.tenant_id,
  2545. provider=dataset.embedding_model_provider,
  2546. model_type=ModelType.TEXT_EMBEDDING,
  2547. model=dataset.embedding_model,
  2548. )
  2549. else:
  2550. embedding_model_instance = model_manager.get_default_model_instance(
  2551. tenant_id=dataset.tenant_id,
  2552. model_type=ModelType.TEXT_EMBEDDING,
  2553. )
  2554. else:
  2555. raise ValueError("The knowledge base index technique is not high quality!")
  2556. # get the process rule
  2557. processing_rule = (
  2558. db.session.query(DatasetProcessRule)
  2559. .where(DatasetProcessRule.id == document.dataset_process_rule_id)
  2560. .first()
  2561. )
  2562. if not processing_rule:
  2563. raise ValueError("No processing rule found.")
  2564. VectorService.generate_child_chunks(
  2565. segment, document, dataset, embedding_model_instance, processing_rule, True
  2566. )
  2567. elif document.doc_form in (IndexType.PARAGRAPH_INDEX, IndexType.QA_INDEX):
  2568. if args.enabled or keyword_changed:
  2569. # update segment vector index
  2570. VectorService.update_segment_vector(args.keywords, segment, dataset)
  2571. else:
  2572. segment_hash = helper.generate_text_hash(content)
  2573. tokens = 0
  2574. if dataset.indexing_technique == "high_quality":
  2575. model_manager = ModelManager()
  2576. embedding_model = model_manager.get_model_instance(
  2577. tenant_id=current_user.current_tenant_id,
  2578. provider=dataset.embedding_model_provider,
  2579. model_type=ModelType.TEXT_EMBEDDING,
  2580. model=dataset.embedding_model,
  2581. )
  2582. # calc embedding use tokens
  2583. if document.doc_form == "qa_model":
  2584. segment.answer = args.answer
  2585. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content + segment.answer])[0] # type: ignore
  2586. else:
  2587. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])[0]
  2588. segment.content = content
  2589. segment.index_node_hash = segment_hash
  2590. segment.word_count = len(content)
  2591. segment.tokens = tokens
  2592. segment.status = "completed"
  2593. segment.indexing_at = naive_utc_now()
  2594. segment.completed_at = naive_utc_now()
  2595. segment.updated_by = current_user.id
  2596. segment.updated_at = naive_utc_now()
  2597. segment.enabled = True
  2598. segment.disabled_at = None
  2599. segment.disabled_by = None
  2600. if document.doc_form == "qa_model":
  2601. segment.answer = args.answer
  2602. segment.word_count += len(args.answer) if args.answer else 0
  2603. word_count_change = segment.word_count - word_count_change
  2604. # update document word count
  2605. if word_count_change != 0:
  2606. assert document.word_count is not None
  2607. document.word_count = max(0, document.word_count + word_count_change)
  2608. db.session.add(document)
  2609. db.session.add(segment)
  2610. db.session.commit()
  2611. if document.doc_form == IndexType.PARENT_CHILD_INDEX and args.regenerate_child_chunks:
  2612. # get embedding model instance
  2613. if dataset.indexing_technique == "high_quality":
  2614. # check embedding model setting
  2615. model_manager = ModelManager()
  2616. if dataset.embedding_model_provider:
  2617. embedding_model_instance = model_manager.get_model_instance(
  2618. tenant_id=dataset.tenant_id,
  2619. provider=dataset.embedding_model_provider,
  2620. model_type=ModelType.TEXT_EMBEDDING,
  2621. model=dataset.embedding_model,
  2622. )
  2623. else:
  2624. embedding_model_instance = model_manager.get_default_model_instance(
  2625. tenant_id=dataset.tenant_id,
  2626. model_type=ModelType.TEXT_EMBEDDING,
  2627. )
  2628. else:
  2629. raise ValueError("The knowledge base index technique is not high quality!")
  2630. # get the process rule
  2631. processing_rule = (
  2632. db.session.query(DatasetProcessRule)
  2633. .where(DatasetProcessRule.id == document.dataset_process_rule_id)
  2634. .first()
  2635. )
  2636. if not processing_rule:
  2637. raise ValueError("No processing rule found.")
  2638. VectorService.generate_child_chunks(
  2639. segment, document, dataset, embedding_model_instance, processing_rule, True
  2640. )
  2641. elif document.doc_form in (IndexType.PARAGRAPH_INDEX, IndexType.QA_INDEX):
  2642. # update segment vector index
  2643. VectorService.update_segment_vector(args.keywords, segment, dataset)
  2644. except Exception as e:
  2645. logger.exception("update segment index failed")
  2646. segment.enabled = False
  2647. segment.disabled_at = naive_utc_now()
  2648. segment.status = "error"
  2649. segment.error = str(e)
  2650. db.session.commit()
  2651. new_segment = db.session.query(DocumentSegment).where(DocumentSegment.id == segment.id).first()
  2652. if not new_segment:
  2653. raise ValueError("new_segment is not found")
  2654. return new_segment
  2655. @classmethod
  2656. def delete_segment(cls, segment: DocumentSegment, document: Document, dataset: Dataset):
  2657. indexing_cache_key = f"segment_{segment.id}_delete_indexing"
  2658. cache_result = redis_client.get(indexing_cache_key)
  2659. if cache_result is not None:
  2660. raise ValueError("Segment is deleting.")
  2661. # enabled segment need to delete index
  2662. if segment.enabled:
  2663. # send delete segment index task
  2664. redis_client.setex(indexing_cache_key, 600, 1)
  2665. # Get child chunk IDs before parent segment is deleted
  2666. child_node_ids = []
  2667. if segment.index_node_id:
  2668. child_chunks = (
  2669. db.session.query(ChildChunk.index_node_id)
  2670. .where(
  2671. ChildChunk.segment_id == segment.id,
  2672. ChildChunk.dataset_id == dataset.id,
  2673. )
  2674. .all()
  2675. )
  2676. child_node_ids = [chunk[0] for chunk in child_chunks if chunk[0]]
  2677. delete_segment_from_index_task.delay([segment.index_node_id], dataset.id, document.id, child_node_ids)
  2678. db.session.delete(segment)
  2679. # update document word count
  2680. assert document.word_count is not None
  2681. document.word_count -= segment.word_count
  2682. db.session.add(document)
  2683. db.session.commit()
  2684. @classmethod
  2685. def delete_segments(cls, segment_ids: list, document: Document, dataset: Dataset):
  2686. assert current_user is not None
  2687. # Check if segment_ids is not empty to avoid WHERE false condition
  2688. if not segment_ids or len(segment_ids) == 0:
  2689. return
  2690. segments_info = (
  2691. db.session.query(DocumentSegment)
  2692. .with_entities(DocumentSegment.index_node_id, DocumentSegment.id, DocumentSegment.word_count)
  2693. .where(
  2694. DocumentSegment.id.in_(segment_ids),
  2695. DocumentSegment.dataset_id == dataset.id,
  2696. DocumentSegment.document_id == document.id,
  2697. DocumentSegment.tenant_id == current_user.current_tenant_id,
  2698. )
  2699. .all()
  2700. )
  2701. if not segments_info:
  2702. return
  2703. index_node_ids = [info[0] for info in segments_info]
  2704. segment_db_ids = [info[1] for info in segments_info]
  2705. total_words = sum(info[2] for info in segments_info if info[2] is not None)
  2706. # Get child chunk IDs before parent segments are deleted
  2707. child_node_ids = []
  2708. if index_node_ids:
  2709. child_chunks = (
  2710. db.session.query(ChildChunk.index_node_id)
  2711. .where(
  2712. ChildChunk.segment_id.in_(segment_db_ids),
  2713. ChildChunk.dataset_id == dataset.id,
  2714. )
  2715. .all()
  2716. )
  2717. child_node_ids = [chunk[0] for chunk in child_chunks if chunk[0]]
  2718. # Start async cleanup with both parent and child node IDs
  2719. if index_node_ids or child_node_ids:
  2720. delete_segment_from_index_task.delay(index_node_ids, dataset.id, document.id, child_node_ids)
  2721. if document.word_count is None:
  2722. document.word_count = 0
  2723. else:
  2724. document.word_count = max(0, document.word_count - total_words)
  2725. db.session.add(document)
  2726. # Delete database records
  2727. db.session.query(DocumentSegment).where(DocumentSegment.id.in_(segment_ids)).delete()
  2728. db.session.commit()
  2729. @classmethod
  2730. def update_segments_status(
  2731. cls, segment_ids: list, action: Literal["enable", "disable"], dataset: Dataset, document: Document
  2732. ):
  2733. assert current_user is not None
  2734. # Check if segment_ids is not empty to avoid WHERE false condition
  2735. if not segment_ids or len(segment_ids) == 0:
  2736. return
  2737. if action == "enable":
  2738. segments = db.session.scalars(
  2739. select(DocumentSegment).where(
  2740. DocumentSegment.id.in_(segment_ids),
  2741. DocumentSegment.dataset_id == dataset.id,
  2742. DocumentSegment.document_id == document.id,
  2743. DocumentSegment.enabled == False,
  2744. )
  2745. ).all()
  2746. if not segments:
  2747. return
  2748. real_deal_segment_ids = []
  2749. for segment in segments:
  2750. indexing_cache_key = f"segment_{segment.id}_indexing"
  2751. cache_result = redis_client.get(indexing_cache_key)
  2752. if cache_result is not None:
  2753. continue
  2754. segment.enabled = True
  2755. segment.disabled_at = None
  2756. segment.disabled_by = None
  2757. db.session.add(segment)
  2758. real_deal_segment_ids.append(segment.id)
  2759. db.session.commit()
  2760. enable_segments_to_index_task.delay(real_deal_segment_ids, dataset.id, document.id)
  2761. elif action == "disable":
  2762. segments = db.session.scalars(
  2763. select(DocumentSegment).where(
  2764. DocumentSegment.id.in_(segment_ids),
  2765. DocumentSegment.dataset_id == dataset.id,
  2766. DocumentSegment.document_id == document.id,
  2767. DocumentSegment.enabled == True,
  2768. )
  2769. ).all()
  2770. if not segments:
  2771. return
  2772. real_deal_segment_ids = []
  2773. for segment in segments:
  2774. indexing_cache_key = f"segment_{segment.id}_indexing"
  2775. cache_result = redis_client.get(indexing_cache_key)
  2776. if cache_result is not None:
  2777. continue
  2778. segment.enabled = False
  2779. segment.disabled_at = naive_utc_now()
  2780. segment.disabled_by = current_user.id
  2781. db.session.add(segment)
  2782. real_deal_segment_ids.append(segment.id)
  2783. db.session.commit()
  2784. disable_segments_from_index_task.delay(real_deal_segment_ids, dataset.id, document.id)
  2785. @classmethod
  2786. def create_child_chunk(
  2787. cls, content: str, segment: DocumentSegment, document: Document, dataset: Dataset
  2788. ) -> ChildChunk:
  2789. assert isinstance(current_user, Account)
  2790. lock_name = f"add_child_lock_{segment.id}"
  2791. with redis_client.lock(lock_name, timeout=20):
  2792. index_node_id = str(uuid.uuid4())
  2793. index_node_hash = helper.generate_text_hash(content)
  2794. max_position = (
  2795. db.session.query(func.max(ChildChunk.position))
  2796. .where(
  2797. ChildChunk.tenant_id == current_user.current_tenant_id,
  2798. ChildChunk.dataset_id == dataset.id,
  2799. ChildChunk.document_id == document.id,
  2800. ChildChunk.segment_id == segment.id,
  2801. )
  2802. .scalar()
  2803. )
  2804. child_chunk = ChildChunk(
  2805. tenant_id=current_user.current_tenant_id,
  2806. dataset_id=dataset.id,
  2807. document_id=document.id,
  2808. segment_id=segment.id,
  2809. position=max_position + 1 if max_position else 1,
  2810. index_node_id=index_node_id,
  2811. index_node_hash=index_node_hash,
  2812. content=content,
  2813. word_count=len(content),
  2814. type="customized",
  2815. created_by=current_user.id,
  2816. )
  2817. db.session.add(child_chunk)
  2818. # save vector index
  2819. try:
  2820. VectorService.create_child_chunk_vector(child_chunk, dataset)
  2821. except Exception as e:
  2822. logger.exception("create child chunk index failed")
  2823. db.session.rollback()
  2824. raise ChildChunkIndexingError(str(e))
  2825. db.session.commit()
  2826. return child_chunk
  2827. @classmethod
  2828. def update_child_chunks(
  2829. cls,
  2830. child_chunks_update_args: list[ChildChunkUpdateArgs],
  2831. segment: DocumentSegment,
  2832. document: Document,
  2833. dataset: Dataset,
  2834. ) -> list[ChildChunk]:
  2835. assert isinstance(current_user, Account)
  2836. child_chunks = db.session.scalars(
  2837. select(ChildChunk).where(
  2838. ChildChunk.dataset_id == dataset.id,
  2839. ChildChunk.document_id == document.id,
  2840. ChildChunk.segment_id == segment.id,
  2841. )
  2842. ).all()
  2843. child_chunks_map = {chunk.id: chunk for chunk in child_chunks}
  2844. new_child_chunks, update_child_chunks, delete_child_chunks, new_child_chunks_args = [], [], [], []
  2845. for child_chunk_update_args in child_chunks_update_args:
  2846. if child_chunk_update_args.id:
  2847. child_chunk = child_chunks_map.pop(child_chunk_update_args.id, None)
  2848. if child_chunk:
  2849. if child_chunk.content != child_chunk_update_args.content:
  2850. child_chunk.content = child_chunk_update_args.content
  2851. child_chunk.word_count = len(child_chunk.content)
  2852. child_chunk.updated_by = current_user.id
  2853. child_chunk.updated_at = naive_utc_now()
  2854. child_chunk.type = "customized"
  2855. update_child_chunks.append(child_chunk)
  2856. else:
  2857. new_child_chunks_args.append(child_chunk_update_args)
  2858. if child_chunks_map:
  2859. delete_child_chunks = list(child_chunks_map.values())
  2860. try:
  2861. if update_child_chunks:
  2862. db.session.bulk_save_objects(update_child_chunks)
  2863. if delete_child_chunks:
  2864. for child_chunk in delete_child_chunks:
  2865. db.session.delete(child_chunk)
  2866. if new_child_chunks_args:
  2867. child_chunk_count = len(child_chunks)
  2868. for position, args in enumerate(new_child_chunks_args, start=child_chunk_count + 1):
  2869. index_node_id = str(uuid.uuid4())
  2870. index_node_hash = helper.generate_text_hash(args.content)
  2871. child_chunk = ChildChunk(
  2872. tenant_id=current_user.current_tenant_id,
  2873. dataset_id=dataset.id,
  2874. document_id=document.id,
  2875. segment_id=segment.id,
  2876. position=position,
  2877. index_node_id=index_node_id,
  2878. index_node_hash=index_node_hash,
  2879. content=args.content,
  2880. word_count=len(args.content),
  2881. type="customized",
  2882. created_by=current_user.id,
  2883. )
  2884. db.session.add(child_chunk)
  2885. db.session.flush()
  2886. new_child_chunks.append(child_chunk)
  2887. VectorService.update_child_chunk_vector(new_child_chunks, update_child_chunks, delete_child_chunks, dataset)
  2888. db.session.commit()
  2889. except Exception as e:
  2890. logger.exception("update child chunk index failed")
  2891. db.session.rollback()
  2892. raise ChildChunkIndexingError(str(e))
  2893. return sorted(new_child_chunks + update_child_chunks, key=lambda x: x.position)
  2894. @classmethod
  2895. def update_child_chunk(
  2896. cls,
  2897. content: str,
  2898. child_chunk: ChildChunk,
  2899. segment: DocumentSegment,
  2900. document: Document,
  2901. dataset: Dataset,
  2902. ) -> ChildChunk:
  2903. assert current_user is not None
  2904. try:
  2905. child_chunk.content = content
  2906. child_chunk.word_count = len(content)
  2907. child_chunk.updated_by = current_user.id
  2908. child_chunk.updated_at = naive_utc_now()
  2909. child_chunk.type = "customized"
  2910. db.session.add(child_chunk)
  2911. VectorService.update_child_chunk_vector([], [child_chunk], [], dataset)
  2912. db.session.commit()
  2913. except Exception as e:
  2914. logger.exception("update child chunk index failed")
  2915. db.session.rollback()
  2916. raise ChildChunkIndexingError(str(e))
  2917. return child_chunk
  2918. @classmethod
  2919. def delete_child_chunk(cls, child_chunk: ChildChunk, dataset: Dataset):
  2920. db.session.delete(child_chunk)
  2921. try:
  2922. VectorService.delete_child_chunk_vector(child_chunk, dataset)
  2923. except Exception as e:
  2924. logger.exception("delete child chunk index failed")
  2925. db.session.rollback()
  2926. raise ChildChunkDeleteIndexError(str(e))
  2927. db.session.commit()
  2928. @classmethod
  2929. def get_child_chunks(
  2930. cls, segment_id: str, document_id: str, dataset_id: str, page: int, limit: int, keyword: str | None = None
  2931. ):
  2932. assert isinstance(current_user, Account)
  2933. query = (
  2934. select(ChildChunk)
  2935. .filter_by(
  2936. tenant_id=current_user.current_tenant_id,
  2937. dataset_id=dataset_id,
  2938. document_id=document_id,
  2939. segment_id=segment_id,
  2940. )
  2941. .order_by(ChildChunk.position.asc())
  2942. )
  2943. if keyword:
  2944. query = query.where(ChildChunk.content.ilike(f"%{keyword}%"))
  2945. return db.paginate(select=query, page=page, per_page=limit, max_per_page=100, error_out=False)
  2946. @classmethod
  2947. def get_child_chunk_by_id(cls, child_chunk_id: str, tenant_id: str) -> ChildChunk | None:
  2948. """Get a child chunk by its ID."""
  2949. result = (
  2950. db.session.query(ChildChunk)
  2951. .where(ChildChunk.id == child_chunk_id, ChildChunk.tenant_id == tenant_id)
  2952. .first()
  2953. )
  2954. return result if isinstance(result, ChildChunk) else None
  2955. @classmethod
  2956. def get_segments(
  2957. cls,
  2958. document_id: str,
  2959. tenant_id: str,
  2960. status_list: list[str] | None = None,
  2961. keyword: str | None = None,
  2962. page: int = 1,
  2963. limit: int = 20,
  2964. ):
  2965. """Get segments for a document with optional filtering."""
  2966. query = select(DocumentSegment).where(
  2967. DocumentSegment.document_id == document_id, DocumentSegment.tenant_id == tenant_id
  2968. )
  2969. # Check if status_list is not empty to avoid WHERE false condition
  2970. if status_list and len(status_list) > 0:
  2971. query = query.where(DocumentSegment.status.in_(status_list))
  2972. if keyword:
  2973. query = query.where(DocumentSegment.content.ilike(f"%{keyword}%"))
  2974. query = query.order_by(DocumentSegment.position.asc())
  2975. paginated_segments = db.paginate(select=query, page=page, per_page=limit, max_per_page=100, error_out=False)
  2976. return paginated_segments.items, paginated_segments.total
  2977. @classmethod
  2978. def get_segment_by_id(cls, segment_id: str, tenant_id: str) -> DocumentSegment | None:
  2979. """Get a segment by its ID."""
  2980. result = (
  2981. db.session.query(DocumentSegment)
  2982. .where(DocumentSegment.id == segment_id, DocumentSegment.tenant_id == tenant_id)
  2983. .first()
  2984. )
  2985. return result if isinstance(result, DocumentSegment) else None
  2986. class DatasetCollectionBindingService:
  2987. @classmethod
  2988. def get_dataset_collection_binding(
  2989. cls, provider_name: str, model_name: str, collection_type: str = "dataset"
  2990. ) -> DatasetCollectionBinding:
  2991. dataset_collection_binding = (
  2992. db.session.query(DatasetCollectionBinding)
  2993. .where(
  2994. DatasetCollectionBinding.provider_name == provider_name,
  2995. DatasetCollectionBinding.model_name == model_name,
  2996. DatasetCollectionBinding.type == collection_type,
  2997. )
  2998. .order_by(DatasetCollectionBinding.created_at)
  2999. .first()
  3000. )
  3001. if not dataset_collection_binding:
  3002. dataset_collection_binding = DatasetCollectionBinding(
  3003. provider_name=provider_name,
  3004. model_name=model_name,
  3005. collection_name=Dataset.gen_collection_name_by_id(str(uuid.uuid4())),
  3006. type=collection_type,
  3007. )
  3008. db.session.add(dataset_collection_binding)
  3009. db.session.commit()
  3010. return dataset_collection_binding
  3011. @classmethod
  3012. def get_dataset_collection_binding_by_id_and_type(
  3013. cls, collection_binding_id: str, collection_type: str = "dataset"
  3014. ) -> DatasetCollectionBinding:
  3015. dataset_collection_binding = (
  3016. db.session.query(DatasetCollectionBinding)
  3017. .where(
  3018. DatasetCollectionBinding.id == collection_binding_id, DatasetCollectionBinding.type == collection_type
  3019. )
  3020. .order_by(DatasetCollectionBinding.created_at)
  3021. .first()
  3022. )
  3023. if not dataset_collection_binding:
  3024. raise ValueError("Dataset collection binding not found")
  3025. return dataset_collection_binding
  3026. class DatasetPermissionService:
  3027. @classmethod
  3028. def get_dataset_partial_member_list(cls, dataset_id):
  3029. user_list_query = db.session.scalars(
  3030. select(
  3031. DatasetPermission.account_id,
  3032. ).where(DatasetPermission.dataset_id == dataset_id)
  3033. ).all()
  3034. return user_list_query
  3035. @classmethod
  3036. def update_partial_member_list(cls, tenant_id, dataset_id, user_list):
  3037. try:
  3038. db.session.query(DatasetPermission).where(DatasetPermission.dataset_id == dataset_id).delete()
  3039. permissions = []
  3040. for user in user_list:
  3041. permission = DatasetPermission(
  3042. tenant_id=tenant_id,
  3043. dataset_id=dataset_id,
  3044. account_id=user["user_id"],
  3045. )
  3046. permissions.append(permission)
  3047. db.session.add_all(permissions)
  3048. db.session.commit()
  3049. except Exception as e:
  3050. db.session.rollback()
  3051. raise e
  3052. @classmethod
  3053. def check_permission(cls, user, dataset, requested_permission, requested_partial_member_list):
  3054. if not user.is_dataset_editor:
  3055. raise NoPermissionError("User does not have permission to edit this dataset.")
  3056. if user.is_dataset_operator and dataset.permission != requested_permission:
  3057. raise NoPermissionError("Dataset operators cannot change the dataset permissions.")
  3058. if user.is_dataset_operator and requested_permission == "partial_members":
  3059. if not requested_partial_member_list:
  3060. raise ValueError("Partial member list is required when setting to partial members.")
  3061. local_member_list = cls.get_dataset_partial_member_list(dataset.id)
  3062. request_member_list = [user["user_id"] for user in requested_partial_member_list]
  3063. if set(local_member_list) != set(request_member_list):
  3064. raise ValueError("Dataset operators cannot change the dataset permissions.")
  3065. @classmethod
  3066. def clear_partial_member_list(cls, dataset_id):
  3067. try:
  3068. db.session.query(DatasetPermission).where(DatasetPermission.dataset_id == dataset_id).delete()
  3069. db.session.commit()
  3070. except Exception as e:
  3071. db.session.rollback()
  3072. raise e