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 147KB

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