Compare commits

..
Author SHA1 Message Date
jyong 85e568e114 compatible query is None 2024-04-03 18:39:29 +08:00
jyong 0026cb404f compatible query is None 2024-04-03 18:38:27 +08:00
JzoNg 62919a9ff5 app list mutation 2024-04-03 18:06:36 +08:00
StyleZhang e13f8da9d5 fix: prompt editor 2024-04-03 18:04:46 +08:00
takatost 53aca1a922 add sys variables for start node 2024-04-03 17:53:54 +08:00
StyleZhang 464aee08a1 fix: prompt editor 2024-04-03 17:45:27 +08:00
Joel ab56e6b6af fix: enable memory add sys query var input 2024-04-03 17:42:21 +08:00
Joel 2a2f4cd4d5 fix: label ui 2024-04-03 17:22:10 +08:00
Joel b3a4a52a7a fix: valid tool valid empty error 2024-04-03 17:18:16 +08:00
Joel 379f9b56ad fix: start node not show sys files 2024-04-03 16:55:55 +08:00
Joel b705041dda chore: remove uage output 2024-04-03 16:52:01 +08:00
takatost fedcfe94ae update version to 0.6.0-preview-workflow.2 2024-04-03 16:50:11 +08:00
Joel add7bdc877 fix: add input instance id 2024-04-03 16:46:47 +08:00
StyleZhang 088842dcdb fix: prompt editor 2024-04-03 16:13:14 +08:00
Joel c43eaeec06 fix: can not open 2024-04-03 15:48:57 +08:00
StyleZhang f06554a11e fix: sync draft 2024-04-03 15:37:19 +08:00
Yeuoly 3ac37e802a fix: sandbox tips 2024-04-03 15:34:05 +08:00
JzoNg aee669f67d fix max length for paragraph 2024-04-03 15:32:59 +08:00
Joel c8db4d8a08 fix: editor choose context would blur 2024-04-03 15:15:35 +08:00
StyleZhang c3bb541a69 fix 2024-04-03 15:13:26 +08:00
StyleZhang ba3039d6c9 merge feat/workflow 2024-04-03 15:00:26 +08:00
Joel bd3b400121 chore: support click to show choose add var 2024-04-03 14:57:16 +08:00
StyleZhang 28e813f57f fix 2024-04-03 14:38:15 +08:00
Joel 3f11e11c2d chore: confirm ui 2024-04-03 14:08:36 +08:00
Yeuoly 37a282cc1c fix: add default lora 2024-04-03 13:51:18 +08:00
JzoNg 88ef220d4d fix app list cache 2024-04-03 13:49:29 +08:00
Yeuoly ccb67bffc4 fix: tools 2024-04-03 13:46:29 +08:00
StyleZhang 20394b3231 fix 2024-04-03 13:39:15 +08:00
nite-knite 52a1c4580c feat: update chat app publishing 2024-04-03 13:12:07 +08:00
JzoNg aca395b97d fix test run 2024-04-03 12:44:32 +08:00
StyleZhang 459b690416 fix: prompt-editor 2024-04-03 12:31:40 +08:00
Yeuoly d48bdf3e14 chore: generic 2024-04-03 12:02:51 +08:00
Joel 9fea2fd44b feat: change from creditical schema value from api 2024-04-03 11:56:54 +08:00
Joel f291aec2cd chore: start input placeholder and bg 2024-04-03 11:41:44 +08:00
takatost 00d9c48461 fix migration version dependency 2024-04-02 22:46:38 +08:00
takatost fef62d937d Merge branch 'main' into feat/workflow 2024-04-02 22:36:27 +08:00
takatost 6b06c5b957 optimize workflow inputs 2024-04-02 22:36:07 +08:00
takatost 5a4ea0932a add inputs for workflow_started event 2024-04-02 21:13:08 +08:00
StyleZhang f7e4f0a988 fix: run error 2024-04-02 21:05:04 +08:00
StyleZhang cf449b31a1 code node rename 2024-04-02 20:48:46 +08:00
StyleZhang f7184c0e36 fix: tool node check 2024-04-02 20:19:50 +08:00
JzoNg 5df66579a8 fix crash of advanced prompt app 2024-04-02 20:12:43 +08:00
StyleZhang d260e6b064 fix: prompt-editor 2024-04-02 19:55:58 +08:00
Yeuoly 01c6a35966 chore: encoder 2024-04-02 19:25:52 +08:00
StyleZhang 0202469254 fix: checklist 2024-04-02 19:06:22 +08:00
Joel fb2fa625b4 fix: use sys query instead user query 2024-04-02 18:46:44 +08:00
Joel fbdf2ba839 fix: classify default two classifies and empty check 2024-04-02 18:41:31 +08:00
Joel 716936e37a fix: remove key replicate 2024-04-02 18:30:57 +08:00
Yeuoly 1c004e0df6 optimize: sd 2024-04-02 18:21:08 +08:00
Joel 59d279fbe0 fix: remove rename check 2024-04-02 18:12:44 +08:00
Joel 2d7c43b60f feat: http panel 2024-04-02 17:45:12 +08:00
Joel a9f7f88a9a feat: answer support render var input 2024-04-02 17:38:05 +08:00
nite-knite 56cb9ccec1 feat: update workflow app publishing 2024-04-02 17:33:35 +08:00
StyleZhang e0a152164b fix: prompt-editor 2024-04-02 17:20:32 +08:00
JzoNg d72524ceb0 hide result info in chatflow 2024-04-02 17:16:39 +08:00
jyong 74538fb3b2 Merge remote-tracking branch 'origin/feat/workflow' into feat/workflow 2024-04-02 16:59:04 +08:00
jyong f832211e2e db migrate merge 2024-04-02 16:58:49 +08:00
Yeuoly e46c3a9235 optimize: tool 2024-04-02 16:58:24 +08:00
JzoNg 36c3774fac modify test run panel 2024-04-02 16:57:28 +08:00
jyong 5e201324d6 Merge branch 'main' into feat/workflow
# Conflicts:
#	api/.env.example
#	docker/docker-compose.yaml
2024-04-02 16:55:43 +08:00
Joel 5adbcacc52 fix: end node can not selector 2024-04-02 15:52:15 +08:00
takatost 8b01796f5d fix external data convert 2024-04-02 15:30:39 +08:00
Joel 34f4f76f67 fix: handle debug run valid 2024-04-02 15:27:03 +08:00
Yeuoly 01e832a587 fix: linter 2024-04-02 15:25:15 +08:00
Yeuoly 1af2d06d29 feat: add tool benchmark 2024-04-02 15:23:54 +08:00
Joel 426abe2134 fix: variable type add missing key 2024-04-02 15:14:00 +08:00
StyleZhang f62775bcad fix: prompt-editor 2024-04-02 14:12:52 +08:00
Joel 7a2083a6b7 fix: num suuport var insert 2024-04-02 14:12:34 +08:00
jyong 09650b9d47 Merge remote-tracking branch 'origin/feat/workflow' into feat/workflow 2024-04-02 14:03:02 +08:00
jyong f19219ab8d fix knowledge retrival 2024-04-02 14:02:49 +08:00
Joel 8be04b57f9 fix: http attr key rerender 2024-04-02 13:55:30 +08:00
StyleZhang ef39fa3fb2 node connect 2024-04-02 13:23:36 +08:00
JzoNg fe569559ac fix app type label 2024-04-02 12:56:11 +08:00
JzoNg 8125d8fc9f modify params of app switch 2024-04-02 12:45:33 +08:00
JzoNg fd8ed95209 fix prompt log 2024-04-02 12:34:40 +08:00
JzoNg cf22842554 support app creation in nav 2024-04-02 12:15:28 +08:00
takatost 0fcb746c08 add created_at for app model config 2024-04-02 12:07:30 +08:00
StyleZhang 9d7ab0400d chat error 2024-04-02 12:01:32 +08:00
Yeuoly 396a3e0456 feat: add tool parameter type converter 2024-04-02 11:58:50 +08:00
Joel 56a1d5330a chore: types 2024-04-02 11:50:03 +08:00
takatost c5e58c713c remove not necessary error reporting 2024-04-02 11:15:50 +08:00
Joel 6e0f13f269 feat: tool new struct 2024-04-02 11:14:33 +08:00
JzoNg 00728c2b1d support type fitlering for app template 2024-04-01 22:55:53 +08:00
JzoNg 9fb7100b3f modify style of app type tag 2024-04-01 22:55:53 +08:00
StyleZhang 4e31d7b64f chat 2024-04-01 21:17:39 +08:00
takatost 1ab3b73c14 add app info for workflow convert 2024-04-01 21:00:08 +08:00
StyleZhang b5fa68fdfe node selected 2024-04-01 20:47:59 +08:00
Yeuoly 31f24e1a14 enhance: enable configurate limitation of code 2024-04-01 20:47:26 +08:00
StyleZhang e800109c02 node selected 2024-04-01 20:33:20 +08:00
Joel 5c3162cc33 fix: http delete btn hide 2024-04-01 19:58:51 +08:00
StyleZhang 04b4be27b7 refresh history 2024-04-01 19:41:37 +08:00
takatost 5793855115 fix http single run 2024-04-01 19:40:49 +08:00
Joel 41cce464ca fix: http var inputs 2024-04-01 19:36:09 +08:00
takatost 8c55ff392d fix bugs 2024-04-01 19:33:53 +08:00
StyleZhang 45d5d259a4 fix prompt editor 2024-04-01 19:03:34 +08:00
Joel e08d871837 fix: http other params check 2024-04-01 18:48:36 +08:00
Joel ab2c112059 feat: reuse get vars inputs and http request url 2024-04-01 18:33:17 +08:00
Joel a42f26d857 fix: object label not pass the right value 2024-04-01 17:52:11 +08:00
Joel 6fea18b4d0 feat: insert var key ui 2024-04-01 17:40:31 +08:00
Joel 7e259600bf fix: debugger form struct and textare line-height 2024-04-01 17:40:31 +08:00
Yeuoly 75e95e09d3 fix: test 2024-04-01 17:07:09 +08:00
StyleZhang 51f225e567 fix 2024-04-01 16:57:42 +08:00
Joel 53c988718b fix: no var caused bugs 2024-04-01 16:57:03 +08:00
Joel 74ead43ae1 fix: query selector set sys value problem 2024-04-01 16:50:09 +08:00
StyleZhang d0509213d1 prompt editor 2024-04-01 16:47:41 +08:00
Yeuoly 5b81234db8 fix: tool entities 2024-04-01 16:43:10 +08:00
StyleZhang df9e2e478f workflow template 2024-04-01 16:38:37 +08:00
takatost 7c64f2cfe0 feat: use en-US recommended apps as fallback if using unmaintained language 2024-04-01 16:24:59 +08:00
takatost 3b3d19dab7 Merge branch 'main' into feat/workflow
# Conflicts:
#	api/controllers/console/explore/recommended_app.py
2024-04-01 16:22:49 +08:00
JzoNg 806f27c370 revert automatic prompt 2024-04-01 16:00:34 +08:00
Yeuoly 86a32517e5 fix: tool variable selectors 2024-04-01 15:42:00 +08:00
takatost 072967a1d3 fix node single step run of answer & http request & llm 2024-04-01 15:24:35 +08:00
StyleZhang 9147e0046f node connect 2024-04-01 14:10:05 +08:00
JzoNg f967203012 remove automatic 2024-04-01 13:31:30 +08:00
Joel e2d0ff4784 chore: run text font size 2024-04-01 13:19:40 +08:00
StyleZhang 85ce2e8df8 merge main 2024-04-01 13:09:40 +08:00
Joel c330f89c77 feat: support llm single run 2024-04-01 12:55:20 +08:00
StyleZhang ffb698922a fix: edge 2024-04-01 12:54:15 +08:00
takatost 50a7c2c92c fix bug 2024-04-01 12:51:01 +08:00
Joel 0843af2996 fix: sys var not show 2024-04-01 12:39:54 +08:00
Joel e9985f0696 chore: enchance debug show name 2024-04-01 12:29:51 +08:00
StyleZhang dfad42075c sys variable 2024-04-01 12:06:22 +08:00
Joel 705d765a71 feat: llm show vars 2024-04-01 11:48:42 +08:00
Joel e03367a188 feat: get input vars 2024-04-01 10:38:12 +08:00
Yeuoly c20685e669 fix 2024-03-29 22:26:26 +08:00
takatost 429dd11dd7 add icon for tool node execution 2024-03-29 22:22:58 +08:00
takatost b394dd6fb0 fix convert bug 2024-03-29 21:43:44 +08:00
takatost a30a6dda63 Merge branch 'main' into feat/workflow
# Conflicts:
#	docker/docker-compose.yaml
2024-03-29 21:18:16 +08:00
takatost de3b7e8815 http request node support template variable 2024-03-29 20:54:17 +08:00
Yeuoly 142d1be4f8 refactor 2024-03-29 20:53:48 +08:00
Yeuoly fb364d44d1 refactor 2024-03-29 20:12:26 +08:00
jyong a647698c32 Merge remote-tracking branch 'origin/feat/workflow' into feat/workflow 2024-03-29 19:44:35 +08:00
jyong 75ffdc9d3f fixed single retrival 2024-03-29 19:44:26 +08:00
StyleZhang 0d12e5c795 run history 2024-03-29 19:32:38 +08:00
jyong bab88efda9 Merge remote-tracking branch 'origin/feat/workflow' into feat/workflow 2024-03-29 19:29:42 +08:00
jyong ca6acf2650 fixed single retrival 2024-03-29 19:29:27 +08:00
Yeuoly 11b428a73f feat: agent log 2024-03-29 19:23:48 +08:00
nite-knite f43faa125b feat: add condition placeholder to if-else node 2024-03-29 19:08:35 +08:00
Joel 6b3bc789b5 fix: http text pass vars 2024-03-29 19:04:53 +08:00
Joel 586488c6a9 feat: llm output and raw text 2024-03-29 19:04:53 +08:00
jyong 704cb42869 Merge remote-tracking branch 'origin/feat/workflow' into feat/workflow
# Conflicts:
#	api/core/workflow/nodes/question_classifier/question_classifier_node.py
2024-03-29 19:00:21 +08:00
jyong 2d26c4745b add history message 2024-03-29 18:58:59 +08:00
takatost 971436d935 llm and answer node support inner variable template 2024-03-29 18:44:30 +08:00
Joel 8a2d04b305 chore: llm editor bg and not flash 2024-03-29 18:32:59 +08:00
StyleZhang 7c45f369d1 checklist 2024-03-29 18:27:41 +08:00
JzoNg 6444d94f41 fix style of app card 2024-03-29 18:24:46 +08:00
Joel a8236a270a feat: body to json editor 2024-03-29 18:19:45 +08:00
StyleZhang 760ada399f checklist 2024-03-29 18:08:27 +08:00
Joel 815262b9a6 chore: remove input vars 2024-03-29 18:02:06 +08:00
Joel 83651a038f feat: http attr support selct keys 2024-03-29 17:55:59 +08:00
Joel 589ac9b22c feat: http key value inputs 2024-03-29 17:24:36 +08:00
StyleZhang d673b4c219 fix: prompt editor 2024-03-29 17:20:48 +08:00
Joel 4e548fff5e feat: add insert var tooltip 2024-03-29 16:58:07 +08:00
Joel 636603d5af chore: type picker 2024-03-29 16:32:36 +08:00
Joel 950a52f4fc feat: input var ui 2024-03-29 16:19:09 +08:00
StyleZhang b50e897aa0 fix: prompt editor 2024-03-29 16:08:10 +08:00
StyleZhang d7be9c0afc prompt editor 2024-03-29 14:59:13 +08:00
StyleZhang 06a6d398cd checklist 2024-03-29 14:56:47 +08:00
Joel 12ed31be4d feat: api support var logic 2024-03-29 14:56:32 +08:00
Joel 8d2ac8ff8f feat: ignore invalid vars keys 2024-03-29 13:56:13 +08:00
Joel 91b84d8f1e chore: http node check 2024-03-29 13:01:36 +08:00
Joel 46cc635e05 fix: error status code 2024-03-29 12:35:04 +08:00
Joel 1ea8504cf1 chore: code output var empty check 2024-03-29 11:48:45 +08:00
Joel a32465eeb8 chore: handle key exists check 2024-03-29 11:37:16 +08:00
Joel f930521d64 chore: start var name check 2024-03-29 11:19:24 +08:00
JzoNg 42ad622a6c fix tool icon 2024-03-28 21:49:56 +08:00
JzoNg 4eb9027510 add icon for tool node in web app 2024-03-28 21:47:10 +08:00
JzoNg 05bb65bd94 add icon for tool node 2024-03-28 21:37:23 +08:00
Yeuoly 85285931e2 feat: add agent tool invoke meta 2024-03-28 20:04:31 +08:00
JzoNg d7c4032917 fix style of app creation 2024-03-28 19:48:45 +08:00
Yeuoly c1466a7a4d Merge branch 'feat/merge-tool-engine' into feat/workflow 2024-03-28 18:44:12 +08:00
Yeuoly 51404f9035 refactor: tool engine 2024-03-28 18:36:58 +08:00
Joel c1bf4c6405 chore: var picker ui 2024-03-28 18:23:05 +08:00
Joel b8818c90b0 feat: answer use selector vars 2024-03-28 17:41:41 +08:00
Joel ead55ce931 chore: support hide editor var search 2024-03-28 17:37:11 +08:00
takatost 0a0d9565ac add icon return for tool node in workflow event stream 2024-03-28 17:26:09 +08:00
StyleZhang 4235baf493 editor 2024-03-28 17:11:39 +08:00
Joel 82a82fff35 chore: llm remove var inputs 2024-03-28 16:54:14 +08:00
Joel 4934a655dd chore: xxx 2024-03-28 16:48:54 +08:00
Joel 615178dafa feat: get var list hooks 2024-03-28 16:44:11 +08:00
Joel 08650339d7 feat: split var reference 2024-03-28 15:27:11 +08:00
StyleZhang 12ea3af242 fix: sync draft 2024-03-28 14:47:09 +08:00
takatost 858ab8c8c4 merge main 2024-03-28 14:38:21 +08:00
takatost 63a4ddc251 add text/plain support for draft sync api 2024-03-28 14:36:24 +08:00
StyleZhang aa4d734244 fix 2024-03-28 12:39:24 +08:00
Joel 85b45a7cd0 fix: http json value would changed 2024-03-28 11:34:31 +08:00
StyleZhang de3fd0f382 fix 2024-03-27 21:00:53 +08:00
JzoNg db3f38bc2b workflow webapp result modification 2024-03-27 18:42:07 +08:00
StyleZhang d239e6bf0f fix 2024-03-27 17:36:16 +08:00
jyong 9e4b39e19f fix question classifier node type 2024-03-27 17:03:49 +08:00
Yeuoly 078b10a9f0 fix: linter 2024-03-27 16:01:09 +08:00
Yeuoly c70d0546ae sign single step files 2024-03-27 16:00:54 +08:00
JzoNg c3d926e2ed templates filtering 2024-03-27 15:49:33 +08:00
Joel 78a851d240 fix: hide readonly tooltip 2024-03-27 14:47:23 +08:00
Yeuoly 6256a3fadb fix: missing datasets 2024-03-27 14:44:04 +08:00
jyong 8def0f8cf2 Merge remote-tracking branch 'origin/feat/workflow' into feat/workflow 2024-03-27 14:19:38 +08:00
jyong a29d3f2400 fix question classifier issue when llm
is completion mode
2024-03-27 14:19:23 +08:00
Joel 794c57b938 fix: code editor readonly can get focus 2024-03-27 13:49:22 +08:00
Joel 9eff8715fb fix: model params in question classify 2024-03-27 13:38:26 +08:00
Yeuoly e952e01dfe fix: sql 2024-03-27 12:28:07 +08:00
Yeuoly a20d305842 fix: missing agent 2024-03-27 12:26:00 +08:00
Yeuoly 17d1e2e5b7 fix: template transform node output length 2024-03-27 11:51:12 +08:00
Joel 1c05d2ef7f fix: questioin classify memory limit 2024-03-27 11:06:51 +08:00
StyleZhang f9caa09cac fix: empty chat 2024-03-27 10:39:41 +08:00
JzoNg 829a7b0d16 Merge branch 'main' into feat/workflow 2024-03-27 10:33:28 +08:00
JzoNg 83aaacd71d app creation update 2024-03-26 18:53:02 +08:00
Joel a56115a664 chore: message type i18n 2024-03-26 18:07:35 +08:00
Joel b5578c754f fix: var too long 2024-03-26 17:18:23 +08:00
Joel de00245af0 fix: not highlight query block 2024-03-26 17:02:41 +08:00
Joel 2c9d4c8dca feat: value support hights 2024-03-26 16:47:38 +08:00
Joel 1ac96564a0 feat: http node hightlight node 2024-03-26 16:35:53 +08:00
StyleZhang c15677634f merge main 2024-03-26 15:25:02 +08:00
Joel 2dd2c8c358 feat: support url highlight 2024-03-26 15:02:34 +08:00
Joel 8e3be982eb feat: chat memory placeholder 2024-03-26 14:19:50 +08:00
Joel 46f4e61edc fix: tools value too long ui 2024-03-26 13:52:35 +08:00
StyleZhang a35b5e4fff chat restart 2024-03-25 18:42:51 +08:00
StyleZhang 07091c9d33 node panel resize 2024-03-25 18:02:09 +08:00
Joel b3db119146 feat: memory example 2024-03-25 16:36:33 +08:00
Joel 28206cac72 feat: move start output var to vars 2024-03-25 15:51:31 +08:00
Joel 47f2fe591d feat: default fold output 2024-03-25 15:24:33 +08:00
Joel acd0e22b9e feat: handle limit tool var type 2024-03-25 15:00:36 +08:00
Joel 2ebd8d9fdc feat: support var search 2024-03-25 14:30:43 +08:00
Joel b5fe1f7c46 chore: var reference support portal 2024-03-25 11:34:56 +08:00
takatost d7b2fe1e8b update docker compose images verison 2024-03-24 00:14:53 +09:00
takatost fac9459402 add workflow image build 2024-03-23 23:19:33 +09:00
takatost 6cf0e0c242 Merge branch 'main' into feat/workflow 2024-03-23 23:09:36 +09:00
takatost 656bd9257d Merge branch 'feat/workflow-backend' into feat/workflow 2024-03-23 23:09:20 +09:00
Yeuoly 38441c930c fix: tool sort 2024-03-23 17:54:40 +08:00
StyleZhang dafdbfa0fd fix: next step tool icon 2024-03-23 12:15:38 +08:00
JzoNg a264973366 hide log panel in web app 2024-03-22 17:23:40 +08:00
Joel 5843b30a13 feat: support var remove in code node 2024-03-22 15:20:09 +08:00
Joel 340ae3c52f feat: remove var check in start node 2024-03-22 15:10:01 +08:00
StyleZhang 817e16493f checklist 2024-03-22 14:58:11 +08:00
Joel 66cf787755 fix: can remove struct 2024-03-22 14:35:22 +08:00
StyleZhang 4f3872277c all tools 2024-03-22 13:08:28 +08:00
Yeuoly 9b84086bac fix: tool provider icon 2024-03-22 12:43:56 +08:00
JzoNg ce2b2755af add description for workflow 2024-03-22 10:30:20 +08:00
takatost a91bec033d fix bug 2024-03-21 22:04:43 +08:00
JzoNg 096cc74373 hide node info in chat 2024-03-21 19:56:43 +08:00
takatost 34db42ecea fix bug 2024-03-21 18:37:37 +08:00
takatost 34e8d2f6bb add message error record 2024-03-21 18:30:23 +08:00
Joel a771d59b1e fix: model param inner ui 2024-03-21 18:14:12 +08:00
JzoNg 3a00941125 fix style of dataset 2024-03-21 18:08:10 +08:00
StyleZhang 8e9ade14df fix: style 2024-03-21 17:49:12 +08:00
JzoNg a1ec45fdd1 fix style of message log operation 2024-03-21 17:47:23 +08:00
Joel 9295739dc0 fix: model trigger ui 2024-03-21 17:45:45 +08:00
StyleZhang 4afb16844c chat stop 2024-03-21 17:30:59 +08:00
takatost c4e6ed1aa2 optimize codes 2024-03-21 17:12:52 +08:00
takatost 95c5848d05 update workflow app bind datasets 2024-03-21 17:06:45 +08:00
JzoNg 8e56096f83 fix style of nav 2024-03-21 16:58:00 +08:00
Joel c8f51dd6db chore: edit code support line wrap 2024-03-21 16:56:49 +08:00
Joel ebbb30de44 fix: wrong infernece 2024-03-21 16:48:53 +08:00
Joel fe1168d15a feat: code var sync 2024-03-21 16:43:36 +08:00
StyleZhang fd7fded6e5 fix: style 2024-03-21 16:34:56 +08:00
Joel 8cffbc6b2a chore: more info to workflows 2024-03-21 16:23:47 +08:00
Yeuoly fa673f9b4c fix: raw text 2024-03-21 16:21:59 +08:00
Joel 178f1fc5d6 fix: tools var renmae problem 2024-03-21 16:15:50 +08:00
Yeuoly 0c409e2b9e enhance: increase code timeout 2024-03-21 16:14:16 +08:00
StyleZhang e366e12be0 fix: running line 2024-03-21 16:12:55 +08:00
Joel 8e0d8fdb3f feat: other nodes support rename and fix knonw set var bug 2024-03-21 16:06:45 +08:00
StyleZhang 524b19bb3a node style 2024-03-21 15:59:20 +08:00
JzoNg fb2e351c08 fix icons 2024-03-21 15:56:20 +08:00
Yeuoly 260fef40c4 enhance: full tools 2024-03-21 15:40:08 +08:00
takatost 72818e946d fix llm memory 2024-03-21 15:36:25 +08:00
Joel e673c64534 feat: llm rename 2024-03-21 15:23:38 +08:00
Joel 93bbb2694f temp publish not check valid 2024-03-21 15:18:10 +08:00
Joel b038b7aa33 fix: can not choose var type 2024-03-21 15:14:54 +08:00
Joel 02a059bdc6 feat: var name rename struct 2024-03-21 15:07:44 +08:00
StyleZhang 267d9568c6 fix: running status 2024-03-21 15:03:49 +08:00
takatost d71eae8f93 fix qc 2024-03-21 15:02:55 +08:00
StyleZhang 8bdaab96b1 fix 2024-03-21 14:25:11 +08:00
takatost a05fcedd61 fix stop 2024-03-21 14:04:22 +08:00
takatost 0db67a2fd3 fix features not publish 2024-03-21 13:47:10 +08:00
JzoNg 6e56a504fd fix docs for advanced-chat 2024-03-21 12:39:46 +08:00
JzoNg 69fa8c9794 add docs for advanced-chat 2024-03-21 12:36:28 +08:00
JzoNg 8dc8650ecb fix type of workflow process 2024-03-21 09:24:09 +08:00
JzoNg 40775e27ce correct api doc of workflow 2024-03-20 23:46:53 +08:00
JzoNg 6fb294202d modify workflow web app output 2024-03-20 23:07:43 +08:00
Yeuoly bd409a3caf enhance: code node validator 2024-03-20 23:01:24 +08:00
takatost 0d0da9a892 fix variable assigner multi route 2024-03-20 22:49:24 +08:00
takatost a7e2f9caf0 fix variable assigner 2024-03-20 22:27:59 +08:00
Joel 3d4d60a353 feat: llm intput only number and str 2024-03-20 22:00:56 +08:00
Joel 75e876b14e chore: reduce more var limit 2024-03-20 21:56:18 +08:00
Joel 66fd60bc6f fix: var objects sorts change 2024-03-20 21:56:18 +08:00
takatost c3e7299494 fix service api blocking mode 2024-03-20 21:55:06 +08:00
StyleZhang 8fc576870d fix 2024-03-20 20:52:19 +08:00
Joel d4f362164f fix: memory support switch 2024-03-20 20:50:16 +08:00
StyleZhang 94ca0edb68 run history 2024-03-20 20:27:52 +08:00
takatost a0dde6e4da fix bug 2024-03-20 20:02:51 +08:00
Joel 17f572f23f feat: can not add context 2024-03-20 19:35:42 +08:00
StyleZhang 137746387d fix style 2024-03-20 19:24:47 +08:00
JzoNg 9b5deaf80a add proccess of workflow in web app 2024-03-20 18:56:03 +08:00
Joel 1201bef879 chore: picker width set 2024-03-20 18:18:34 +08:00
takatost 30a9b8b917 fix bug 2024-03-20 17:52:47 +08:00
takatost 77bdc6ffb1 fix bug 2024-03-20 17:36:56 +08:00
takatost a65c99496b add extra info for workflow stream output 2024-03-20 17:34:07 +08:00
Joel a8c86b759d fix: var02 icon show 2024-03-20 17:31:46 +08:00
StyleZhang 76081db6e4 fix: style 2024-03-20 17:27:45 +08:00
Joel 0606b6f922 fix: remove datasets problem 2024-03-20 17:23:18 +08:00
Joel 9ed2a99abf feat: var reference support readonly 2024-03-20 17:01:53 +08:00
Joel 8f311b020a feat: tools readonly 2024-03-20 16:56:09 +08:00
Yeuoly de6cbc36bb enhance: code return tyoe 2024-03-20 16:54:32 +08:00
Joel 0aa984219f feat: telmplate transform support readonly 2024-03-20 16:52:01 +08:00
Joel c9168c19cd feat: question classify support readonly 2024-03-20 16:48:52 +08:00
Joel beca05848c feat: llm support readonly 2024-03-20 16:43:00 +08:00
StyleZhang 2e5acef1b6 fix 2024-03-20 16:42:13 +08:00
Joel c4811f921f feat: retrieval support readonly 2024-03-20 16:36:49 +08:00
Joel 7569346943 feat: if support readonly 2024-03-20 16:27:41 +08:00
StyleZhang 2919cc9adf fix 2024-03-20 16:25:02 +08:00
JzoNg 18883d9faa fix agent config 2024-03-20 16:20:19 +08:00
Joel e462ddb805 feat: http support readonly 2024-03-20 16:17:04 +08:00
Joel df274416f9 feat: end support readonly 2024-03-20 16:00:41 +08:00
JzoNg b35d9f6c36 fix style of running workflow 2024-03-20 15:54:21 +08:00
Joel 4c5737fc7f feat: code support readonly 2024-03-20 15:53:14 +08:00
Joel 7bb1decaf8 feat: support prompt readonly 2024-03-20 15:46:21 +08:00
StyleZhang 4bef2eed25 chat add workflow process 2024-03-20 15:44:51 +08:00
takatost 0d2a90adf3 fix knowledge retriever return 2024-03-20 15:43:22 +08:00
Joel 38a1ea139a feat: answer support readonly 2024-03-20 15:32:06 +08:00
Joel 698eb9671f feat: start support readonly 2024-03-20 15:09:12 +08:00
Joel 1b857eba29 chore: remove useless 2024-03-20 14:49:39 +08:00
Joel b060b773ef fix: set default logic error 2024-03-20 14:42:35 +08:00
Joel ae197fb2ba fix: switch provider call infinate 2024-03-20 14:42:35 +08:00
StyleZhang 2697454a8e fix 2024-03-20 14:10:43 +08:00
Joel 2a75258836 feat: not show var 2024-03-20 13:55:26 +08:00
takatost b50f221327 fix bug 2024-03-20 12:47:36 +08:00
Joel d984eb3648 chore: workflow editor not choose outtool in var 2024-03-20 12:05:30 +08:00
Joel 4df8fa0afb feat: if change to defalut operator 2024-03-20 11:42:57 +08:00
Joel 67b3ee3776 feat: ifelse check and item choose var first 2024-03-20 11:35:31 +08:00
takatost 8337e3c6ba fix lint 2024-03-20 11:23:33 +08:00
takatost a9b8917e22 fix bug 2024-03-20 11:23:25 +08:00
JzoNg 70698b553e fix prompt log in completion debug 2024-03-20 11:09:03 +08:00
Joel b131c5dc73 fix: code defalut may not switch if not load config 2024-03-20 10:50:43 +08:00
Joel 15e2ab9203 feat: ifelse not set var not change selector 2024-03-20 10:50:43 +08:00
JzoNg d5c79e0489 fix user-inputs generation 2024-03-20 10:45:30 +08:00
jyong 884eeebe83 fix react response 2024-03-20 04:00:50 +08:00
jyong 9042db301d fix page content is empty 2024-03-20 03:50:28 +08:00
takatost f4f8d6c652 Merge branch 'main' into feat/workflow-backend
# Conflicts:
#	api/core/model_runtime/model_providers/anthropic/llm/llm.py
2024-03-20 00:06:33 +08:00
takatost 20cd3e52d0 fix qc bug 2024-03-19 23:55:06 +08:00
takatost 53fa4ffe73 fix bug 2024-03-19 21:53:24 +08:00
takatost 8acd6f2531 fix bug 2024-03-19 21:10:19 +08:00
takatost 8d8bbc586e fix bug 2024-03-19 20:57:07 +08:00
takatost df4e1339da fix convert bug 2024-03-19 20:51:06 +08:00
takatost 0183651cd5 fix stream output 2024-03-19 20:34:43 +08:00
StyleZhang 9f024835aa chat 2024-03-19 20:34:10 +08:00
jyong 45017f3f35 fix knowledge single retrieve when function call response is none 2024-03-19 20:08:16 +08:00
StyleZhang 089072432e chat log 2024-03-19 19:46:14 +08:00
jyong 6e600bc0dc Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-19 19:41:33 +08:00
jyong 25995eb735 fix knowledge single retrieve when function call response is none 2024-03-19 19:41:18 +08:00
JzoNg 28dc089540 fix style of node tracing 2024-03-19 19:24:36 +08:00
StyleZhang 8967c4c8f6 fix 2024-03-19 19:19:47 +08:00
Yeuoly 3969ed6f69 enhance: check valid JSON 2024-03-19 19:01:09 +08:00
JzoNg 56b025ebdd fix import by DSL 2024-03-19 18:57:57 +08:00
JzoNg aab5566d98 fix app switch 2024-03-19 18:49:51 +08:00
Yeuoly a9e44b1fd2 fix: missing head 2024-03-19 18:38:06 +08:00
takatost bae1bc2e4b fix 2024-03-19 18:37:27 +08:00
StyleZhang b9f58d3c1d Merge branch 'main' into feat/workflow 2024-03-19 18:37:09 +08:00
takatostandtakatost 7c7f3958ff feat: optimize ollama model default parameters (#2894) 2024-03-19 18:36:30 +08:00
Lance MaotakatostOSS-MAOLONGDONG\kaihong <maolongdong@kaihong.com>
85da94aac4 fix incorrect exception raised by api tool which leads to incorrect L… (#2886)
Co-authored-by: OSS-MAOLONGDONG\kaihong <maolongdong@kaihong.com>
2024-03-19 18:36:30 +08:00
Su Yangandtakatost 5350753905 chore: update Qwen model params (#2892) 2024-03-19 18:36:30 +08:00
crazywoolaandtakatost e7895cdc53 chore: update pr template (#2893) 2024-03-19 18:36:30 +08:00
Su Yangandtakatost b84d4bdb85 chore: Update TongYi models prices (#2890) 2024-03-19 18:36:30 +08:00
呆萌闷油瓶andtakatost 66538d8cbd feat:support azure openai llm 0125 version (#2889) 2024-03-19 18:36:30 +08:00
Su Yangandtakatost 4e24e116aa chore: use API Key instead of APIKey (#2888) 2024-03-19 18:36:29 +08:00
Bowen Liangandtakatost 3f13c47b9b Bump tiktoken to 0.6.0 to support text-embedding-3-* in encoding_for_model (#2891) 2024-03-19 18:36:29 +08:00
Su Yangandtakatost 10237c99e4 fix: anthropic system prompt not working (#2885) 2024-03-19 18:36:28 +08:00
Su Yangandtakatost faf936416f fix: Fix the problem of system not working (#2884) 2024-03-19 18:36:14 +08:00
crazywoolaandtakatost 779f77ccd6 feat: add icons for 01.ai (#2883) 2024-03-19 18:36:14 +08:00
Su Yangandtakatost 758b8bf812 i18n: update bedrock label (#2879) 2024-03-19 18:36:14 +08:00
c61f51dc5d feat: AWS Bedrock Claude3 (#2864)
Co-authored-by: crazywoola <427733928@qq.com>
Co-authored-by: Chenhe Gu <guchenhe@gmail.com>
2024-03-19 18:36:14 +08:00
Yeuoly b17e30b1c2 fix: form-data 2024-03-19 18:30:13 +08:00
Joel 0756b09cf5 chore: var assigner output 2024-03-19 18:19:07 +08:00
Yeuoly 2f16b3600c fix: avoid space in http key 2024-03-19 18:13:30 +08:00
Yeuoly 55d2417906 fix: invalid http header 2024-03-19 18:12:50 +08:00
Joel 49dd5b76f1 chore: http remove blank to value 2024-03-19 18:08:09 +08:00
Joel 43429108f5 chore: http files 2024-03-19 18:05:32 +08:00
Joel 18159b1a4b feat: valid assignes 2024-03-19 18:03:54 +08:00
StyleZhang b31da3b195 initial node position 2024-03-19 17:59:35 +08:00
takatost 17b7426cc6 fix external_data_tools bug 2024-03-19 17:58:33 +08:00
Joel ba7b9a595b fix: tool invaild 2024-03-19 17:52:43 +08:00
takatost 7778901630 fix tool image render 2024-03-19 17:49:26 +08:00
JzoNg 8f7356cc12 fix completion log item 2024-03-19 17:37:17 +08:00
Joel d49834ee56 feat: if node valid 2024-03-19 17:33:49 +08:00
Joel e4fdf1730e chore: change output 2024-03-19 17:29:40 +08:00
StyleZhang f41a619490 check before publish 2024-03-19 17:24:35 +08:00
jyong 1607fcfaa7 fix knowledge single retrieve when function call response is none 2024-03-19 17:18:29 +08:00
Yeuoly 8386abaed1 fix: file 2024-03-19 17:07:44 +08:00
JzoNg 16a1562900 fix style of tip modal 2024-03-19 17:06:33 +08:00
Joel 9b1869f521 feat: template transform code valid 2024-03-19 16:58:13 +08:00
Joel 3dfcd9ca67 feat: valid question classify 2024-03-19 16:58:13 +08:00
takatost 74408c4ced fix app convert 2024-03-19 16:44:28 +08:00
JzoNg 653917649d add beta tag and fix some style 2024-03-19 16:43:24 +08:00
JzoNg 00f51749a3 add switch operation in app list 2024-03-19 16:18:22 +08:00
Joel 8d3158a6d5 feat: tool valid 2024-03-19 16:14:25 +08:00
StyleZhang dbaf54c93d chat 2024-03-19 16:04:34 +08:00
takatost 7762737796 optimize app list desc 2024-03-19 15:40:03 +08:00
takatost 133d52deb9 fix bug 2024-03-19 15:32:10 +08:00
StyleZhang 0ede136d67 fix: single run sync draft 2024-03-19 15:30:13 +08:00
Joel 8d82d9f7ef fix: overwrite defalut value in tool 2024-03-19 15:27:33 +08:00
JzoNg 1532564601 modify operations in app list 2024-03-19 15:27:14 +08:00
takatost 24ac4996c0 fix bug 2024-03-19 15:20:03 +08:00
takatost 112593119a fix suggested_questions_after_answer 2024-03-19 15:12:29 +08:00
StyleZhang 0c100ac0b1 fix node 2024-03-19 15:07:13 +08:00
Joel 45168d0e00 remove log 2024-03-19 14:55:11 +08:00
Joel dc91b2e3df fix: retieveal output error and var ref error 2024-03-19 14:54:23 +08:00
StyleZhang ced6a5c18b answer node 2024-03-19 14:50:33 +08:00
JzoNg 0b7cdd1e5d node collapse 2024-03-19 14:47:03 +08:00
Joel 67de047122 fix: http not pass headers and so on 2024-03-19 14:42:54 +08:00
jyong 4ec14d8d91 fix knowledge single retrieve when function call response is none 2024-03-19 14:17:22 +08:00
Joel 09516726e9 fix: overwrite template 2024-03-19 13:58:51 +08:00
Joel 6bfd61a887 feat: retrieval check valid 2024-03-19 13:58:51 +08:00
StyleZhang a436550dff workflow info 2024-03-19 13:50:10 +08:00
StyleZhang f5a3069913 sync draft 2024-03-19 13:18:14 +08:00
JzoNg cf0c96e0d1 fix workflow outputs 2024-03-19 12:34:03 +08:00
Joel 978ee93df7 fix: not show sys var type 2024-03-19 11:54:47 +08:00
Joel f3bf4c7730 feat: code default value 2024-03-19 11:36:29 +08:00
Joel d2de16fba2 fix: var list defalut 2024-03-19 10:57:05 +08:00
Joel 90543c458c feat: valid before run struct 2024-03-19 10:46:28 +08:00
JzoNg d6e655eaae fix restart button 2024-03-19 09:43:39 +08:00
JzoNg 9884466ef0 fix judgement of app configure 2024-03-19 09:33:18 +08:00
JzoNg 3b4676d8e9 fix agent configuration 2024-03-19 08:55:47 +08:00
JzoNg 3ee9f74cf8 fix style of completion creation 2024-03-19 08:02:56 +08:00
takatost 1c7573a686 add logging callback for workflow 2024-03-19 04:37:29 +08:00
takatost 2da7cc6928 fix file bugs 2024-03-19 03:56:47 +08:00
JzoNg fda802e796 chore: remove comments 2024-03-18 22:46:19 +08:00
jyong 5a5beb5b59 Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-18 22:38:27 +08:00
jyong a0b16e541c question classifier 2024-03-18 22:38:12 +08:00
JzoNg a67777b8e2 app overview 2024-03-18 22:32:21 +08:00
Joel eae4c80679 fix: input text error 2024-03-18 22:12:46 +08:00
Yeuoly ac63b5385a fix: set code execution timeout 2024-03-18 22:12:21 +08:00
StyleZhang f61ceadec5 fix 2024-03-18 22:03:26 +08:00
Yeuoly 5ff2fbed59 fix: linter 2024-03-18 22:00:35 +08:00
Yeuoly d24cf9e56a limit http response 2024-03-18 22:00:34 +08:00
Joel 7b9fbccf60 feat: support add files and vision 2024-03-18 21:59:51 +08:00
takatost 0b07c6914a fix bugs 2024-03-18 21:52:39 +08:00
jyong f803fb5855 Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-18 21:51:32 +08:00
jyong cd3c2f6b00 knowledge fix 2024-03-18 21:51:23 +08:00
takatost 587ba27f8c fix bugs 2024-03-18 21:42:45 +08:00
takatost 1b0acdbe63 fix message resign url 2024-03-18 21:22:58 +08:00
jyong 3e810bc490 knowledge fix 2024-03-18 21:22:16 +08:00
Yeuoly cc86850ad9 pure: rm file transformer 2024-03-18 21:17:13 +08:00
Yeuoly fed19db938 feat: http download file 2024-03-18 21:16:21 +08:00
takatost 9175eb455f fix context 2024-03-18 21:11:27 +08:00
StyleZhang a89287bf20 block icon 2024-03-18 21:03:02 +08:00
takatost 977020f580 lint fix 2024-03-18 20:59:22 +08:00
takatost a2195c813c fix file render 2024-03-18 20:59:11 +08:00
jyong d5a404236a knowledge fix 2024-03-18 20:54:50 +08:00
JzoNg 202492e5ac message log style modified 2024-03-18 20:54:18 +08:00
Joel 601e888fde feat: handle sys var to run 2024-03-18 20:40:38 +08:00
jyong 4a483a8754 Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-18 20:35:23 +08:00
jyong a4f367b8ff knowledge fix 2024-03-18 20:35:10 +08:00
Yeuoly e225a3d33c linter 2024-03-18 20:22:25 +08:00
Joel 31b6383697 fix: to new sys vars 2024-03-18 20:12:43 +08:00
Yeuoly e7d6def1e8 fix: trim file extension 2024-03-18 19:59:54 +08:00
Yeuoly 197c0bb1a3 fix: jsonable_encoder 2024-03-18 19:56:38 +08:00
Joel d6953f28d3 chore: remove not necessary config 2024-03-18 19:52:40 +08:00
StyleZhang 249f013ca3 fix 2024-03-18 19:50:55 +08:00
takatost 387a6cfee4 remove answer as end 2024-03-18 19:25:18 +08:00
StyleZhang 81cbf2e713 node prev available nodes 2024-03-18 19:22:58 +08:00
jyong e66c55ba9e fix enable annotation reply when collection is None 2024-03-18 19:21:36 +08:00
Joel 56044a104c remove logs 2024-03-18 19:14:21 +08:00
Joel c409ab4c3c feat: knowledge support one sigle 2024-03-18 18:49:01 +08:00
Yeuoly 487efcb206 fix: support deprecated tools 2024-03-18 18:45:29 +08:00
StyleZhang 4eb7546177 workflow publish 2024-03-18 18:45:24 +08:00
Yeuoly 4b561aec93 feat: workflow statistics 2024-03-18 18:44:27 +08:00
takatost 34695f02fb add model config for conversation 2024-03-18 18:25:46 +08:00
takatost aa421269c4 deduct llm quota use llm node func 2024-03-18 18:01:57 +08:00
takatost 09cfbe117e fix annotation bugs 2024-03-18 17:57:10 +08:00
takatost 0ea233edbe Merge branch 'main' into feat/workflow-backend 2024-03-18 17:20:25 +08:00
takatost d69e0a79d4 fix file upload config internal err 2024-03-18 16:55:15 +08:00
Joel 7320ac41af feat: support context and other var reset 2024-03-18 16:50:52 +08:00
takatost 08b1f5d7c3 fix web app bugs 2024-03-18 16:48:31 +08:00
takatost 61b41ca04b fix retriever resource 2024-03-18 16:38:39 +08:00
JzoNg 8d4f40bc7c fix style of chat message log 2024-03-18 16:37:50 +08:00
Joel 3e9c7dccc0 feat: prompt editor set context status setter 2024-03-18 16:25:20 +08:00
StyleZhang 672b8f14f2 chat 2024-03-18 16:14:05 +08:00
StyleZhang 513d075ebc chat 2024-03-18 16:03:57 +08:00
Joel 8d34082246 feat: llm default 2024-03-18 15:56:37 +08:00
jyong 5ed181dd42 knowledge entities fix 2024-03-18 15:54:59 +08:00
JzoNg 9d8f9f6f63 fix app template list filtering 2024-03-18 15:52:02 +08:00
Joel 8e8c39a88c feat: sys var remove nodeid 2024-03-18 15:46:36 +08:00
jyong 41d9fdee50 Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-18 15:40:26 +08:00
jyong 9e37021387 knowledge entities fix 2024-03-18 15:40:11 +08:00
takatost bf06be0c75 fix migration order 2024-03-18 15:37:23 +08:00
takatost a93a2e2e0c Merge branch 'main' into feat/workflow-backend 2024-03-18 15:35:04 +08:00
takatost 02337cbb09 fix answer message save 2024-03-18 15:07:56 +08:00
StyleZhang c35c0fc6f4 chat upload file 2024-03-18 15:04:32 +08:00
Joel 1482eb0348 feat: generation support vars 2024-03-18 14:57:28 +08:00
JzoNg cbe7116bb7 fix data fetching of app list 2024-03-18 14:54:01 +08:00
StyleZhang 788550affa chat upload file 2024-03-18 14:49:40 +08:00
Joel 25949338cb feat: editor history and query 2024-03-18 14:49:15 +08:00
takatost 958da42f74 fix advanced chat answer 2024-03-18 14:28:07 +08:00
JzoNg 6e8ea528c2 fix loading of run 2024-03-18 14:19:47 +08:00
JzoNg d537efe97a refactor run data fetching 2024-03-18 14:15:29 +08:00
JzoNg 0439276866 add tracing panel 2024-03-18 13:24:27 +08:00
takatost 69c8e4ddd1 fix source handle 2024-03-18 13:11:58 +08:00
JzoNg 711f7107b4 fix merge 2024-03-18 13:11:17 +08:00
StyleZhang ea4476ac6e init edges 2024-03-18 12:49:55 +08:00
Joel 13dbc7f0ce feat: handle questioin classify 2024-03-18 11:26:26 +08:00
Joel b8ecfd859b feat: fill single run form variable with constant value first time 2024-03-18 11:03:23 +08:00
Joel 4daf93ef4f feat: form input var type 2024-03-18 10:52:45 +08:00
Joel 90b7ca1df1 chore: merge main 2024-03-18 10:34:57 +08:00
takatost 96f38b2d15 fix bug 2024-03-18 00:13:34 +08:00
takatost 8a27e51658 add Bad Request when generating 2024-03-17 21:40:59 +08:00
takatost 8ecec84dcf Merge branch 'main' into feat/workflow-backend
# Conflicts:
#	api/core/application_manager.py
2024-03-17 21:38:33 +08:00
takatost a2b3096159 add text chunk subscribe for advanced chat blocking mode 2024-03-17 21:36:22 +08:00
takatost 80f1fbba56 add image file as markdown stream outupt 2024-03-17 21:27:08 +08:00
Yeuoly d8ab611480 fix: code 2024-03-17 21:08:41 +08:00
StyleZhang 722ff7795d insert node 2024-03-17 20:19:58 +08:00
takatost 73c2b35dfe add completion app creation back 2024-03-17 16:30:04 +08:00
Yeuoly b99eadecf6 fix: code template 2024-03-17 16:18:15 +08:00
JzoNg 843db3dbdf fix typo 2024-03-17 15:06:53 +08:00
JzoNg 3b660f1698 chat list api 2024-03-17 15:03:37 +08:00
JzoNg a2e30e6aa9 message log 2024-03-17 14:05:56 +08:00
JzoNg 9638885a67 fix prompt log 2024-03-17 12:41:23 +08:00
StyleZhang cd01c890e1 chat record 2024-03-17 09:53:16 +08:00
StyleZhang 552ccb058b stop & restart 2024-03-17 09:25:19 +08:00
takatost 36180b1001 add model support for kr node single_retrieval_config 2024-03-16 22:22:08 +08:00
takatost 65ed4dc91f refactor recommend app api 2024-03-16 22:13:06 +08:00
takatost c709e339b1 fix route 2024-03-16 18:48:16 +08:00
takatost 3cf8416484 add workflow api for installed app & web api & service api 2024-03-16 16:27:39 +08:00
takatost d2d47d0e0e fix bug 2024-03-16 15:09:47 +08:00
StyleZhang 05f97f6e06 fix chat 2024-03-16 15:00:30 +08:00
takatost 11dfdb236d lint fix 2024-03-16 14:45:39 +08:00
takatost 6df520ebc6 add skip ran node 2024-03-16 14:45:16 +08:00
takatost a047a98462 advanced chat support 2024-03-16 14:30:53 +08:00
jyong 1df68a546e variable assigner node 2024-03-16 01:15:40 +08:00
jyong 5013ea09d5 variable assigner node 2024-03-16 00:54:29 +08:00
jyong d92d952e76 Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-16 00:37:15 +08:00
jyong 4af304e6ae question classifier 2024-03-16 00:36:58 +08:00
takatost 5c4d1c52ee add conversation_id & message_id to advanced-chat workflow-runs API 2024-03-15 22:24:00 +08:00
Joel 5ee7fc4fde feat: tools vars limit 2024-03-15 22:15:36 +08:00
takatost b0cf8c00db add created_at return in publish workflow 2024-03-15 22:08:25 +08:00
Joel 338dd1c714 feat: http var limit 2024-03-15 22:04:07 +08:00
Joel af9ae91934 feat: template transform default 2024-03-15 21:58:56 +08:00
takatost d122daca87 fix conversation filter 2024-03-15 21:56:17 +08:00
Joel ec49da073e feat: code default value 2024-03-15 21:54:16 +08:00
takatost 62846be275 refactor app generate pipeline 2024-03-15 21:42:22 +08:00
Joel 6b9cc927c0 feat: llm default value 2024-03-15 21:41:27 +08:00
StyleZhang a577db9ddd stop run 2024-03-15 21:33:51 +08:00
JzoNg e5c8743712 fix elpased time 2024-03-15 21:15:44 +08:00
Joel 777cca1a09 feat: question classify init 2024-03-15 20:50:55 +08:00
StyleZhang e3c65c072c node value init 2024-03-15 20:26:00 +08:00
StyleZhang 9b069bd3d4 node value form 2024-03-15 20:18:19 +08:00
StyleZhang 56c53d1f07 node value init 2024-03-15 20:18:19 +08:00
JzoNg 6146f24932 fix tip of workflow 2024-03-15 20:15:57 +08:00
JzoNg 9908a8bf1f prompt log 2024-03-15 19:55:33 +08:00
StyleZhang e33260d2e2 node value init 2024-03-15 19:51:46 +08:00
jyong 5713ee5fce Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend
# Conflicts:
#	api/constants/languages.py
#	api/controllers/console/app/app.py
#	api/controllers/console/app/model_config.py
2024-03-15 19:50:50 +08:00
StyleZhang 129a68bb06 auto layout 2024-03-15 19:34:50 +08:00
Joel aff5ab933b feat: knowledge node var init value and limit 2024-03-15 19:22:35 +08:00
JzoNg 4835358f24 modify prompt log 2024-03-15 18:26:56 +08:00
jyongandtakatost 9b57b4c6c8 dataset retrival 2024-03-15 18:22:48 +08:00
jyongandtakatost 785dfc5c00 dataset retrival 2024-03-15 18:22:48 +08:00
takatost 12eb236364 answer stream output support 2024-03-15 18:22:48 +08:00
Yeuolyandtakatost 1cfeb989f7 fix: code default output 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost ede65eca4d fix: tool 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost dc53362506 fix: conversation_id equals to none 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 74e644be1c fix: linter 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 6e51ce123c fix: null conversation id 2024-03-15 18:22:47 +08:00
takatost 737321da75 add advanced chat apis support 2024-03-15 18:22:47 +08:00
takatost 72d2f76d24 fix default configs 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 87a36a1fc8 fix: linter 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost c2ded79cb2 fix: node type 2024-03-15 18:22:47 +08:00
takatost fb6e5bf4d5 fix publish route 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 6633a92e1a fix: http 2024-03-15 18:22:47 +08:00
takatost 44c4d5be72 add answer output parse 2024-03-15 18:22:47 +08:00
takatost 5a67c09b48 use answer node instead of end in advanced chatbot 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 0614ddde7d fix: allow None AuthorizationConfig 2024-03-15 18:22:47 +08:00
takatost e5ff06bcb7 fix err typo 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 6b19ba3bb2 enhance: sandbox-docker-compose 2024-03-15 18:22:47 +08:00
takatost 735b55e61b add if-else node 2024-03-15 18:22:47 +08:00
takatost 7e53625eae fix value type 2024-03-15 18:22:47 +08:00
takatost 5213b0aade add sequence_number for workflow_started event 2024-03-15 18:22:47 +08:00
takatost 2b4b6817a3 record inputs and process data when node failed 2024-03-15 18:22:47 +08:00
takatost da3e1e9d14 add deduct quota for llm node 2024-03-15 18:22:47 +08:00
takatost e4794e309a add llm node test 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost e6572ef2d7 fix: linter 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 2182533af8 feat: javascript code 2024-03-15 18:22:47 +08:00
takatost d88ac6c238 add llm node 2024-03-15 18:22:47 +08:00
takatost e8751bebfa fix single step run error 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 92c1da8dbe fix: remove answer 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 951aaf5161 feat: sandbox 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost a420953385 feat: docker-compose 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost b102562614 fix: forward-ref 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 2c2b9e7389 test: template transform 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 513a8655b1 test: tool 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost d3385a2715 feat 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost ebf9c41adb feat: http 2024-03-15 18:22:47 +08:00
jyongandtakatost 7372776992 knowledge node 2024-03-15 18:22:47 +08:00
takatost 7f7269d261 remove unused params in workflow_run_for_list_fields 2024-03-15 18:22:47 +08:00
takatost f2bb0012fd add debug code 2024-03-15 18:22:47 +08:00
takatost 33113034ea add single step run 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 88c29f613f fix: typing 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost f318fa058c feat: add variable selector mapping 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 407bfb8182 feat: add user uid 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 91845fc9f6 fix: linter 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost f911b1c488 feat: support empty code output children 2024-03-15 18:22:47 +08:00
takatost 7a6fa3655f add user for node 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 5eb7b4d56a feat: tool entity 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 5e4bd9fc38 feat: tool node 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost f8cba2679e fix: linter 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost e0883302d2 feat: jinja2 2024-03-15 18:22:47 +08:00
takatost a0a1618869 add tenant_id / app_id / workflow_id for nodes 2024-03-15 18:22:47 +08:00
takatost be68369983 add workflow_app_log codes 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 9d0a832e40 refactor: github actions 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 8031262006 feat: workflow mock test 2024-03-15 18:22:47 +08:00
takatost 751489fa54 modify readme 2024-03-15 18:22:47 +08:00
Yeuolyandtakatost 1e6feadc7e fix: code node dose not work as expected 2024-03-15 18:22:47 +08:00
takatost 2d8497f79b add readme for db connection management in App Runner and Task Pipeline 2024-03-15 18:22:47 +08:00
takatost 61a1aadf9c optimize workflow db connections 2024-03-15 18:22:47 +08:00
takatost 8b832097de optimize db connections 2024-03-15 18:22:45 +08:00
takatost 7e4daf131e optimize db connections 2024-03-15 18:17:05 +08:00
takatost de3978fdbb optimize db connections 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 51f6ab49cf fix: linter 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 2895c3bc8c feat: template transform 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 3d5f9b5a1e fix: missing _extract_variable_selector_to_variable_mapping 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 614bc2e075 feat: http reqeust 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 193bcce236 feat: http request 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost a0fd731170 feat: mapping variables 2024-03-15 18:17:05 +08:00
takatost 2f57d090a1 refactor pipeline and remove node run run_args 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 4c5822fb6e fix: transform 2024-03-15 18:17:05 +08:00
takatost e90637f67a fix generate bug 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 9b0f83f807 fix: add max number array length 2024-03-15 18:17:05 +08:00
takatost fc573564b4 refactor workflow runner 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 5596b3b00b fix: linter 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost cb02b1e12e feat: code 2024-03-15 18:17:05 +08:00
Yeuolyandtakatost 736e386f15 fix: bugs 2024-03-15 18:17:05 +08:00
takatost c152d55f68 fix workflow app bugs 2024-03-15 18:17:05 +08:00
takatost 1a0b6adc2c fix stream bugs 2024-03-15 18:17:05 +08:00
takatost 1914dfea77 fix bugs 2024-03-15 18:17:05 +08:00
takatost 1f986a3abb fix bugs 2024-03-15 18:17:05 +08:00
takatost b174f85237 fix bug 2024-03-15 18:17:05 +08:00
takatost 2ad9c76093 modify migrations 2024-03-15 18:17:05 +08:00
takatost 8684b172d2 add start, end, direct answer node 2024-03-15 18:17:05 +08:00
takatost 3e54cb26be move funcs 2024-03-15 18:17:05 +08:00
takatost 079cc082a3 use callback to filter workflow stream output 2024-03-15 18:17:05 +08:00
takatost a1bc6b50c5 refactor workflow generate pipeline 2024-03-15 18:17:05 +08:00
takatost 7d28fe8ea5 completed workflow engine main logic 2024-03-15 18:17:05 +08:00
takatost dd50deaa43 fix audio voice arg 2024-03-15 18:17:04 +08:00
takatost 79a10e9729 add updated_at to sync workflow api 2024-03-15 18:17:04 +08:00
takatost a5de7b10f3 update ruff check 2024-03-15 18:17:04 +08:00
takatost bc4edbfc2b lint fix 2024-03-15 18:17:04 +08:00
takatost 75f1355d4c add few workflow run codes 2024-03-15 18:17:04 +08:00
takatost 1a86e79d4a lint fix 2024-03-15 18:17:04 +08:00
takatost c8a1f923f5 lint fix 2024-03-15 18:17:04 +08:00
takatost df753e84a3 fix workflow api return 2024-03-15 18:17:04 +08:00
takatost 3086893ee7 fix typo 2024-03-15 18:17:04 +08:00
takatost 242fcf0145 fix typo 2024-03-15 18:17:04 +08:00
takatost de40422205 lint fix 2024-03-15 18:17:04 +08:00
takatost df809ff435 add get default node config 2024-03-15 18:17:04 +08:00
takatost 75559bcbf9 replace block type to node type 2024-03-15 18:17:04 +08:00
takatost d9b8a938c6 use enum instead 2024-03-15 18:17:04 +08:00
takatost e9004a06a5 lint fix 2024-03-15 18:17:04 +08:00
takatost be709d4b84 add AdvancedChatAppGenerateTaskPipeline 2024-03-15 18:17:04 +08:00
takatost 602bc67495 lint fix 2024-03-15 18:17:04 +08:00
takatost e498efce2d refactor app generate 2024-03-15 18:17:04 +08:00
takatost 09dfe80718 add app copy api 2024-03-15 18:17:04 +08:00
takatost 06b05163f6 update app import response 2024-03-15 18:17:04 +08:00
takatost b80092ea12 lint fix 2024-03-15 18:17:04 +08:00
takatost 2eaae6742a lint fix 2024-03-15 18:17:04 +08:00
takatost 3f5d1a79c6 refactor apps 2024-03-15 18:17:04 +08:00
takatost 15c7e0ec2f lint fix 2024-03-15 18:17:04 +08:00
takatost 43b0440358 support workflow features 2024-03-15 18:17:03 +08:00
takatost 9651a208a9 lint fix 2024-03-15 18:15:54 +08:00
takatost 7bff65304f add features structure validate 2024-03-15 18:15:54 +08:00
takatost 8a8882ed8d move workflow_id to app 2024-03-15 18:15:54 +08:00
takatost 9467fe9aa9 lint fix 2024-03-15 18:15:54 +08:00
takatost 799db69e4f refactor app 2024-03-15 18:15:48 +08:00
takatost 896c200211 fix import problem 2024-03-15 18:15:17 +08:00
takatost 3badc4423a fix: wrong default model parameters when creating app 2024-03-15 18:15:17 +08:00
takatost d741527ae4 lint 2024-03-15 18:15:17 +08:00
takatost 77618823a5 add features update api
refactor app model config validation
2024-03-15 18:15:17 +08:00
takatost dd70aeff24 lint fix 2024-03-15 18:15:17 +08:00
takatost 022b7d5dd4 optimize default model exceptions 2024-03-15 18:15:17 +08:00
takatost 11337e51c5 lint fix 2024-03-15 18:15:17 +08:00
takatost 7724d010b6 add app description
add update app api
2024-03-15 18:15:16 +08:00
takatost 124aa9db08 lint fix 2024-03-15 18:15:16 +08:00
takatost 20cf075b2d add workflow runs & workflow node executions api 2024-03-15 18:15:16 +08:00
takatost bf4a5f6b33 lint fix 2024-03-15 18:15:16 +08:00
takatost 03749917f0 add workflow app log api 2024-03-15 18:15:16 +08:00
takatost 7d51d6030b remove publish workflow when app import 2024-03-15 18:15:16 +08:00
takatost 742b87df5e lint fix 2024-03-15 18:15:16 +08:00
takatost a457faa2bf trigger app_model_config_was_updated when app import 2024-03-15 18:15:16 +08:00
takatost 4f50f113dd lint fix 2024-03-15 18:15:16 +08:00
takatost 8b529a3ec7 refactor app api 2024-03-15 18:15:16 +08:00
takatost 84c3ec0ea7 site init move to event handler 2024-03-15 18:15:16 +08:00
takatost c13e8077ba fix agent app converter command 2024-03-15 18:15:16 +08:00
takatost 9f42892b42 lint fix 2024-03-15 18:15:16 +08:00
takatost 27ba5a0bce refactor app mode
add app import and export
2024-03-15 18:15:13 +08:00
takatost 78afba49bf lint fix 2024-03-15 18:13:55 +08:00
takatost a9192bc1c6 make recommended app list api public 2024-03-15 18:13:55 +08:00
takatost 77f04603b3 fix bugs 2024-03-15 18:13:55 +08:00
takatost 34ed5e428c fix bugs 2024-03-15 18:13:55 +08:00
takatost 98cb17e79e lint fix 2024-03-15 18:13:55 +08:00
takatost fce20e483c restore completion app 2024-03-15 18:13:55 +08:00
takatost 97c4733e79 lint fix 2024-03-15 18:13:55 +08:00
takatost 748aa22ee2 add manual convert logic 2024-03-15 18:13:55 +08:00
takatost 2ba7ac8bc1 add expert mode of chatapp convert command 2024-03-15 18:13:55 +08:00
takatost 7458fde5a5 add agent app convert command 2024-03-15 18:13:55 +08:00
takatost f11bf9153d add more tests 2024-03-15 18:13:55 +08:00
takatost 0806b3163a add to http request node convert tests 2024-03-15 18:13:55 +08:00
takatost 45621ba4d7 add api extension to http request node convert 2024-03-15 18:13:55 +08:00
takatost 6aecf42b6e fix prompt transform bugs 2024-03-15 18:13:55 +08:00
takatost 3b234febf5 fix bugs and add unit tests 2024-03-15 18:13:55 +08:00
takatost 8642354a2a lint 2024-03-15 18:13:55 +08:00
takatost c028e5f889 add app convert codes 2024-03-15 18:13:55 +08:00
takatost 3642dd3a73 add workflow logics 2024-03-15 18:13:55 +08:00
takatost 603b1e9ed4 lint 2024-03-15 18:13:55 +08:00
takatost b7c6cba23f add workflow models 2024-03-15 18:13:55 +08:00
takatost d430136f65 lint 2024-03-15 18:13:55 +08:00
takatost 381b3d5016 optimize get app model to wraps 2024-03-15 18:13:55 +08:00
Joel e3f1e143e5 feat: llm context type limit 2024-03-15 18:03:01 +08:00
Joel 9f1cbb2ee7 feat: answer node input limit 2024-03-15 18:03:01 +08:00
StyleZhang d0ef9e672f llm mode 2024-03-15 17:57:46 +08:00
Joel b5c212f575 feat: parse to right datatype and show parse json error 2024-03-15 17:42:00 +08:00
Joel ff5ab43f9c feat: check before run 2024-03-15 17:42:00 +08:00
StyleZhang 68f947c7e0 stop workflow run 2024-03-15 17:24:40 +08:00
StyleZhang e98456b025 store 2024-03-15 16:58:48 +08:00
Joel 75b332695b feat: support string num seletor to single run debug 2024-03-15 16:37:58 +08:00
jyong 3e4bb695e4 dataset retrival 2024-03-15 16:14:32 +08:00
Joel 7ba1b37a5a feat: show assigner panel 2024-03-15 15:23:27 +08:00
Joel 2886255c8b fix: can not get first var type 2024-03-15 15:10:41 +08:00
Joel f7a9564e11 feat: can noe choose selected nodes 2024-03-15 14:44:48 +08:00
jyong c1b0f115d0 dataset retrival 2024-03-15 14:40:53 +08:00
StyleZhang 2203d9a138 available nodes 2024-03-15 14:40:44 +08:00
Joel 5adf94bd7d feat: support filter obj select type 2024-03-15 14:01:25 +08:00
StyleZhang 5fbf8ee6c6 available nodes 2024-03-15 13:24:29 +08:00
Joel 8d9c86ac4c fix: advance setting error 2024-03-15 11:47:53 +08:00
Joel 946ef4c685 chore: remove uselsee lang 2024-03-15 11:31:48 +08:00
Joel c3773bc2d1 chore: add language placeholder 2024-03-15 11:30:39 +08:00
Joel 1b8c8b0a43 feat: node before and after run 2024-03-15 11:26:19 +08:00
StyleZhang 86d2c1184c Merge branch 'main' into feat/workflow 2024-03-15 11:17:18 +08:00
StyleZhang 817aea9f05 fix 2024-03-15 11:04:34 +08:00
StyleZhang 985c07b25b fix 2024-03-15 11:01:47 +08:00
StyleZhang 05ac27dfa8 fix 2024-03-14 21:07:59 +08:00
JzoNg bcce53a929 web app support workflow 2024-03-14 21:02:15 +08:00
JzoNg 58922ba40b add route for workflow app 2024-03-14 21:02:15 +08:00
takatost e6b8b13f2e answer stream output support 2024-03-14 20:50:03 +08:00
Joel ac675c4443 feat: add checkvalid empty fn 2024-03-14 20:44:51 +08:00
Joel ae6a558662 feat: add prev and next nodes 2024-03-14 20:29:47 +08:00
Joel 64e44d1709 chore: direct answer to answer 2024-03-14 19:58:17 +08:00
Yeuoly f35ae2355f fix: code default output 2024-03-14 19:17:27 +08:00
Joel 3a857c83e6 chore: only show has value node in end 2024-03-14 18:46:30 +08:00
Joel d9edcb2250 feat: change to new end node 2024-03-14 18:43:04 +08:00
StyleZhang d129d7951c fix 2024-03-14 18:27:58 +08:00
Joel 5c246285da feat: support node type filter 2024-03-14 17:58:26 +08:00
StyleZhang 19c1722032 node default value 2024-03-14 17:27:42 +08:00
Joel cd9a58231b fix: tool show 2024-03-14 16:40:21 +08:00
Yeuoly d85b5b9134 fix: tool 2024-03-14 16:38:22 +08:00
Joel 8bd74d5abf feat: var picker support choose type 2024-03-14 16:04:15 +08:00
StyleZhang 2af2e2be67 node add 2024-03-14 15:14:31 +08:00
Joel 43a3b827a3 chore: stringify output 2024-03-14 13:43:13 +08:00
Joel 3c6de0bf3e feat: tool default value 2024-03-14 13:43:13 +08:00
Yeuoly 13a724864d fix: conversation_id equals to none 2024-03-14 13:24:48 +08:00
Yeuoly baf536eb2b fix: linter 2024-03-14 12:57:14 +08:00
Yeuoly 5200668336 fix: null conversation id 2024-03-14 12:57:14 +08:00
JzoNg 7eeffb16e2 fix url of webapp 2024-03-14 12:35:12 +08:00
JzoNg 300909341e use app store in overview 2024-03-14 12:27:54 +08:00
JzoNg 277d21cccb fix webapp url 2024-03-14 12:22:08 +08:00
takatost de184051f0 add advanced chat apis support 2024-03-14 12:17:15 +08:00
takatost 95ee72556f fix default configs 2024-03-14 12:12:38 +08:00
Yeuoly f48364914b fix: linter 2024-03-14 11:59:43 +08:00
Yeuoly 19df70efad fix: node type 2024-03-14 11:59:43 +08:00
StyleZhang 9813609645 publish 2024-03-14 11:48:58 +08:00
takatost 975d0a1651 fix publish route 2024-03-14 11:39:18 +08:00
Yeuoly 3c3571713e fix: http 2024-03-14 11:35:51 +08:00
JzoNg aa6254a3b4 add doc for workflow app 2024-03-14 11:31:31 +08:00
JzoNg 0b05d2939a add doc for workflow 2024-03-14 11:31:31 +08:00
JzoNg 6f33163f88 fix app siderbar hook 2024-03-14 11:31:31 +08:00
JzoNg 93101b4d9a add running state for step run 2024-03-14 11:31:31 +08:00
JzoNg d8222a15ca remove useless comments 2024-03-14 11:31:31 +08:00
JzoNg 1728513634 fix sequence number and tokens in result panel 2024-03-14 11:31:31 +08:00
Joel 68fa81ec82 chore: change tool input types 2024-03-14 11:25:27 +08:00
Joel c051c89176 chore: fix http i18n 2024-03-14 11:25:27 +08:00
StyleZhang 8b2a63e545 fix 2024-03-14 11:19:50 +08:00
takatost fcd470fcac add answer output parse 2024-03-13 23:00:28 +08:00
takatost fd8fe15d28 use answer node instead of end in advanced chatbot 2024-03-13 20:54:23 +08:00
Yeuoly e80315f504 fix: allow None AuthorizationConfig 2024-03-13 20:40:37 +08:00
Joel ae9e7acd77 feat: other node run 2024-03-13 18:49:22 +08:00
Joel 149eb38e84 feat: tool single run 2024-03-13 18:43:43 +08:00
Joel d777184fd5 feat: http run 2024-03-13 18:33:08 +08:00
Joel 1653e5eebe feat: template transform 2024-03-13 18:05:17 +08:00
takatost 1f4826ca01 fix err typo 2024-03-13 18:02:19 +08:00
Yeuoly ef700b2688 enhance: sandbox-docker-compose 2024-03-13 17:46:42 +08:00
Joel cedc1bada2 fix: temple transform query selec can not choose var 2024-03-13 17:17:28 +08:00
takatost 0c709afe5c add if-else node 2024-03-13 17:10:51 +08:00
StyleZhang 1c5d07871f hooks 2024-03-13 17:07:03 +08:00
StyleZhang e11fc8c131 init 2024-03-13 17:07:03 +08:00
Joel 2edef89a8d feat: handle system var 2024-03-13 16:38:24 +08:00
StyleZhang cbe7de58ab backup draft 2024-03-13 16:27:04 +08:00
Joel 801160c430 feat: tool output vars 2024-03-13 16:18:46 +08:00
Joel cb2a814296 feat: assign output 2024-03-13 15:58:03 +08:00
Joel db78b91ec2 feat: http output 2024-03-13 15:58:02 +08:00
Joel 25a11c5bb7 feat: question classify output 2024-03-13 15:58:02 +08:00
StyleZhang 1f41521c21 workflow run 2024-03-13 15:38:56 +08:00
Joel e686d42262 feat: support template transform output var 2024-03-13 15:21:51 +08:00
Joel 9bca3f8fd7 feat: code support output var list 2024-03-13 15:17:03 +08:00
takatost 6ef3542c6c fix value type 2024-03-13 15:08:15 +08:00
takatost db299a876e add sequence_number for workflow_started event 2024-03-13 15:01:02 +08:00
takatost 737d04361b record inputs and process data when node failed 2024-03-13 14:55:56 +08:00
Joel 0d2366b432 feat: knowledge output var 2024-03-13 14:52:32 +08:00
Joel b13345ceb2 chore: remove useless and node filter 2024-03-13 14:41:11 +08:00
Joel f15dce9ee3 feat: llm output and var type 2024-03-13 14:37:58 +08:00
StyleZhang b718e66b26 fix: drag stop & click 2024-03-13 13:59:57 +08:00
StyleZhang a55a7603dd split hooks 2024-03-13 11:53:49 +08:00
Joel 64fa343d16 chore: remove log 2024-03-13 11:24:20 +08:00
Joel 6b02eebe36 feat: support start node vars 2024-03-13 11:22:59 +08:00
Joel d0f5318b75 feat: code node can run 2024-03-13 10:43:18 +08:00
takatost 5fe0d50cee add deduct quota for llm node 2024-03-13 00:08:13 +08:00
takatost 4d7caa3458 add llm node test 2024-03-12 23:08:23 +08:00
Yeuoly 856466320d fix: linter 2024-03-12 22:42:28 +08:00
Yeuoly 3bd53556ca feat: javascript code 2024-03-12 22:41:59 +08:00
JzoNg c74854aec0 icon fix 2024-03-12 22:24:23 +08:00
JzoNg 294128d43a fix tracing 2024-03-12 22:21:45 +08:00
takatost 3f59a579d7 add llm node 2024-03-12 22:12:03 +08:00
JzoNg e5cf4ea60e fix result panel 2024-03-12 21:40:41 +08:00
JzoNg 768ca2d3f0 add panel of result 2024-03-12 21:05:15 +08:00
JzoNg 92e9b1bbb1 update style of app list 2024-03-12 21:05:15 +08:00
JzoNg 446932e076 update style of app creation 2024-03-12 21:05:15 +08:00
StyleZhang 0469edcc0c fix 2024-03-12 21:03:45 +08:00
Joel 3823ae5890 chore: prompt to promt template 2024-03-12 20:05:42 +08:00
Joel 14d71fb598 feat: var picker get vars 2024-03-12 20:03:35 +08:00
Joel a031507443 feat: code show result 2024-03-12 19:45:45 +08:00
takatost 4f5c052dc8 fix single step run error 2024-03-12 19:15:11 +08:00
StyleZhang 90e013554c fix 2024-03-12 18:47:24 +08:00
Joel 30ea3cb702 feat: can run code node 2024-03-12 17:59:14 +08:00
StyleZhang a5147a382d fix 2024-03-12 17:44:45 +08:00
Joel 74bf6cd186 feat: add single run api 2024-03-12 16:26:30 +08:00
Yeuoly 15ddbb5e6f fix: remove answer 2024-03-12 16:25:07 +08:00
StyleZhang 547df0b5fe fix 2024-03-12 15:04:52 +08:00
StyleZhang 8ae46a8a14 fix 2024-03-12 13:25:57 +08:00
StyleZhang 9753077661 fix 2024-03-12 13:03:39 +08:00
StyleZhang 22e7393b9d fix 2024-03-12 11:56:15 +08:00
Yeuoly 943c676768 feat: sandbox 2024-03-11 22:14:28 +08:00
Yeuoly 4ecfe1fec5 feat: docker-compose 2024-03-11 22:12:13 +08:00
Yeuoly 5fac4f8737 fix: forward-ref 2024-03-11 21:58:54 +08:00
Yeuoly a5394fa2ce test: template transform 2024-03-11 21:53:08 +08:00
Yeuoly 8dc4d122b9 test: tool 2024-03-11 21:53:08 +08:00
StyleZhang 0eb482f35b chat workflow run 2024-03-11 21:05:54 +08:00
StyleZhang bd52937c88 chat workflow run 2024-03-11 20:54:29 +08:00
jyong d5b321af3f Merge remote-tracking branch 'origin/feat/workflow-backend' into feat/workflow-backend 2024-03-11 20:06:49 +08:00
jyong f3b46bf7e2 knowledge node 2024-03-11 20:06:38 +08:00
Yeuoly 2008986f83 feat 2024-03-11 19:51:31 +08:00
Yeuoly 1a57951d72 feat: http 2024-03-11 19:51:06 +08:00
StyleZhang 7655d7f662 run 2024-03-11 19:35:06 +08:00
takatost 373857d0f2 remove unused params in workflow_run_for_list_fields 2024-03-11 19:04:48 +08:00
takatost 6719af9ba9 add debug code 2024-03-11 18:52:24 +08:00
takatost 19c9091d5b add single step run 2024-03-11 18:49:58 +08:00
StyleZhang 84e2071a32 run 2024-03-11 18:11:01 +08:00
Joel b3b9e1dabb feat: tools support run 2024-03-11 17:33:17 +08:00
Yeuoly 91a35ded18 fix: typing 2024-03-11 16:51:27 +08:00
Yeuoly 2d68594a86 feat: add variable selector mapping 2024-03-11 16:48:28 +08:00
Yeuoly f3d19f9691 feat: add user uid 2024-03-11 16:46:11 +08:00
Yeuoly 94047de8b4 fix: linter 2024-03-11 16:44:36 +08:00
Yeuoly 1c450e27d3 feat: support empty code output children 2024-03-11 16:44:22 +08:00
Joel c0ccffa1c3 chore: no var not show var group 2024-03-11 16:43:13 +08:00
takatost bbc76cb833 add user for node 2024-03-11 16:31:43 +08:00
Yeuoly 94f3cf1a4c feat: tool entity 2024-03-11 16:13:52 +08:00
Joel 2aa8847b78 mrege main 2024-03-11 14:54:29 +08:00
StyleZhang 049e858ef7 run 2024-03-11 14:43:50 +08:00
Yeuoly 8e491ace5c feat: tool node 2024-03-11 13:54:11 +08:00
Yeuoly dcf9d85e8d fix: linter 2024-03-10 21:12:07 +08:00
Yeuoly 460c0da176 feat: jinja2 2024-03-10 20:24:16 +08:00
takatost 295a248561 add tenant_id / app_id / workflow_id for nodes 2024-03-10 20:15:49 +08:00
takatost 4630f9c746 add workflow_app_log codes 2024-03-10 20:02:19 +08:00
Yeuoly ba66beb487 refactor: github actions 2024-03-10 18:41:49 +08:00
Yeuoly b5cb38641a feat: workflow mock test 2024-03-10 18:41:25 +08:00
takatost 4b37d30c0d modify readme 2024-03-10 18:02:05 +08:00
Yeuoly 59ba7917c4 fix: code node dose not work as expected 2024-03-10 17:55:24 +08:00
takatost 8d0ff01a59 add readme for db connection management in App Runner and Task Pipeline 2024-03-10 17:11:39 +08:00
takatost 100fb0c5d6 optimize workflow db connections 2024-03-10 16:59:17 +08:00
takatost b75cd2514e optimize db connections 2024-03-10 16:29:55 +08:00
takatost 7693ba8797 optimize db connections 2024-03-10 15:55:14 +08:00
takatost 3d6b06696e optimize db connections 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 0386061fdf fix: linter 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 3407b4d8dd feat: template transform 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 71ff2a8356 fix: missing _extract_variable_selector_to_variable_mapping 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 8b809b8004 feat: http reqeust 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 707a3a0a66 feat: http request 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost b798aa915c feat: mapping variables 2024-03-10 15:55:14 +08:00
takatost 2db67c4101 refactor pipeline and remove node run run_args 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 80b4db08dc fix: transform 2024-03-10 15:55:14 +08:00
takatost 37cdee5101 fix generate bug 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost b5366cba03 fix: add max number array length 2024-03-10 15:55:14 +08:00
takatost 6cfda369ef refactor workflow runner 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 5a57ed2536 fix: linter 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 13937fc103 feat: code 2024-03-10 15:55:14 +08:00
Yeuolyandtakatost 17cd512284 fix: bugs 2024-03-10 15:55:14 +08:00
takatost 97398ff209 fix workflow app bugs 2024-03-10 15:55:14 +08:00
takatost 2ffb63ff0c fix stream bugs 2024-03-10 15:55:14 +08:00
takatost 90bcb241cc fix bugs 2024-03-10 15:55:14 +08:00
takatost f4f7cfd45a fix bugs 2024-03-10 15:55:14 +08:00
takatost d214c047e9 fix bug 2024-03-10 15:55:14 +08:00
takatost fee8a86880 modify migrations 2024-03-10 15:55:14 +08:00
takatost ea883b5e48 add start, end, direct answer node 2024-03-10 15:55:14 +08:00
takatost 46296d777c move funcs 2024-03-10 15:55:14 +08:00
takatost 79f0e894e9 use callback to filter workflow stream output 2024-03-10 15:55:14 +08:00
takatost 6372183471 refactor workflow generate pipeline 2024-03-10 15:55:14 +08:00
takatost 5963e7d1c5 completed workflow engine main logic 2024-03-10 15:55:14 +08:00
takatost c7618fc377 fix audio voice arg 2024-03-10 15:55:14 +08:00
takatost 3fc932b041 add updated_at to sync workflow api 2024-03-10 15:55:14 +08:00
takatost 97cdc96f7c update ruff check 2024-03-10 15:55:14 +08:00
takatost 892fe927c2 lint fix 2024-03-10 15:55:14 +08:00
takatost d51d456d80 add few workflow run codes 2024-03-10 15:55:14 +08:00
takatost 836376c6c8 lint fix 2024-03-10 15:55:14 +08:00
takatost fa29eadb7a lint fix 2024-03-10 15:55:14 +08:00
takatost 0cc0065f8c fix workflow api return 2024-03-10 15:55:14 +08:00
takatost c3eac450ce fix typo 2024-03-10 15:55:14 +08:00
takatost 7b738e045e fix typo 2024-03-10 15:55:14 +08:00
takatost 3f6c17247f lint fix 2024-03-10 15:55:14 +08:00
takatost 0551a9bfcd add get default node config 2024-03-10 15:55:14 +08:00
takatost 7c149ebf4f replace block type to node type 2024-03-10 15:55:14 +08:00
takatost 37b70eb73e use enum instead 2024-03-10 15:55:14 +08:00
takatost 451ea5308f lint fix 2024-03-10 15:55:14 +08:00
takatost a4d6954d4f add AdvancedChatAppGenerateTaskPipeline 2024-03-10 15:55:14 +08:00
takatost c786533f22 lint fix 2024-03-10 15:55:13 +08:00
takatost 406a625c98 refactor app generate 2024-03-10 15:55:13 +08:00
takatost 171b2bdc20 add app copy api 2024-03-10 15:55:13 +08:00
takatost 4266ce73cb update app import response 2024-03-10 15:55:13 +08:00
takatost afa920cc94 lint fix 2024-03-10 15:55:13 +08:00
takatost 701f116be3 lint fix 2024-03-10 15:55:13 +08:00
takatost 5c7ea08bdf refactor apps 2024-03-10 15:55:12 +08:00
takatost 5e38996222 lint fix 2024-03-10 15:54:10 +08:00
takatost 18febeabd1 support workflow features 2024-03-10 15:54:10 +08:00
takatost be1500bf7d lint fix 2024-03-10 15:54:10 +08:00
takatost fea549679a add features structure validate 2024-03-10 15:54:10 +08:00
takatost 11e1b569ea move workflow_id to app 2024-03-10 15:54:10 +08:00
takatost 2bbf96d762 lint fix 2024-03-10 15:54:10 +08:00
takatost 70394bae52 refactor app 2024-03-10 15:54:08 +08:00
takatost 0c9e112f41 fix import problem 2024-03-10 15:52:45 +08:00
takatost 607b84d929 fix: wrong default model parameters when creating app 2024-03-10 15:52:45 +08:00
takatost 7a13cd1530 lint 2024-03-10 15:52:45 +08:00
takatost 9b1afb68eb add features update api
refactor app model config validation
2024-03-10 15:52:45 +08:00
takatost cf9d2965bf lint fix 2024-03-10 15:52:45 +08:00
takatost b1328c193b optimize default model exceptions 2024-03-10 15:52:45 +08:00
takatost 3d222caaae lint fix 2024-03-10 15:52:45 +08:00
takatost 77ac6fa356 add app description
add update app api
2024-03-10 15:52:45 +08:00
takatost a3b46006a8 lint fix 2024-03-10 15:52:45 +08:00
takatost ea4716d039 add workflow runs & workflow node executions api 2024-03-10 15:52:45 +08:00
takatost db9e7a53f8 lint fix 2024-03-10 15:52:45 +08:00
takatost 4432e055be add workflow app log api 2024-03-10 15:52:45 +08:00
takatost 403c2f436d remove publish workflow when app import 2024-03-10 15:52:45 +08:00
takatost 594de43dec lint fix 2024-03-10 15:52:45 +08:00
takatost 2e68c3fc11 trigger app_model_config_was_updated when app import 2024-03-10 15:52:45 +08:00
takatost 2187f6f62e lint fix 2024-03-10 15:52:45 +08:00
takatost 9249c38bf9 refactor app api 2024-03-10 15:52:44 +08:00
takatost 67e0ba5167 site init move to event handler 2024-03-10 15:52:10 +08:00
takatost 9004d8c3cd fix agent app converter command 2024-03-10 15:52:10 +08:00
takatost 4df424438d lint fix 2024-03-10 15:52:10 +08:00
takatost 6e3cd62e31 refactor app mode
add app import and export
2024-03-10 15:52:09 +08:00
takatost 61b4bedc16 lint fix 2024-03-10 15:51:36 +08:00
takatost 4e5de036c6 make recommended app list api public 2024-03-10 15:51:36 +08:00
takatost 8e54b2e3f2 fix bugs 2024-03-10 15:51:36 +08:00
takatost d39a51c134 fix bugs 2024-03-10 15:51:36 +08:00
takatost 6efc3d4913 lint fix 2024-03-10 15:51:35 +08:00
takatost 55c31eec31 restore completion app 2024-03-10 15:51:35 +08:00
takatost 9820dcb201 lint fix 2024-03-10 15:51:35 +08:00
takatost 9f29ce9591 add manual convert logic 2024-03-10 15:51:35 +08:00
takatost afb0ff37bd add expert mode of chatapp convert command 2024-03-10 15:51:35 +08:00
takatost 67b6f08d89 add agent app convert command 2024-03-10 15:51:35 +08:00
takatost 892036bd7d add more tests 2024-03-10 15:51:35 +08:00
takatost d123ddedc8 add to http request node convert tests 2024-03-10 15:51:35 +08:00
takatost fc243982e5 add api extension to http request node convert 2024-03-10 15:51:35 +08:00
takatost df66cd2205 fix prompt transform bugs 2024-03-10 15:51:35 +08:00
takatost a44d3c3eda fix bugs and add unit tests 2024-03-10 15:51:35 +08:00
takatost 297b33aa41 lint 2024-03-10 15:51:35 +08:00
takatost 0d858cc036 add app convert codes 2024-03-10 15:51:35 +08:00
takatost f067947266 add workflow logics 2024-03-10 15:51:35 +08:00
takatost 9ad6bd78f5 lint 2024-03-10 15:51:35 +08:00
takatost b1e220f2d2 add workflow models 2024-03-10 15:51:35 +08:00
takatost 200dc56c37 lint 2024-03-10 15:51:35 +08:00
takatost 49992925e2 optimize get app model to wraps 2024-03-10 15:51:33 +08:00
JzoNg 405e99d27f fix api url of workflow run 2024-03-09 13:03:22 +08:00
JzoNg 90ee7fe201 tracing 2024-03-09 12:48:14 +08:00
JzoNg bc90fc885f tracing node style update 2024-03-09 11:06:25 +08:00
JzoNg 5afa5fb085 app switch 2024-03-09 10:30:26 +08:00
JzoNg 93e2dc4f5f workflow log result 2024-03-08 21:10:11 +08:00
StyleZhang 08d2a4279f cache toolsmap 2024-03-08 18:36:48 +08:00
StyleZhang d79b686992 block selector 2024-03-08 18:10:30 +08:00
Joel 1adec7ab51 feat: tool auth 2024-03-08 17:13:24 +08:00
Joel 3b029f2387 feat: tool auth 2024-03-08 17:13:24 +08:00
JzoNg 6d6afe8f52 fix app mode in logs 2024-03-08 17:11:33 +08:00
StyleZhang e307947dd8 node control 2024-03-08 17:02:02 +08:00
JzoNg 04ad1eef79 workflow logs 2024-03-08 16:43:41 +08:00
StyleZhang 2b475b7916 help line 2024-03-08 16:02:28 +08:00
Joel f51f4a5843 feat: tool inputs 2024-03-08 15:43:11 +08:00
JzoNg b5f3bbead2 update cache in appNav after app info updated 2024-03-08 14:48:10 +08:00
Joel a192ae9314 feat: remove useless file 2024-03-08 14:37:29 +08:00
Joel 7a07d8c2bc feat: tool params 2024-03-08 14:32:33 +08:00
StyleZhang 17a67e7922 remove annatation 2024-03-08 13:46:14 +08:00
StyleZhang 328a3e2e6b node about author 2024-03-08 13:24:59 +08:00
JzoNg 597053c30e fix style of app info 2024-03-08 11:46:25 +08:00
JzoNg 29bef1e3ab app sidebar auto collapse 2024-03-08 11:46:25 +08:00
JzoNg e36d62f08c hide switch modal 2024-03-08 11:46:25 +08:00
JzoNg 50b4c7fa18 switch app 2024-03-08 11:46:25 +08:00
JzoNg d86ef15d9a add tip for switch 2024-03-08 11:46:25 +08:00
JzoNg fa3eb11b6a old app do not support duplicate and export dsl 2024-03-08 11:46:25 +08:00
JzoNg beff31b003 update style app config 2024-03-08 11:46:25 +08:00
StyleZhang 2360fb293b update data 2024-03-08 11:27:05 +08:00
Joel 1c82e3870a feat: not choose model hide in node 2024-03-08 11:06:32 +08:00
Joel 49ce9d2200 feat: http support debug and remove mock init debug data 2024-03-08 10:59:49 +08:00
Joel c20c9b53e1 feat: template tranform support debug 2024-03-08 10:40:12 +08:00
Joel 89fc90ac80 chore: code support debug 2024-03-08 10:36:57 +08:00
StyleZhang 072f5caa06 init 2024-03-07 19:43:11 +08:00
Joel 783f7a9b13 feat: question classifer support run 2024-03-07 18:43:19 +08:00
Joel 425e162a91 feat: knowledge support single run 2024-03-07 18:36:45 +08:00
Joel 55b5d76e0b chore: move node run data to node hooks 2024-03-07 18:13:56 +08:00
Joel 9693d014ba feat: add llm debug 2024-03-07 17:48:18 +08:00
StyleZhang 16abcf082c node control 2024-03-07 17:09:04 +08:00
StyleZhang 173336f256 node handle 2024-03-07 15:58:46 +08:00
Joel f37316f2a0 feat: single run modal 2024-03-07 15:15:39 +08:00
StyleZhang e044e8efaa chat mode 2024-03-07 14:35:13 +08:00
StyleZhang af99a55552 chat mode 2024-03-07 14:24:27 +08:00
StyleZhang 8f3d9d0149 panel 2024-03-07 13:54:02 +08:00
StyleZhang 344e30bef4 node 2024-03-07 12:15:51 +08:00
StyleZhang 45ef4059f0 block-icon 2024-03-07 11:48:42 +08:00
StyleZhang 13174aac18 debug and preview 2024-03-07 11:21:59 +08:00
StyleZhang 74f02363f4 record 2024-03-07 10:48:11 +08:00
Joel 10c421a94c Merge branch 'main' into feat/workflow 2024-03-07 10:35:05 +08:00
StyleZhang 3162227b54 features 2024-03-06 19:43:47 +08:00
JzoNg 7e647cc6e7 fix page title update 2024-03-06 19:14:25 +08:00
StyleZhang ec710d7ffd Merge branch 'main' into feat/workflow 2024-03-06 19:05:21 +08:00
StyleZhang 36718c39dc features 2024-03-06 19:04:06 +08:00
JzoNg fca9753140 fix app detail update 2024-03-06 18:42:37 +08:00
Joel 0529c3d5d2 feat: add role tooltip and fix add prompt error 2024-03-06 18:36:35 +08:00
Joel 5a27a95f8d feat: llm support type select 2024-03-06 18:11:14 +08:00
Joel 5ec3a967b5 feat: all other code expand 2024-03-06 17:59:58 +08:00
StyleZhang a45ec15a56 features 2024-03-06 17:48:01 +08:00
StyleZhang 0164dec438 features 2024-03-06 17:46:42 +08:00
JzoNg 4edaa95cbf app menu 2024-03-06 17:39:27 +08:00
JzoNg 067e6b5ae7 app detail redirection 2024-03-06 17:39:27 +08:00
Joel 6adb986167 feat: expend toggle 2024-03-06 16:56:18 +08:00
Joel cc4ca942c9 feat: prompt editor blur and focus ui 2024-03-06 15:38:45 +08:00
Joel 3202f12cb8 feat: config prompt 2024-03-06 15:17:51 +08:00
StyleZhang 6448d71ca6 draft updated at 2024-03-06 14:35:47 +08:00
StyleZhang e3a3e07eef tool 2024-03-06 14:04:15 +08:00
Joel 8a906e2959 fix: http nodes update error and support json 2024-03-06 11:34:07 +08:00
Joel 9839b5cb53 fix: enchance code editor syle 2024-03-06 11:23:42 +08:00
StyleZhang 430569d486 app detail 2024-03-05 17:38:32 +08:00
Joel d3dfadbd9b feat: add code editor 2024-03-05 17:37:20 +08:00
StyleZhang e474e02a50 sync workflow draft 2024-03-05 17:11:54 +08:00
StyleZhang 54d9cdaabf sync workflow draft 2024-03-05 17:11:54 +08:00
Joel 76fe3c1d76 fix: question classifer can not edit 2024-03-05 16:13:24 +08:00
StyleZhang 261e56e61d single run 2024-03-05 15:57:10 +08:00
StyleZhang ede0bb5396 control run 2024-03-05 15:28:28 +08:00
JzoNg 186b85cd62 add store of app detail 2024-03-05 15:27:52 +08:00
Joel eab405af5b chore: node add memo 2024-03-05 15:26:28 +08:00
Joel 93999cec56 chore: panel memo 2024-03-05 14:54:59 +08:00
StyleZhang acacc0a4cb service 2024-03-05 14:44:13 +08:00
Joel b2ae7089dc fix: var assigner 2024-03-05 14:40:21 +08:00
Joel d4ab6b294a fix: llm default 2024-03-05 14:35:12 +08:00
Joel e6d89f6756 fix: start node add 2024-03-05 14:27:52 +08:00
Joel 7ec29bbee7 feat: node add default value 2024-03-05 14:27:52 +08:00
StyleZhang f1d44a4c87 zoom in out 2024-03-05 14:15:05 +08:00
StyleZhang 466f16eb1d node name 2024-03-05 13:05:36 +08:00
StyleZhang 04d54c0319 fix 2024-03-05 12:40:56 +08:00
StyleZhang 0367a2148a bg 2024-03-05 12:36:59 +08:00
Joel 57e9e229de temp 2024-03-05 12:35:36 +08:00
StyleZhang 90c8d9d27b service 2024-03-05 11:57:51 +08:00
Joel a30b6acc52 fix: start node 2024-03-05 11:30:45 +08:00
Joel 0ee7f952ef fix: start node 2024-03-05 11:27:24 +08:00
Joel 86656de971 feat: classify data panel node sync 2024-03-05 11:06:35 +08:00
JzoNg 2e649c3329 add icon of yaml 2024-03-05 09:03:52 +08:00
StyleZhang e868e44025 help line 2024-03-04 20:35:01 +08:00
Joel 4376813951 feat: get and set data use context 2024-03-04 20:14:18 +08:00
StyleZhang ccd3e519ea edges change 2024-03-04 19:01:38 +08:00
StyleZhang c4ca3bd34d rename data 2024-03-04 18:18:47 +08:00
StyleZhang 081baae883 operator 2024-03-04 17:45:41 +08:00
StyleZhang a3d4befad4 service 2024-03-04 17:45:41 +08:00
Joel 2f13d2775f Merge branch 'main' into feat/workflow 2024-03-04 17:40:52 +08:00
Joel a36a2a1080 feat: handleupdate logic 2024-03-04 17:04:53 +08:00
Joel 474c7865d7 feat: get and set value from store 2024-03-04 15:51:05 +08:00
StyleZhang bd205f63cc fix: workflow route 2024-03-04 14:53:48 +08:00
Joel ac40eb8d87 chore: add missing jp files 2024-03-04 10:44:34 +08:00
Joel 3ea06d286a merge main 2024-03-04 10:41:33 +08:00
JzoNg 8d6984e286 create app by import yaml 2024-03-03 15:37:47 +08:00
JzoNg cd773b8cc9 app import supported 2024-03-03 14:25:50 +08:00
JzoNg 9bca69ebfb app DSL export supported 2024-03-03 14:10:11 +08:00
JzoNg b33da6a09c duplicate app supported 2024-03-03 13:41:14 +08:00
JzoNg 7ae23d5567 add redirection 2024-03-03 13:24:58 +08:00
JzoNg 569315ee3e add tip for chatbot orchestrate 2024-03-03 12:39:07 +08:00
JzoNg 4c7941adef app creation 2024-03-02 16:47:43 +08:00
JzoNg 93d116a9d0 add tracing panel 2024-03-02 14:05:05 +08:00
JzoNg 7b2499c292 add meta data of run log 2024-03-02 11:16:23 +08:00
JzoNg 2be2bc5877 add run log status 2024-03-02 09:59:31 +08:00
JzoNg cfb853efbf log detail panel 2024-03-01 20:32:22 +08:00
JzoNg 2691164fc4 workflow log list 2024-03-01 20:32:22 +08:00
StyleZhang b113711a86 hooks 2024-03-01 20:22:06 +08:00
StyleZhang 68e9530507 run by single 2024-03-01 19:09:27 +08:00
StyleZhang 0ca23bb840 features 2024-03-01 18:20:49 +08:00
StyleZhang 6e3d6c4269 features 2024-03-01 18:20:49 +08:00
Joel c2eaa32036 temp 2024-03-01 17:09:53 +08:00
Joel 604930db64 feat: support detect when to show vision config 2024-03-01 16:43:56 +08:00
Joel c3f99779f2 feat: vision config 2024-03-01 16:30:24 +08:00
Joel 0518da1e49 feat: handle llm memory 2024-03-01 15:07:29 +08:00
Joel 6f6f032244 feat: choose context var 2024-03-01 14:35:37 +08:00
StyleZhang 0acb2db9b6 layout 2024-03-01 14:29:02 +08:00
Joel 74d26764f8 feat: knowledge retrieval dataset setting 2024-03-01 13:56:52 +08:00
Joel cf77a89123 feat: dasetitem ui 2024-03-01 11:38:24 +08:00
StyleZhang 1b73632f77 utils 2024-03-01 11:27:30 +08:00
Joel 0a7cbf6fde feat: dataset list struct 2024-02-29 20:26:51 +08:00
Joel e4701e26c8 feat: add datasets 2024-02-29 20:03:26 +08:00
Joel 045156985a fix: not show rerank modal picker 2024-02-29 19:39:27 +08:00
Joel 257e795ca9 feat: retrieval config 2024-02-29 18:24:15 +08:00
StyleZhang bafdc510d6 record panel 2024-02-29 17:33:49 +08:00
StyleZhang 1840d05a37 record panel 2024-02-29 17:27:08 +08:00
Joel 6d5618447e feat: knowledge retirveval output 2024-02-29 16:39:36 +08:00
Joel b2de27b7be feat: knowledge query var 2024-02-29 15:48:48 +08:00
Joel 9c0d44fa09 feat: llm node support config memroy 2024-02-29 15:36:25 +08:00
Joel f95eb2df0d feat: filed fold 2024-02-29 15:26:06 +08:00
Joel cbb298ccb6 feat: config conversation role name 2024-02-29 15:17:20 +08:00
Joel 9e6940ed3e feat: mermory size config 2024-02-29 14:50:36 +08:00
Joel fbcc769d4e feat: instructions 2024-02-29 11:50:46 +08:00
Joel 65f0378e43 feat: classlist crud 2024-02-29 11:37:53 +08:00
Joel f7a90f2660 merge main 2024-02-29 10:59:21 +08:00
StyleZhang 3d825dcb3e add features 2024-02-28 20:58:00 +08:00
StyleZhang 2094a554f6 multiple edge 2024-02-28 20:58:00 +08:00
Joel 4837ae4958 feat: question add class 2024-02-28 20:49:12 +08:00
Joel 6da9950b72 feat: workflow to auth 2024-02-28 20:19:22 +08:00
StyleZhang e8921787b3 hooks 2024-02-28 20:11:24 +08:00
StyleZhang d2d6904c9b panel-operator 2024-02-28 20:11:23 +08:00
Joel 510f0593e9 chore: question classify 2024-02-28 19:54:20 +08:00
Joel 7a438f8999 chore: assign var 2024-02-28 19:49:01 +08:00
Joel 113af85c3c chore: add requierd 2024-02-28 18:32:36 +08:00
Joel 916bacb60e chore: remove auto show modal 2024-02-28 18:17:39 +08:00
Joel a98b5ca97e chore: auth i18n 2024-02-28 18:11:09 +08:00
Joel 076fe8ca3a feat: auth struct 2024-02-28 17:37:31 +08:00
Joel b08327cb4b feat: edit body 2024-02-28 16:25:09 +08:00
StyleZhang f1b868d5d9 next step 2024-02-28 16:19:57 +08:00
Joel 76ff004ea5 feat: bulk edit 2024-02-28 15:01:58 +08:00
Joel df173764d2 chore: replace remove btn 2024-02-28 13:54:11 +08:00
Joel 7fa25934af feat: key value input 2024-02-28 11:30:28 +08:00
Joel 649c3d0732 feat: key value struct 2024-02-27 18:48:01 +08:00
Joel 35c56237a0 feat: url selector 2024-02-27 18:34:54 +08:00
StyleZhang 236cc6f526 hooks 2024-02-27 18:20:32 +08:00
StyleZhang a311f88c99 compute node position 2024-02-27 18:02:49 +08:00
Joel e92bc25216 fix: if node condition operation i18n 2024-02-27 17:10:52 +08:00
Joel 0c06d84e22 chore: add spacing and hover 2024-02-27 16:22:47 +08:00
Joel 77c8261fca chore: if not align 2024-02-27 16:19:29 +08:00
Joel 91a2e71fff feat: if comparasion 2024-02-27 15:52:07 +08:00
Joel 0fb47fed9e feat: add adn update condition 2024-02-27 15:20:04 +08:00
Joel 4519c6ab29 feat: conditions struct 2024-02-27 11:50:56 +08:00
Joel 32c6431dbc feat: assign node no var list tip 2024-02-27 10:58:46 +08:00
Joel 925964ac28 feat: add default and utils 2024-02-27 10:43:11 +08:00
Joel 4d4d3bb965 feat: add default values and utils and fix ts 2024-02-27 10:34:13 +08:00
StyleZhang 3d526b3a87 handleAddNextNode 2024-02-26 19:03:04 +08:00
StyleZhang f91582e060 publish button 2024-02-26 18:43:33 +08:00
Joel dec60fdd4c feat: fin var assigner 2024-02-26 18:19:01 +08:00
Joel 31930159b8 feat: var assigner data logic 2024-02-26 18:19:01 +08:00
StyleZhang 6e2611c86c node title desc 2024-02-26 17:10:18 +08:00
StyleZhang 7574107d8c add run-history 2024-02-26 15:38:49 +08:00
StyleZhang 58d8b0dd01 node handle connection line 2024-02-26 14:33:31 +08:00
JzoNg 49f78bacef update icons of app menu 2024-02-25 14:06:07 +08:00
JzoNg 3b190467c1 update i18n and style of creatioin from app template 2024-02-24 14:58:00 +08:00
JzoNg 804a090457 app templates 2024-02-24 14:21:42 +08:00
JzoNg 14cfb310e3 app creation 2024-02-24 12:45:58 +08:00
JzoNg f607a334ac create from DSL 2024-02-24 12:45:58 +08:00
JzoNg 117b84116e app list modification 2024-02-24 12:45:58 +08:00
StyleZhang 171dd5c737 node-handle 2024-02-23 19:26:56 +08:00
Joel b5ed4af25a feat: var assigner node 2024-02-23 18:26:42 +08:00
StyleZhang b6c683a1b8 next step 2024-02-23 17:20:06 +08:00
Joel 5200ec0b9a feat: end node panle 2024-02-23 17:01:48 +08:00
Joel 307cbf1d9f feat: input no var tip 2024-02-23 16:15:45 +08:00
StyleZhang e7ecdb01a6 block-selector 2024-02-23 15:20:04 +08:00
Joel 383bfd7583 feat: merge i18n 2024-02-23 15:18:48 +08:00
Joel 508ea8bc0a feat: add number type var 2024-02-23 15:02:00 +08:00
Joel 077de17cd5 feat: support config modal edit 2024-02-23 14:25:08 +08:00
StyleZhang f6c07c996b workflow store 2024-02-23 14:16:19 +08:00
Joel 7ba0bfffa2 fix: debug set var value error 2024-02-23 11:58:28 +08:00
StyleZhang 9b577fa32c chore 2024-02-23 11:31:46 +08:00
StyleZhang 94cda3e837 chore 2024-02-22 20:10:58 +08:00
Joel f09f91e25a hide debug 2024-02-22 18:51:25 +08:00
Joel 235bec6481 feat: new var input editor 2024-02-22 18:49:32 +08:00
StyleZhang ee616ee6dd header 2024-02-22 16:35:54 +08:00
Joel 5153068a64 feat: start var list 2024-02-22 16:17:38 +08:00
StyleZhang 701e441349 panel 2024-02-22 15:37:33 +08:00
Joel 5817a035f9 feat: start build in vars show 2024-02-22 15:06:27 +08:00
StyleZhang ea76f46223 block-selector 2024-02-22 15:02:02 +08:00
Joel 0759b29ca2 feat: retrial node 2024-02-22 14:40:16 +08:00
Joel db6074e035 feat: tool node 2024-02-22 14:06:34 +08:00
Joel 6057ba0988 feat: var assigner node struct 2024-02-22 11:42:20 +08:00
Joel 2fdcf1756e feat: end node 2024-02-22 11:04:14 +08:00
StyleZhang f489736e06 add debug-and-preview 2024-02-21 20:23:03 +08:00
StyleZhang 15f13209cf node handle 2024-02-21 19:02:58 +08:00
Joel dbf3b7ad6d feat: end node typs and mock 2024-02-21 18:38:52 +08:00
Joel 3341077587 feat: start node 2024-02-21 18:31:45 +08:00
Joel e39d7021e0 feat: if else node 2024-02-21 17:45:52 +08:00
Joel cffaf30760 feat: if types 2024-02-21 16:34:38 +08:00
Joel bc60cf0a35 feat: http node content 2024-02-21 16:00:14 +08:00
Joel 9bb9807252 feat: http node struct 2024-02-21 15:50:36 +08:00
Joel 8b8fdb48bb feat: output var 2024-02-21 14:56:10 +08:00
Joel b4437ccd2b chore: output lines 2024-02-21 14:11:51 +08:00
Joel 65ac4dedcc feat: template transform code tooltip 2024-02-21 13:55:17 +08:00
StyleZhang 671654da71 add node 2024-02-21 12:28:10 +08:00
Joel 31490417d1 Merge branch 'main' into feat/workflow 2024-02-21 12:05:22 +08:00
Joel 17e8c91267 feat: template transform panel content 2024-02-21 11:48:34 +08:00
Joel db7dccf349 feat: type selector 2024-02-21 11:33:25 +08:00
Joel 71d3f71e22 feat: code editor base 2024-02-21 11:04:37 +08:00
StyleZhang 13a54c3f56 block-selector edit 2024-02-20 20:12:41 +08:00
Joel d58a1b1359 feat: code support vars 2024-02-20 18:42:21 +08:00
Joel bb87a350ac feat: question classify panel 2024-02-20 17:39:09 +08:00
Joel c441a848e7 feat: question classify node 2024-02-20 17:29:06 +08:00
StyleZhang f14a5c7346 add node-control 2024-02-20 16:58:29 +08:00
Joel 92219b5aad feat: prompt ide and fin direct ansewer node 2024-02-20 16:52:22 +08:00
Joel 291201db1c chore: llm use config 2024-02-20 15:34:44 +08:00
Joel c8ea6d7bfb feat: direct answer node 2024-02-20 15:21:35 +08:00
Joel 9c70befaf6 chore: move node type to self struct 2024-02-20 14:59:03 +08:00
Joel fcadb807f6 feat: llm node content 2024-02-20 14:51:19 +08:00
Joel 4364775dcb feat: output vars 2024-02-20 14:27:40 +08:00
Joel 2a196e91a6 feat: default set var name 2024-02-20 14:04:24 +08:00
Joel 7a0358827a feat: finish choose var 2024-02-20 14:01:20 +08:00
Joel 62e2deafca feat: infinite choose var 2024-02-20 11:23:23 +08:00
StyleZhang 25b4e68fbb delete 2024-02-19 19:58:49 +08:00
StyleZhang c909319413 base-node base-panel 2024-02-19 19:44:48 +08:00
StyleZhang c7ee8ac1c7 add app-info-panel 2024-02-19 19:06:42 +08:00
Joel 2386eed703 chore: new block enum 2024-02-19 18:46:21 +08:00
Joel ada558bedc feat: add picker shower 2024-02-19 18:33:12 +08:00
StyleZhang 6caca3aaf7 base panel 2024-02-19 17:58:54 +08:00
StyleZhang 3d3bc4c512 initial node data 2024-02-19 17:45:36 +08:00
Joel 044ed624eb feat: var picker trigger 2024-02-19 16:36:53 +08:00
Joel 4dff0c5dff feat: to not ignore var 2024-02-19 16:01:12 +08:00
StyleZhang 59d8f926c8 block-selector 2024-02-19 15:54:41 +08:00
Joel c6f1900a93 chore: merge main 2024-02-19 15:52:51 +08:00
Joel d94a9cd864 feat: add node icons 2024-02-19 15:44:52 +08:00
Joel 21db8e3be4 feat: add var struct 2024-02-19 11:26:25 +08:00
Joel e05bbec879 chore: model and params select 2024-02-19 10:35:11 +08:00
StyleZhang 240e0dfa6f next-step 2024-02-18 20:26:16 +08:00
Joel ab6a01b476 chore: handle llm model type 2024-02-18 18:31:04 +08:00
StyleZhang dce01cf002 header 2024-02-18 17:56:00 +08:00
StyleZhang da84ba06c7 add block-icon 2024-02-18 17:36:34 +08:00
Joel 45ba3ca07b feat: add model selector 2024-02-18 17:26:52 +08:00
StyleZhang 56407a910d add block-selector 2024-02-18 16:14:21 +08:00
StyleZhang e624c33d51 node props 2024-02-18 16:14:21 +08:00
Joel 3666462076 feat: llm input struct 2024-02-18 14:33:44 +08:00
Joel da0d9aab39 chore: remove node code to panel 2024-02-18 14:08:08 +08:00
Joel ace04b3ef4 feat: filed and var 2024-02-18 14:01:22 +08:00
Joel 1a4c2e77c4 feat: nodes placeholder 2024-02-06 17:49:07 +08:00
StyleZhang f3c78fe73d init 2024-02-06 17:17:29 +08:00
StyleZhang a17c0e5bf6 init 2024-02-06 17:05:26 +08:00
StyleZhang 20d5fdea2c init 2024-02-06 12:41:34 +08:00
785 changed files with 5492 additions and 57075 deletions
+3
View File
@@ -1,5 +1,8 @@
FROM mcr.microsoft.com/devcontainers/python:3.10
COPY . .
# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
-2
View File
@@ -8,8 +8,6 @@ body:
label: Self Checks
description: "To make sure we get to you in time, please check the following :)"
options:
- label: This is only for bug report, if you would like to ask a quesion, please head to [Discussions](https://github.com/langgenius/dify/discussions/categories/general).
required: true
- label: I have searched for existing issues [search for existing issues](https://github.com/langgenius/dify/issues), including closed ones.
required: true
- label: I confirm that I am using English to submit this report (我已阅读并同意 [Language Policy](https://github.com/langgenius/dify/issues/1542)).
+6 -3
View File
@@ -1,5 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: "\U0001F4E7 Discussions"
url: https://github.com/langgenius/dify/discussions/categories/general
about: General discussions and request help from the community
- name: "\U0001F4DA Dify user documentation"
url: https://docs.dify.ai/getting-started/readme
about: Documentation for users of Dify
- name: "\U0001F4DA Dify dev documentation"
url: https://docs.dify.ai/getting-started/install-self-hosted
about: Documentation for people interested in developing and contributing for Dify
+22
View File
@@ -0,0 +1,22 @@
name: "🤝 Help Wanted"
description: "Request help from the community [please use English :]"
labels:
- help-wanted
body:
- type: checkboxes
attributes:
label: Self Checks
description: "To make sure we get to you in time, please check the following :)"
options:
- label: I have searched for existing issues [search for existing issues](https://github.com/langgenius/dify/issues), including closed ones.
required: true
- label: I confirm that I am using English to submit this report (我已阅读并同意 [Language Policy](https://github.com/langgenius/dify/issues/1542)).
required: true
- label: "Pleas do not modify this template :) and fill in all the required fields."
required: true
- type: textarea
attributes:
label: Provide a description of the help you need
placeholder: Briefly describe what you need help with.
validations:
required: true
@@ -8,9 +8,6 @@ on:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
env:
OPENAI_API_KEY: sk-IamNotARealKeyJustForMockTestKawaiiiiiiiiii
@@ -29,34 +26,20 @@ jobs:
HUGGINGFACE_TEXT2TEXT_GEN_ENDPOINT_URL: b
HUGGINGFACE_EMBEDDINGS_ENDPOINT_URL: c
MOCK_SWITCH: true
CODE_MAX_STRING_LENGTH: 80000
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install APT packages
uses: awalsh128/cache-apt-pkgs-action@v1
with:
packages: ffmpeg
- name: Set up Python ${{ matrix.python-version }}
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
python-version: '3.10'
cache: 'pip'
cache-dependency-path: |
./api/requirements.txt
./api/requirements-dev.txt
cache-dependency-path: ./api/requirements.txt
- name: Install dependencies
run: pip install -r ./api/requirements.txt -r ./api/requirements-dev.txt
run: pip install -r ./api/requirements.txt
- name: Run ModelRuntime
run: dev/pytest/pytest_model_runtime.sh
- name: Run Tool
run: dev/pytest/pytest_tools.sh
- name: Run Workflow
run: dev/pytest/pytest_workflow.sh
- name: Run pytest
run: pytest api/tests/integration_tests/model_runtime/anthropic api/tests/integration_tests/model_runtime/azure_openai api/tests/integration_tests/model_runtime/openai api/tests/integration_tests/model_runtime/chatglm api/tests/integration_tests/model_runtime/google api/tests/integration_tests/model_runtime/xinference api/tests/integration_tests/model_runtime/huggingface_hub/test_llm.py
+26
View File
@@ -0,0 +1,26 @@
name: Run Tool Pytest
on:
pull_request:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
cache: 'pip'
cache-dependency-path: ./api/requirements.txt
- name: Install dependencies
run: pip install -r ./api/requirements.txt
- name: Run pytest
run: pytest ./api/tests/integration_tests/tools/test_all_provider.py
+31
View File
@@ -0,0 +1,31 @@
name: Run Pytest
on:
pull_request:
branches:
- main
- deploy/dev
jobs:
test:
runs-on: ubuntu-latest
env:
MOCK_SWITCH: true
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
cache: 'pip'
cache-dependency-path: ./api/requirements.txt
- name: Install dependencies
run: pip install -r ./api/requirements.txt
- name: Run pytest
run: pytest api/tests/integration_tests/workflow
+2 -1
View File
@@ -5,6 +5,7 @@ on:
branches:
- "main"
- "deploy/dev"
- "feat/workflow"
release:
types: [published]
@@ -46,7 +47,7 @@ jobs:
with:
images: ${{ env[matrix.image_name_env] }}
tags: |
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/') }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' && startsWith(github.ref, 'refs/tags/') }}
type=ref,event=branch
type=sha,enable=true,priority=100,prefix=,suffix=,format=long
type=raw,value=${{ github.ref_name }},enable=${{ startsWith(github.ref, 'refs/tags/') }}
+1 -4
View File
@@ -24,14 +24,11 @@ jobs:
python-version: '3.10'
- name: Python dependencies
run: pip install ruff dotenv-linter
run: pip install ruff
- name: Ruff check
run: ruff check ./api
- name: Dotenv check
run: dotenv-linter ./api/.env.example ./web/.env.example
- name: Lint hints
if: failure()
run: echo "Please run 'dev/reformat' to fix the fixable linting errors."
+1 -1
View File
@@ -36,7 +36,7 @@ In terms of licensing, please take a minute to read our short [License and Contr
| Feature Type | Priority |
| ------------------------------------------------------------ | --------------- |
| High-Priority Features as being labeled by a team member | High Priority |
| Popular feature requests from our [community feedback board](https://github.com/langgenius/dify/discussions/categories/feedbacks) | Medium Priority |
| Popular feature requests from our [community feedback board](https://feedback.dify.ai/) | Medium Priority |
| Non-core features and minor enhancements | Low Priority |
| Valuable but not immediate | Future-Feature |
+1 -1
View File
@@ -34,7 +34,7 @@
| Feature Type | Priority |
| ------------------------------------------------------------ | --------------- |
| High-Priority Features as being labeled by a team member | High Priority |
| Popular feature requests from our [community feedback board](https://github.com/langgenius/dify/discussions/categories/feedbacks) | Medium Priority |
| Popular feature requests from our [community feedback board](https://feedback.dify.ai/) | Medium Priority |
| Non-core features and minor enhancements | Low Priority |
| Valuable but not immediate | Future-Feature |
+95 -178
View File
@@ -1,176 +1,95 @@
![cover-v5-optimized](https://github.com/langgenius/dify/assets/13230914/f9e19af5-61ba-4119-b926-d10c4c06ebab)
[![](./images/describe.png)](https://dify.ai)
<p align="center">
<a href="https://cloud.dify.ai">Dify Cloud</a> ·
<a href="https://docs.dify.ai/getting-started/install-self-hosted">Self-hosting</a> ·
<a href="https://docs.dify.ai">Documentation</a> ·
<a href="https://cal.com/guchenhe/60-min-meeting">Enterprise inquiry</a>
<a href="./README.md">English</a> |
<a href="./README_CN.md">简体中文</a> |
<a href="./README_JA.md">日本語</a> |
<a href="./README_ES.md">Español</a> |
<a href="./README_KL.md">Klingon</a> |
<a href="./README_FR.md">Français</a>
</p>
<p align="center">
<a href="https://dify.ai" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/Product-F04438"></a>
<a href="https://dify.ai/pricing" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/free-pricing?logo=free&color=%20%23155EEF&label=pricing&labelColor=%20%23528bff"></a>
<img alt="Static Badge" src="https://img.shields.io/badge/AI-Dify?logo=AI&logoColor=%20%23f5f5f5&label=Dify&labelColor=%20%23155EEF&color=%23EAECF0"></a>
<a href="https://discord.gg/FngNHpbcY7" target="_blank">
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=dify_ai" target="_blank">
<img src="https://img.shields.io/twitter/follow/dify_ai?logo=X&color=%20%23f5f5f5"
<img src="https://img.shields.io/twitter/follow/dify_ai?style=social&logo=X"
alt="follow on Twitter"></a>
<a href="https://hub.docker.com/u/langgenius" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web?labelColor=%20%23FDB062&color=%20%23f79009"></a>
<a href="https://github.com/langgenius/dify/graphs/commit-activity" target="_blank">
<img alt="Commits last month" src="https://img.shields.io/github/commit-activity/m/langgenius/dify?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langgenius/dify/" target="_blank">
<img alt="Issues closed" src="https://img.shields.io/github/issues-search?query=repo%3Alanggenius%2Fdify%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langgenius/dify/discussions/" target="_blank">
<img alt="Discussion posts" src="https://img.shields.io/github/discussions/langgenius/dify?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="Commits last month" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README_CN.md"><img alt="Commits last month" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README_JA.md"><img alt="Commits last month" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README_ES.md"><img alt="Commits last month" src="https://img.shields.io/badge/Español-d9d9d9"></a>
<a href="./README_FR.md"><img alt="Commits last month" src="https://img.shields.io/badge/Français-d9d9d9"></a>
<a href="./README_KL.md"><img alt="Commits last month" src="https://img.shields.io/badge/Klingon-d9d9d9"></a>
<a href="https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6" target="_blank">
📌 Check out Dify Premium on AWS and deploy it to your own AWS VPC with one-click.
</a>
</p>
#
**Dify** is an open-source LLM app development platform. Dify's intuitive interface combines a RAG pipeline, AI workflow orchestration, agent capabilities, model management, observability features and more, letting you quickly go from prototype to production.
<p align="center">
<a href="https://trendshift.io/repositories/2152" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2152" alt="langgenius%2Fdify | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</p>
Dify is an open-source LLM app development platform. Its intuitive interface combines AI workflow, RAG pipeline, agent capabilities, model management, observability features and more, letting you quickly go from prototype to production. Here's a list of the core features:
</br> </br>
**1. Workflow**:
Build and test powerful AI workflows on a visual canvas, leveraging all the following features and beyond.
https://github.com/langgenius/dify/assets/13230914/356df23e-1604-483d-80a6-9517ece318aa
![](./images/demo.png)
**2. Comprehensive model support**:
Seamless integration with hundreds of proprietary / open-source LLMs from dozens of inference providers and self-hosted solutions, covering GPT, Mistral, Llama2, and any OpenAI API-compatible models. A full list of supported model providers can be found [here](https://docs.dify.ai/getting-started/readme/model-providers).
## Using our Cloud Services
![providers-v5](https://github.com/langgenius/dify/assets/13230914/5a17bdbe-097a-4100-8363-40255b70f6e3)
You can try out [Dify.AI Cloud](https://dify.ai) now. It provides all the capabilities of the self-deployed version, and includes 200 free requests to OpenAI GPT-3.5.
### Looking to purchase via AWS?
Check out [Dify Premium on AWS](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) and deploy it to your own AWS VPC with one-click.
**3. Prompt IDE**:
Intuitive interface for crafting prompts, comparing model performance, and adding additional features such as text-to-speech to a chat-based app.
## Dify vs. LangChain vs. Assistants API
**4. RAG Pipeline**:
Extensive RAG capabilities that cover everything from document ingestion to retrieval, with out-of-box support for text extraction from PDFs, PPTs, and other common document formats.
**5. Agent capabilities**:
You can define agents based on LLM Function Calling or ReAct, and add pre-built or custom tools for the agent. Dify provides 50+ built-in tools for AI agents, such as Google Search, DELL·E, Stable Diffusion and WolframAlpha.
**6. LLMOps**:
Monitor and analyze application logs and performance over time. You could continuously improve prompts, datasets, and models based on production data and annotations.
**7. Backend-as-a-Service**:
All of Dify's offerings come with corresponding APIs, so you could effortlessly integrate Dify into your own business logic.
## Feature comparison
<table style="width: 100%;">
<tr>
<th align="center">Feature</th>
<th align="center">Dify.AI</th>
<th align="center">LangChain</th>
<th align="center">Flowise</th>
<th align="center">OpenAI Assistants API</th>
</tr>
<tr>
<td align="center">Programming Approach</td>
<td align="center">API + App-oriented</td>
<td align="center">Python Code</td>
<td align="center">App-oriented</td>
<td align="center">API-oriented</td>
</tr>
<tr>
<td align="center">Supported LLMs</td>
<td align="center">Rich Variety</td>
<td align="center">Rich Variety</td>
<td align="center">Rich Variety</td>
<td align="center">OpenAI-only</td>
</tr>
<tr>
<td align="center">RAG Engine</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Agent</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Workflow</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Observability</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Enterprise Feature (SSO/Access control)</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Local Deployment</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
</table>
## Using Dify
- **Cloud </br>**
We host a [Dify Cloud](https://dify.ai) service for anyone to try with zero setup. It provides all the capabilities of the self-deployed version, and includes 200 free GPT-4 calls in the sandbox plan.
- **Self-hosting Dify Community Edition</br>**
Quickly get Dify running in your environment with this [starter guide](#quick-start).
Use our [documentation](https://docs.dify.ai) for further references and more in-depth instructions.
- **Dify for enterprise / organizations</br>**
We provide additional enterprise-centric features. [Schedule a meeting with us](https://cal.com/guchenhe/30min) or [send us an email](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry) to discuss enterprise needs. </br>
> For startups and small businesses using AWS, check out [Dify Premium on AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) and deploy it to your own AWS VPC with one-click. It's an affordable AMI offering with the option to create apps with custom logo and branding.
## Staying ahead
Star Dify on GitHub and be instantly notified of new releases.
![star-us](https://github.com/langgenius/dify/assets/13230914/b823edc1-6388-4e25-ad45-2f6b187adbb4)
| Feature | Dify.AI | Assistants API | LangChain |
|---------|---------|----------------|-----------|
| **Programming Approach** | API-oriented | API-oriented | Python Code-oriented |
| **Ecosystem Strategy** | Open Source | Close Source | Open Source |
| **RAG Engine** | Supported | Supported | Not Supported |
| **Prompt IDE** | Included | Included | None |
| **Supported LLMs** | Rich Variety | OpenAI-only | Rich Variety |
| **Local Deployment** | Supported | Not Supported | Not Applicable |
## Quick start
> Before installing Dify, make sure your machine meets the following minimum system requirements:
>
>- CPU >= 2 Core
>- RAM >= 4GB
## Features
</br>
![](./images/models.png)
**1. LLM Support**: Integration with OpenAI's GPT family of models, or the open-source Llama2 family models. In fact, Dify supports mainstream commercial models and open-source models (locally deployed or based on MaaS).
**2. Prompt IDE**: Visual orchestration of applications and services based on LLMs with your team.
**3. RAG Engine**: Includes various RAG capabilities based on full-text indexing or vector database embeddings, allowing direct upload of PDFs, TXTs, and other text formats.
**4. AI Agent**: Based on Function Calling and ReAct, the Agent inference framework allows users to customize tools, what you see is what you get. Dify provides more than a dozen built-in tool calling capabilities, such as Google Search, DELL·E, Stable Diffusion, WolframAlpha, etc.
**5. Continuous Operations**: Monitor and analyze application logs and performance, continuously improving Prompts, datasets, or models using production data.
## Before You Start
**Star us on GitHub, and be instantly notified for new releases!**
![star-us](https://github.com/langgenius/dify/assets/100913391/95f37259-7370-4456-a9f0-0bc01ef8642f)
- [Website](https://dify.ai)
- [Docs](https://docs.dify.ai)
- [Deployment Docs](https://docs.dify.ai/getting-started/install-self-hosted)
- [FAQ](https://docs.dify.ai/getting-started/faq)
## Install the Community Edition
### System Requirements
Before installing Dify, make sure your machine meets the following minimum system requirements:
- CPU >= 2 Core
- RAM >= 4GB
### Quick Start
The easiest way to start the Dify server is to run our [docker-compose.yml](docker/docker-compose.yaml) file. Before running the installation command, make sure that [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) are installed on your machine:
@@ -179,65 +98,63 @@ cd docker
docker compose up -d
```
After running, you can access the Dify dashboard in your browser at [http://localhost/install](http://localhost/install) and start the initialization process.
After running, you can access the Dify dashboard in your browser at [http://localhost/install](http://localhost/install) and start the initialization installation process.
> If you'd like to contribute to Dify or do additional development, refer to our [guide to deploying from source code](https://docs.dify.ai/getting-started/install-self-hosted/local-source-code)
#### Deploy with Helm Chart
## Next steps
If you need to customize the configuration, please refer to the comments in our [docker-compose.yml](docker/docker-compose.yaml) file and manually set the environment configuration. After making the changes, please run `docker-compose up -d` again. You can see the full list of environment variables [here](https://docs.dify.ai/getting-started/install-self-hosted/environments).
If you'd like to configure a highly-available setup, there are community-contributed [Helm Charts](https://helm.sh/) which allow Dify to be deployed on Kubernetes.
[Helm Chart](https://helm.sh/) version, which allows Dify to be deployed on Kubernetes.
- [Helm Chart by @LeoQuote](https://github.com/douban/charts/tree/master/charts/dify)
- [Helm Chart by @BorisPolonsky](https://github.com/BorisPolonsky/dify-helm)
### Configuration
If you need to customize the configuration, please refer to the comments in our [docker-compose.yml](docker/docker-compose.yaml) file and manually set the environment configuration. After making the changes, please run `docker-compose up -d` again. You can see the full list of environment variables in our [docs](https://docs.dify.ai/getting-started/install-self-hosted/environments).
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Contributing
For those who'd like to contribute code, see our [Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
At the same time, please consider supporting Dify by sharing it on social media and at events and conferences.
### Projects made by community
> We are looking for contributors to help with translating Dify to languages other than Mandarin or English. If you are interested in helping, please see the [i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) for more information, and leave us a comment in the `global-users` channel of our [Discord Community Server](https://discord.gg/8Tpq4AcN9c).
- [Chatbot Chrome Extension by @charli117](https://github.com/langgenius/chatbot-chrome-extension)
**Contributors**
### Contributors
<a href="https://github.com/langgenius/dify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=langgenius/dify" />
</a>
## Community & contact
### Translations
* [Github Discussion](https://github.com/langgenius/dify/discussions). Best for: sharing feedback and asking questions.
We are looking for contributors to help with translating Dify to languages other than Mandarin or English. If you are interested in helping, please see the [i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) for more information, and leave us a comment in the `global-users` channel of our [Discord Community Server](https://discord.gg/8Tpq4AcN9c).
## Community & Support
* [Canny](https://feedback.dify.ai/). Best for: sharing feedback and checking out our feature roadmap.
* [GitHub Issues](https://github.com/langgenius/dify/issues). Best for: bugs you encounter using Dify.AI, and feature proposals. See our [Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
* [Email](mailto:support@dify.ai?subject=[GitHub]Questions%20About%20Dify). Best for: questions you have about using Dify.AI.
* [Email Support](mailto:hello@dify.ai?subject=[GitHub]Questions%20About%20Dify). Best for: questions you have about using Dify.AI.
* [Discord](https://discord.gg/FngNHpbcY7). Best for: sharing your applications and hanging out with the community.
* [Twitter](https://twitter.com/dify_ai). Best for: sharing your applications and hanging out with the community.
* [Business Contact](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry). Best for: business inquiries of licensing Dify.AI for commercial use.
Or, schedule a meeting directly with a team member:
### Direct Meetings
<table>
<tr>
<th>Point of Contact</th>
<th>Purpose</th>
</tr>
<tr>
<td><a href='https://cal.com/guchenhe/15min' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/9ebcd111-1205-4d71-83d5-948d70b809f5' alt='Git-Hub-README-Button-3x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Business enquiries & product feedback</td>
</tr>
<tr>
<td><a href='https://cal.com/pinkbanana' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/d1edd00a-d7e4-4513-be6c-e57038e143fd' alt='Git-Hub-README-Button-2x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Contributions, issues & feature requests</td>
</tr>
</table>
**Help us make Dify better. Reach out directly to us**.
## Star history
| Point of Contact | Purpose |
| :----------------------------------------------------------: | :----------------------------------------------------------: |
| <a href='https://cal.com/guchenhe/15min' target='_blank'><img src='https://i.postimg.cc/fWBqSmjP/Git-Hub-README-Button-3x.png' border='0' alt='Git-Hub-README-Button-3x' height="60" width="214"/></a> | Product design feedback, user experience discussions, feature planning and roadmaps. |
| <a href='https://cal.com/pinkbanana' target='_blank'><img src='https://i.postimg.cc/LsRTh87D/Git-Hub-README-Button-2x.png' border='0' alt='Git-Hub-README-Button-2x' height="60" width="225"/></a> | Technical support, issues, or feature requests |
[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Security disclosure
## Security Disclosure
To protect your privacy, please avoid posting security issues on GitHub. Instead, send your questions to security@dify.ai and we will provide you with a more detailed answer.
+53 -156
View File
@@ -1,167 +1,78 @@
![cover-v5-optimized](https://github.com/langgenius/dify/assets/13230914/f9e19af5-61ba-4119-b926-d10c4c06ebab)
<div align="center">
<a href="https://cloud.dify.ai">Dify 云服务</a> ·
<a href="https://docs.dify.ai/getting-started/install-self-hosted">自托管</a> ·
<a href="https://docs.dify.ai">文档</a> ·
<a href="https://cal.com/guchenhe/dify-demo">预约演示</a>
</div>
[![](./images/describe.png)](https://dify.ai)
<p align="center">
<a href="./README.md">English</a> |
<a href="./README_CN.md">简体中文</a> |
<a href="./README_JA.md">日本語</a> |
<a href="./README_ES.md">Español</a> |
<a href="./README_KL.md">Klingon</a> |
<a href="./README_FR.md">Français</a>
</p>
<p align="center">
<a href="https://dify.ai" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/Product-F04438"></a>
<a href="https://dify.ai/pricing" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/free-pricing?logo=free&color=%20%23155EEF&label=pricing&labelColor=%20%23528bff"></a>
<img alt="Static Badge" src="https://img.shields.io/badge/AI-Dify?logo=AI&logoColor=%20%23f5f5f5&label=Dify&labelColor=%20%23155EEF&color=%23EAECF0"></a>
<a href="https://discord.gg/FngNHpbcY7" target="_blank">
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=dify_ai" target="_blank">
<img src="https://img.shields.io/twitter/follow/dify_ai?logo=X&color=%20%23f5f5f5"
<img src="https://img.shields.io/twitter/follow/dify_ai?style=social&logo=X"
alt="follow on Twitter"></a>
<a href="https://hub.docker.com/u/langgenius" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web?labelColor=%20%23FDB062&color=%20%23f79009"></a>
<a href="https://github.com/langgenius/dify/graphs/commit-activity" target="_blank">
<img alt="Commits last month" src="https://img.shields.io/github/commit-activity/m/langgenius/dify?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langgenius/dify/" target="_blank">
<img alt="Issues closed" src="https://img.shields.io/github/issues-search?query=repo%3Alanggenius%2Fdify%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langgenius/dify/discussions/" target="_blank">
<img alt="Discussion posts" src="https://img.shields.io/github/discussions/langgenius/dify?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web"></a>
</p>
<div align="center">
<a href="./README.md"><img alt="上个月的提交次数" src="https://img.shields.io/badge/英文-d9d9d9"></a>
<a href="./README_CN.md"><img alt="上个月的提交次数" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README_JA.md"><img alt="上个月的提交次数" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README_ES.md"><img alt="上个月的提交次数" src="https://img.shields.io/badge/西班牙语-d9d9d9"></a>
<a href="./README_KL.md"><img alt="上个月的提交次数" src="https://img.shields.io/badge/法语-d9d9d9"></a>
<a href="./README_FR.md"><img alt="上个月的提交次数" src="https://img.shields.io/badge/克林贡语-d9d9d9"></a>
</div>
<p align="center">
<a href="https://mp.weixin.qq.com/s/TnyfIuH-tPi9o1KNjwVArw" target="_blank">
Dify 发布 AI Agent 能力:基于不同的大型语言模型构建 GPTs 和 Assistants
</a>
</p>
Dify 是一个 LLM 应用开发平台,已经有超过 10 万个应用基于 Dify.AI 构建。它融合了 Backend as Service 和 LLMOps 的理念,涵盖了构建生成式 AI 原生应用所需的核心技术栈,包括一个内置 RAG 引擎。使用 Dify,你可以基于任何模型自部署类似 Assistants API 和 GPTs 的能力。
![](./images/demo.png)
## 使用云端服务
使用 [Dify.AI Cloud](https://dify.ai) 提供开源版本的所有功能,并包含 200 次 GPT 试用额度。
## 为什么选择 Dify
Dify 具有模型中立性,相较 LangChain 等硬编码开发库 Dify 是一个完整的、工程化的技术栈,而相较于 OpenAI 的 Assistants API 你可以完全将服务部署在本地。
| 功能 | Dify.AI | Assistants API | LangChain |
| --- | --- | --- | --- |
| 编程方式 | 面向 API | 面向 API | 面向 Python 代码 |
| 生态策略 | 开源 | 封闭且商用 | 开源 |
| RAG 引擎 | 支持 | 支持 | 不支持 |
| Prompt IDE | 包含 | 包含 | 没有 |
| 支持的 LLMs | 丰富 | 仅 GPT | 丰富 |
| 本地部署 | 支持 | 不支持 | 不适用 |
#
## 特点
<div align="center">
<a href="https://trendshift.io/repositories/2152" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2152" alt="langgenius%2Fdify | 趋势转变" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</div>
![](./images/models.png)
Dify 是一个开源的 LLM 应用开发平台。其直观的界面结合了 AI 工作流、RAG 管道、Agent、模型管理、可观测性功能等,让您可以快速从原型到生产。以下是其核心功能列表:
</br> </br>
**1. LLM支持**:与 OpenAI 的 GPT 系列模型集成,或者与开源的 Llama2 系列模型集成。事实上,Dify支持主流的商业模型和开源模型(本地部署或基于 MaaS)。
**1. 工作流**:
在画布上构建和测试功能强大的 AI 工作流程,利用以下所有功能以及更多功能。
**2. Prompt IDE**:和团队一起在 Dify 协作,通过可视化的 Prompt 和应用编排工具开发 AI 应用。 支持无缝切换多种大型语言模型。
**3. RAG引擎**:包括各种基于全文索引或向量数据库嵌入的 RAG 能力,允许直接上传 PDF、TXT 等各种文本格式。
https://github.com/langgenius/dify/assets/13230914/356df23e-1604-483d-80a6-9517ece318aa
**4. AI Agent**:基于 Function Calling 和 ReAct 的 Agent 推理框架,允许用户自定义工具,所见即所得。Dify 提供了十多种内置工具调用能力,如谷歌搜索、DELL·E、Stable Diffusion、WolframAlpha 等。
**5. 持续运营**:监控和分析应用日志和性能,使用生产数据持续改进 Prompt、数据集或模型。
## 在开始之前
**2. 全面的模型支持**:
与数百种专有/开源 LLMs 以及数十种推理提供商和自托管解决方案无缝集成,涵盖 GPT、Mistral、Llama3 以及任何与 OpenAI API 兼容的模型。完整的支持模型提供商列表可在[此处](https://docs.dify.ai/getting-started/readme/model-providers)找到。
**关注我们,您将立即收到 GitHub 上所有新发布版本的通知!**
![providers-v5](https://github.com/langgenius/dify/assets/13230914/5a17bdbe-097a-4100-8363-40255b70f6e3)
![star-us](https://github.com/langgenius/dify/assets/100913391/95f37259-7370-4456-a9f0-0bc01ef8642f)
**3. Prompt IDE**:
用于制作提示、比较模型性能以及向基于聊天的应用程序添加其他功能(如文本转语音)的直观界面。
**4. RAG Pipeline**:
广泛的 RAG 功能,涵盖从文档摄入到检索的所有内容,支持从 PDF、PPT 和其他常见文档格式中提取文本的开箱即用的支持。
**5. Agent 智能体**:
您可以基于 LLM 函数调用或 ReAct 定义 Agent,并为 Agent 添加预构建或自定义工具。Dify 为 AI Agent 提供了50多种内置工具,如谷歌搜索、DELL·E、Stable Diffusion 和 WolframAlpha 等。
**6. LLMOps**:
随时间监视和分析应用程序日志和性能。您可以根据生产数据和标注持续改进提示、数据集和模型。
**7. 后端即服务**:
所有 Dify 的功能都带有相应的 API,因此您可以轻松地将 Dify 集成到自己的业务逻辑中。
## 功能比较
<table style="width: 100%;">
<tr>
<th align="center">功能</th>
<th align="center">Dify.AI</th>
<th align="center">LangChain</th>
<th align="center">Flowise</th>
<th align="center">OpenAI Assistant API</th>
</tr>
<tr>
<td align="center">编程方法</td>
<td align="center">API + 应用程序导向</td>
<td align="center">Python 代码</td>
<td align="center">应用程序导向</td>
<td align="center">API 导向</td>
</tr>
<tr>
<td align="center">支持的 LLMs</td>
<td align="center">丰富多样</td>
<td align="center">丰富多样</td>
<td align="center">丰富多样</td>
<td align="center">仅限 OpenAI</td>
</tr>
<tr>
<td align="center">RAG引擎</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Agent</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">工作流</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">可观测性</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">企业功能(SSO/访问控制)</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">本地部署</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
</table>
## 使用 Dify
- **云 </br>**
我们提供[ Dify 云服务](https://dify.ai),任何人都可以零设置尝试。它提供了自部署版本的所有功能,并在沙盒计划中包含 200 次免费的 GPT-4 调用。
- **自托管 Dify 社区版</br>**
使用这个[入门指南](#quick-start)快速在您的环境中运行 Dify。
使用我们的[文档](https://docs.dify.ai)进行进一步的参考和更深入的说明。
- **面向企业/组织的 Dify</br>**
我们提供额外的面向企业的功能。[与我们安排会议](https://cal.com/guchenhe/30min)或[给我们发送电子邮件](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry)讨论企业需求。 </br>
> 对于使用 AWS 的初创公司和中小型企业,请查看 [AWS Marketplace 上的 Dify 高级版](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6),并使用一键部署到您自己的 AWS VPC。它是一个价格实惠的 AMI 产品,提供了使用自定义徽标和品牌创建应用程序的选项。
## 保持领先
在 GitHub 上给 Dify Star,并立即收到新版本的通知。
![star-us](https://github.com/langgenius/dify/assets/13230914/b823edc1-6388-4e25-ad45-2f6b187adbb4)
- [网站](https://dify.ai)
- [文档](https://docs.dify.ai)
- [部署文档](https://docs.dify.ai/getting-started/install-self-hosted)
- [常见问题](https://docs.dify.ai/getting-started/faq)
## 安装社区版
@@ -199,24 +110,10 @@ docker compose up -d
[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Contributing
对于那些想要贡献代码的人,请参阅我们的[贡献指南](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md)。
同时,请考虑通过社交媒体、活动和会议来支持 Dify 的分享。
> 我们正在寻找贡献者来帮助将Dify翻译成除了中文和英文之外的其他语言。如果您有兴趣帮助,请参阅我们的[i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md)获取更多信息,并在我们的[Discord社区服务器](https://discord.gg/8Tpq4AcN9c)的`global-users`频道中留言。
**Contributors**
<a href="https://github.com/langgenius/dify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=langgenius/dify" />
</a>
## 社区与支持
我们欢迎您为 Dify 做出贡献,以帮助改善 Dify。包括:提交代码、问题、新想法,或分享您基于 Dify 创建的有趣且有用的 AI 应用程序。同时,我们也欢迎您在不同的活动、会议和社交媒体上分享 Dify。
- [Github Discussion](https://github.com/langgenius/dify/discussions). 👉:分享您的应用程序并与社区交流。
- [GitHub Issues](https://github.com/langgenius/dify/issues)。👉:使用 Dify.AI 时遇到的错误和问题,请参阅[贡献指南](CONTRIBUTING.md)。
- [电子邮件支持](mailto:hello@dify.ai?subject=[GitHub]Questions%20About%20Dify)。👉:关于使用 Dify.AI 的问题。
- [Discord](https://discord.gg/FngNHpbcY7)。👉:分享您的应用程序并与社区交流。
+66 -192
View File
@@ -1,245 +1,119 @@
![cover-v5-optimized](https://github.com/langgenius/dify/assets/13230914/f9e19af5-61ba-4119-b926-d10c4c06ebab)
[![](./images/describe.png)](https://dify.ai)
<p align="center">
<a href="https://cloud.dify.ai">Dify Cloud</a> ·
<a href="https://docs.dify.ai/getting-started/install-self-hosted">Auto-alojamiento</a> ·
<a href="https://docs.dify.ai">Documentación</a> ·
<a href="https://cal.com/guchenhe/dify-demo">Programar demostración</a>
<a href="./README.md">English</a> |
<a href="./README_CN.md">简体中文</a> |
<a href="./README_JA.md">日本語</a> |
<a href="./README_ES.md">Español</a> |
<a href="./README_KL.md">Klingon</a> |
<a href="./README_FR.md">Français</a>
</p>
<p align="center">
<a href="https://dify.ai" target="_blank">
<img alt="Insignia Estática" src="https://img.shields.io/badge/Producto-F04438"></a>
<a href="https://dify.ai/pricing" target="_blank">
<img alt="Insignia Estática" src="https://img.shields.io/badge/gratis-precios?logo=gratis&color=%20%23155EEF&label=precios&labelColor=%20%23528bff"></a>
<img alt="Static Badge" src="https://img.shields.io/badge/AI-Dify?logo=AI&logoColor=%20%23f5f5f5&label=Dify&labelColor=%20%23155EEF&color=%23EAECF0"></a>
<a href="https://discord.gg/FngNHpbcY7" target="_blank">
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="chat en Discord"></a>
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=dify_ai" target="_blank">
<img src="https://img.shields.io/twitter/follow/dify_ai?logo=X&color=%20%23f5f5f5"
alt="seguir en Twitter"></a>
<img src="https://img.shields.io/twitter/follow/dify_ai?style=social&logo=X"
alt="follow on Twitter"></a>
<a href="https://hub.docker.com/u/langgenius" target="_blank">
<img alt="Descargas de Docker" src="https://img.shields.io/docker/pulls/langgenius/dify-web?labelColor=%20%23FDB062&color=%20%23f79009"></a>
<a href="https://github.com/langgenius/dify/graphs/commit-activity" target="_blank">
<img alt="Actividad de Commits el último mes" src="https://img.shields.io/github/commit-activity/m/langgenius/dify?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langgenius/dify/" target="_blank">
<img alt="Issues cerrados" src="https://img.shields.io/github/issues-search?query=repo%3Alanggenius%2Fdify%20is%3Aclosed&label=issues%20cerrados&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langgenius/dify/discussions/" target="_blank">
<img alt="Publicaciones de discusión" src="https://img.shields.io/github/discussions/langgenius/dify?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="Actividad de Commits el último mes" src="https://img.shields.io/badge/Inglés-d9d9d9"></a>
<a href="./README_CN.md"><img alt="Actividad de Commits el último mes" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README_JA.md"><img alt="Actividad de Commits el último mes" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README_ES.md"><img alt="Actividad de Commits el último mes" src="https://img.shields.io/badge/Español-d9d9d9"></a>
<a href="./README_KL.md"><img alt="Actividad de Commits el último mes" src="https://img.shields.io/badge/Français-d9d9d9"></a>
<a href="./README_FR.md"><img alt="Actividad de Commits el último mes" src="https://img.shields.io/badge/Klingon-d9d9d9"></a>
<a href="https://dify.ai/blog/dify-ai-unveils-ai-agent-creating-gpts-and-assistants-with-various-llms" target="_blank">
Dify.AI Unveils AI Agent: Creating GPTs and Assistants with Various LLMs
</a>
</p>
#
**Dify** es una plataforma de desarrollo de aplicaciones para modelos de lenguaje de gran tamaño (LLM) que ya ha visto la creación de más de **100,000** aplicaciones basadas en Dify.AI. Integra los conceptos de Backend como Servicio y LLMOps, cubriendo el conjunto de tecnologías esenciales requerido para construir aplicaciones nativas de inteligencia artificial generativa, incluyendo un motor RAG incorporado. Con Dify, **puedes auto-desplegar capacidades similares a las de Assistants API y GPTs basadas en cualquier LLM.**
<p align="center">
<a href="https://trendshift.io/repositories/2152" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2152" alt="langgenius%2Fdify | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</p>
Dify es una plataforma de desarrollo de aplicaciones de LLM de código abierto. Su interfaz intuitiva combina flujo de trabajo de IA, pipeline RAG, capacidades de agente, gestión de modelos, características de observabilidad y más, lo que le permite pasar rápidamente de un prototipo a producción. Aquí hay una lista de las características principales:
</br> </br>
![](./images/demo.png)
**1. Flujo de trabajo**:
Construye y prueba potentes flujos de trabajo de IA en un lienzo visual, aprovechando todas las siguientes características y más.
## Utilizar Servicios en la Nube
Usar [Dify.AI Cloud](https://dify.ai) proporciona todas las capacidades de la versión de código abierto, e incluye un complemento de 200 créditos de prueba para GPT.
https://github.com/langgenius/dify/assets/13230914/356df23e-1604-483d-80a6-9517ece318aa
## Por qué Dify
Dify se caracteriza por su neutralidad de modelo y es un conjunto tecnológico completo e ingenierizado, en comparación con las bibliotecas de desarrollo codificadas como LangChain. A diferencia de la API de Assistants de OpenAI, Dify permite el despliegue local completo de los servicios.
| Característica | Dify.AI | API de Assistants | LangChain |
|----------------|---------|------------------|-----------|
| **Enfoque de Programación** | Orientado a API | Orientado a API | Orientado a Código en Python |
| **Estrategia del Ecosistema** | Código Abierto | Cerrado y Comercial | Código Abierto |
| **Motor RAG** | Soportado | Soportado | No Soportado |
| **IDE de Prompts** | Incluido | Incluido | Ninguno |
| **LLMs Soportados** | Gran Variedad | Solo GPT | Gran Variedad |
| **Despliegue Local** | Soportado | No Soportado | No Aplicable |
**2. Soporte de modelos completo**:
Integración perfecta con cientos de LLMs propietarios / de código abierto de docenas de proveedores de inferencia y soluciones auto-alojadas, que cubren GPT, Mistral, Llama2 y cualquier modelo compatible con la API de OpenAI. Se puede encontrar una lista completa de proveedores de modelos admitidos [aquí](https://docs.dify.ai/getting-started/readme/model-providers).
## Características
![proveedores-v5](https://github.com/langgenius/dify/assets/13230914/5a17bdbe-097a-4100-8363-40255b70f6e3)
![](./images/models.png)
**1. Soporte LLM**: Integración con la familia de modelos GPT de OpenAI, o los modelos de la familia Llama2 de código abierto. De hecho, Dify soporta modelos comerciales convencionales y modelos de código abierto (desplegados localmente o basados en MaaS).
**3. IDE de prompt**:
Interfaz intuitiva para crear prompts, comparar el rendimiento del modelo y agregar características adicionales como texto a voz a una aplicación basada en chat.
**2. IDE de Prompts**: Orquestación visual de aplicaciones y servicios basados en LLMs con tu equipo.
**4. Pipeline RAG**:
Amplias capacidades de RAG que cubren todo, desde la ingestión de documentos hasta la recuperación, con soporte listo para usar para la extracción de texto de PDF, PPT y otros formatos de documento comunes.
**3. Motor RAG**: Incluye varias capacidades RAG basadas en indexación de texto completo o incrustaciones de base de datos vectoriales, permitiendo la carga directa de PDFs, TXTs y otros formatos de texto.
**5. Capacidades de agente**:
Puedes definir agent
**4. Agente de IA**: Basado en la llamada de funciones y ReAct, el marco de inferencia del Agente permite a los usuarios personalizar las herramientas, lo que ves es lo que obtienes. Dify proporciona más de una docena de capacidades de llamada de herramientas incorporadas, como Búsqueda de Google, DELL·E, Difusión Estable, WolframAlpha, etc.
es basados en LLM Function Calling o ReAct, y agregar herramientas preconstruidas o personalizadas para el agente. Dify proporciona más de 50 herramientas integradas para agentes de IA, como Búsqueda de Google, DELL·E, Difusión Estable y WolframAlpha.
**5. Operaciones Continuas**: Monitorear y analizar registros de aplicaciones y rendimiento, mejorando continuamente Prompts, conjuntos de datos o modelos usando datos de producción.
**6. LLMOps**:
Supervisa y analiza registros de aplicaciones y rendimiento a lo largo del tiempo. Podrías mejorar continuamente prompts, conjuntos de datos y modelos basados en datos de producción y anotaciones.
## Antes de Empezar
**7. Backend como servicio**:
Todas las ofertas de Dify vienen con APIs correspondientes, por lo que podrías integrar Dify sin esfuerzo en tu propia lógica empresarial.
**¡Danos una estrella, y recibirás notificaciones instantáneas de todos los nuevos lanzamientos en GitHub!**
![star-us](https://github.com/langgenius/dify/assets/100913391/95f37259-7370-4456-a9f0-0bc01ef8642f)
## Comparación de características
<table style="width: 100%;">
<tr>
<th align="center">Característica</th>
<th align="center">Dify.AI</th>
<th align="center">LangChain</th>
<th align="center">Flowise</th>
<th align="center">API de Asistentes de OpenAI</th>
</tr>
<tr>
<td align="center">Enfoque de programación</td>
<td align="center">API + orientado a la aplicación</td>
<td align="center">Código Python</td>
<td align="center">Orientado a la aplicación</td>
<td align="center">Orientado a la API</td>
</tr>
<tr>
<td align="center">LLMs admitidos</td>
<td align="center">Gran variedad</td>
<td align="center">Gran variedad</td>
<td align="center">Gran variedad</td>
<td align="center">Solo OpenAI</td>
</tr>
<tr>
<td align="center">Motor RAG</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Agente</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Flujo de trabajo</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Observabilidad</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Característica empresarial (SSO/Control de acceso)</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Implementación local</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
</table>
- [Sitio web](https://dify.ai)
- [Documentación](https://docs.dify.ai)
- [Documentación de Implementación](https://docs.dify.ai/getting-started/install-self-hosted)
- [Preguntas Frecuentes](https://docs.dify.ai/getting-started/faq)
## Usando Dify
## Instalar la Edición Comunitaria
- **Nube </br>**
Hospedamos un servicio [Dify Cloud](https://dify.ai) para que cualquiera lo pruebe sin configuración. Proporciona todas las capacidades de la versión autoimplementada e incluye 200 llamadas gratuitas a GPT-4 en el plan sandbox.
### Requisitos del Sistema
- **Auto-alojamiento de Dify Community Edition</br>**
Pon rápidamente Dify en funcionamiento en tu entorno con esta [guía de inicio rápido](#quick-start).
Usa nuestra [documentación](https://docs.dify.ai) para más referencias e instrucciones más detalladas.
Antes de instalar Dify, asegúrate de que tu máquina cumpla con los siguientes requisitos mínimos del sistema:
- **Dify para Empresas / Organizaciones</br>**
Proporcionamos características adicionales centradas en la empresa. [Programa una reunión con nosotros](https://cal.com/guchenhe/30min) o [envíanos un correo electrónico](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry) para discutir las necesidades empresariales. </br>
> Para startups y pequeñas empresas que utilizan AWS, echa un vistazo a [Dify Premium en AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) e impleméntalo en tu propio VPC de AWS con un clic. Es una AMI asequible que ofrece la opción de crear aplicaciones con logotipo y marca personalizados.
- CPU >= 2 núcleos
- RAM >= 4GB
### Inicio Rápido
## Manteniéndote al tanto
Dale estrella a Dify en GitHub y serás notificado instantáneamente de las nuevas versiones.
![danos estrella](https://github.com/langgenius/dify/assets/13230914/b823edc1-6388-4e25-ad45-2f6b187adbb4)
## Inicio Rápido
> Antes de instalar Dify, asegúrate de que tu máquina cumpla con los siguientes requisitos mínimos del sistema:
>
>- CPU >= 2 núcleos
>- RAM >= 4GB
</br>
La forma más fácil de iniciar el servidor de Dify es ejecutar nuestro archivo [docker-compose.yml](docker/docker-compose.yaml). Antes de ejecutar el comando de instalación, asegúrate de que [Docker](https://docs.docker.com/get-docker/) y [Docker Compose](https://docs.docker.com/compose/install/) estén instalados en tu máquina:
La forma más sencilla de iniciar el servidor de Dify es ejecutar nuestro archivo [docker-compose.yml](docker/docker-compose.yaml). Antes de ejecutar el comando de instalación, asegúrate de que [Docker](https://docs.docker.com/get-docker/) y [Docker Compose](https://docs.docker.com/compose/install/) estén instalados en tu máquina:
```bash
cd docker
docker compose up -d
```
Después de ejecutarlo, puedes acceder al panel de control de Dify en tu navegador en [http://localhost/install](http://localhost/install) y comenzar el proceso de inicialización.
Después de ejecutarlo, puedes acceder al panel de control de Dify en tu navegador en [http://localhost/install](http://localhost/install) y comenzar el proceso de instalación de inicialización.
> Si deseas contribuir a Dify o realizar desarrollo adicional, consulta nuestra [guía para implementar desde el código fuente](https://docs.dify.ai/getting-started/install-self-hosted/local-source-code)
### Gráfico Helm
## Próximos pasos
Un gran agradecimiento a @BorisPolonsky por proporcionarnos una versión del [Gráfico Helm](https://helm.sh/), que permite implementar Dify en Kubernetes. Puedes visitar https://github.com/BorisPolonsky/dify-helm para obtener información sobre la implementación.
Si necesitas personalizar la configuración, consulta los comentarios en nuestro archivo [docker-compose.yml](docker/docker-compose.yaml) y configura manualmente la configuración del entorno
### Configuración
. Después de realizar los cambios, ejecuta `docker-compose up -d` nuevamente. Puedes ver la lista completa de variables de entorno [aquí](https://docs.dify.ai/getting-started/install-self-hosted/environments).
Si deseas configurar una instalación altamente disponible, hay [Gráficos Helm](https://helm.sh/) contribuidos por la comunidad que permiten implementar Dify en Kubernetes.
- [Gráfico Helm por @LeoQuote](https://github.com/douban/charts/tree/master/charts/dify)
- [Gráfico Helm por @BorisPolonsky](https://github.com/BorisPolonsky/dify-helm)
## Contribuir
Para aquellos que deseen contribuir con código, consulten nuestra [Guía de contribución](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
Al mismo tiempo, considera apoyar a Dify compartiéndolo en redes sociales y en eventos y conferencias.
> Estamos buscando colaboradores para ayudar con la traducción de Dify a idiomas que no sean el mandarín o el inglés. Si estás interesado en ayudar, consulta el [README de i18n](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) para obtener más información y déjanos un comentario en el canal `global-users` de nuestro [Servidor de Comunidad en Discord](https://discord.gg/8Tpq4AcN9c).
**Contribuidores**
<a href="https://github.com/langgenius/dify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=langgenius/dify" />
</a>
## Comunidad y Contacto
* [Discusión en GitHub](https://github.com/langgenius/dify/discussions). Lo mejor para: compartir comentarios y hacer preguntas.
* [Reporte de problemas en GitHub](https://github.com/langgenius/dify/issues). Lo mejor para: errores que encuentres usando Dify.AI y propuestas de características. Consulta nuestra [Guía de contribución](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
* [Correo electrónico](mailto:support@dify.ai?subject=[GitHub]Questions%20About%20Dify). Lo mejor para: preguntas que tengas sobre el uso de Dify.AI.
* [Discord](https://discord.gg/FngNHpbcY7). Lo mejor para: compartir tus aplicaciones y pasar el rato con la comunidad.
* [Twitter](https://twitter.com/dify_ai). Lo mejor para: compartir tus aplicaciones y pasar el rato con la comunidad.
O, programa una reunión directamente con un miembro del equipo:
<table>
<tr>
<th>Punto de Contacto</th>
<th>Propósito</th>
</tr>
<tr>
<td><a href='https://cal.com/guchenhe/15min' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/9ebcd111-1205-4d71-83d5-948d70b809f5' alt='Git-Hub-README-Button-3x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Consultas comerciales y retroalimentación del producto</td>
</tr>
<tr>
<td><a href='https://cal.com/pinkbanana' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/d1edd00a-d7e4-4513-be6c-e57038e143fd' alt='Git-Hub-README-Button-2x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Contribuciones, problemas y solicitudes de características</td>
</tr>
</table>
Si necesitas personalizar la configuración, consulta los comentarios en nuestro archivo [docker-compose.yml](docker/docker-compose.yaml) y configura manualmente la configuración del entorno. Después de realizar los cambios, ejecuta nuevamente `docker-compose up -d`. Puedes ver la lista completa de variables de entorno en nuestra [documentación](https://docs.dify.ai/getting-started/install-self-hosted/environments).
## Historial de Estrellas
[![Gráfico de Historial de Estrellas](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Comunidad y Soporte
Te damos la bienvenida a contribuir a Dify para ayudar a hacer que Dify sea mejor de diversas maneras, enviando código, informando problemas, proponiendo nuevas ideas o compartiendo las aplicaciones de inteligencia artificial interesantes y útiles que hayas creado basadas en Dify. Al mismo tiempo, también te invitamos a compartir Dify en diferentes eventos, conferencias y redes sociales.
- [Problemas en GitHub](https://github.com/langgenius/dify/issues). Lo mejor para: errores y problemas que encuentres al usar Dify.AI, consulta la [Guía de Contribución](CONTRIBUTING.md).
- [Soporte por Correo Electrónico](mailto:hello@dify.ai?subject=[GitHub]Preguntas%20sobre%20Dify). Lo mejor para: preguntas que tengas sobre el uso de Dify.AI.
- [Discord](https://discord.gg/FngNHpbcY7). Lo mejor para: compartir tus aplicaciones y socializar con la comunidad.
- [Twitter](https://twitter.com/dify_ai). Lo mejor para: compartir tus aplicaciones y socializar con la comunidad.
- [Licencia Comercial](mailto:business@dify.ai?subject=[GitHub]Consulta%20de%20Licencia%20Comercial). Lo mejor para: consultas comerciales sobre la licencia de Dify.AI para uso comercial.
## Divulgación de Seguridad
@@ -247,4 +121,4 @@ Para proteger tu privacidad, evita publicar problemas de seguridad en GitHub. En
## Licencia
Este repositorio está disponible bajo la [Licencia de Código Abierto de Dify](LICENSE), que es esencialmente Apache 2.0 con algunas restricciones adicionales.
Este repositorio está disponible bajo la [Licencia de Código Abierto Dify](LICENSE), que es esencialmente Apache 2.0 con algunas restricciones adicionales.
+85 -208
View File
@@ -1,250 +1,127 @@
![cover-v5-optimized](https://github.com/langgenius/dify/assets/13230914/f9e19af5-61ba-4119-b926-d10c4c06ebab)
[![](./images/describe.png)](https://dify.ai)
<p align="center">
<a href="https://cloud.dify.ai">Dify Cloud</a> ·
<a href="https://docs.dify.ai/getting-started/install-self-hosted">Auto-hébergement</a> ·
<a href="https://docs.dify.ai">Documentation</a> ·
<a href="https://cal.com/guchenhe/dify-demo">Planifier une démo</a>
<a href="./README.md">English</a> |
<a href="./README_CN.md">简体中文</a> |
<a href="./README_JA.md">日本語</a> |
<a href="./README_ES.md">Español</a> |
<a href="./README_KL.md">Klingon</a> |
<a href="./README_FR.md">Français</a>
</p>
<p align="center">
<a href="https://dify.ai" target="_blank">
<img alt="Badge statique" src="https://img.shields.io/badge/Produit-F04438"></a>
<a href="https://dify.ai/pricing" target="_blank">
<img alt="Badge statique" src="https://img.shields.io/badge/gratuit-Tarification?logo=free&color=%20%23155EEF&label=pricing&labelColor=%20%23528bff"></a>
<img alt="Static Badge" src="https://img.shields.io/badge/AI-Dify?logo=AI&logoColor=%20%23f5f5f5&label=Dify&labelColor=%20%23155EEF&color=%23EAECF0"></a>
<a href="https://discord.gg/FngNHpbcY7" target="_blank">
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="chat sur Discord"></a>
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=dify_ai" target="_blank">
<img src="https://img.shields.io/twitter/follow/dify_ai?logo=X&color=%20%23f5f5f5"
alt="suivre sur Twitter"></a>
<img src="https://img.shields.io/twitter/follow/dify_ai?style=social&logo=X"
alt="follow on Twitter"></a>
<a href="https://hub.docker.com/u/langgenius" target="_blank">
<img alt="Tirages Docker" src="https://img.shields.io/docker/pulls/langgenius/dify-web?labelColor=%20%23FDB062&color=%20%23f79009"></a>
<a href="https://github.com/langgenius/dify/graphs/commit-activity" target="_blank">
<img alt="Commits le mois dernier" src="https://img.shields.io/github/commit-activity/m/langgenius/dify?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langgenius/dify/" target="_blank">
<img alt="Problèmes fermés" src="https://img.shields.io/github/issues-search?query=repo%3Alanggenius%2Fdify%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langgenius/dify/discussions/" target="_blank">
<img alt="Messages de discussion" src="https://img.shields.io/github/discussions/langgenius/dify?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="Commits le mois dernier" src="https://img.shields.io/badge/Anglais-d9d9d9"></a>
<a href="./README_CN.md"><img alt="Commits le mois dernier" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README_JA.md"><img alt="Commits le mois dernier" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README_ES.md"><img alt="Commits le mois dernier" src="https://img.shields.io/badge/Español-d9d9d9"></a>
<a href="./README_KL.md"><img alt="Commits le mois dernier" src="https://img.shields.io/badge/Français-d9d9d9"></a>
<a href="./README_FR.md"><img alt="Commits le mois dernier" src="https://img.shields.io/badge/Klingon-d9d9d9"></a>
<a href="https://dify.ai/blog/dify-ai-unveils-ai-agent-creating-gpts-and-assistants-with-various-llms" target="_blank">
Dify.AI Unveils AI Agent: Creating GPTs and Assistants with Various LLMs
</a>
</p>
#
<p align="center">
<a href="https://trendshift.io/repositories/2152" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2152" alt="langgenius%2Fdify | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</p>
Dify est une plateforme de développement d'applications LLM open source. Son interface intuitive combine un flux de travail d'IA, un pipeline RAG, des capacités d'agent, une gestion de modèles, des fonctionnalités d'observabilité, et plus encore, vous permettant de passer rapidement du prototype à la production. Voici une liste des fonctionnalités principales:
</br> </br>
**Dify** est une plateforme de développement d'applications LLM qui a déjà vu plus de **100,000** applications construites sur Dify.AI. Elle intègre les concepts de Backend as a Service et LLMOps, couvrant la pile technologique de base requise pour construire des applications natives d'IA générative, y compris un moteur RAG intégré. Avec Dify, **vous pouvez auto-déployer des capacités similaires aux API Assistants et GPT basées sur n'importe quels LLM.**
**1. Flux de travail**:
Construisez et testez des flux de travail d'IA puissants sur un canevas visuel, en utilisant toutes les fonctionnalités suivantes et plus encore.
![](./images/demo.png)
## Utiliser les services cloud
L'utilisation de [Dify.AI Cloud](https://dify.ai) fournit toutes les capacités de la version open source, et comprend un essai gratuit de 200 crédits GPT.
## Pourquoi Dify
Dify présente une neutralité de modèle et est une pile technologique complète et conçue par rapport à des bibliothèques de développement codées en dur comme LangChain. Contrairement à l'API Assistants d'OpenAI, Dify permet un déploiement local complet des services.
| Fonctionnalité | Dify.AI | API Assistants | LangChain |
|---------------|----------|-----------------|------------|
| **Approche de programmation** | Orientée API | Orientée API | Orientée code Python |
| **Stratégie écosystème** | Open source | Fermé et commercial | Open source |
| **Moteur RAG** | Pris en charge | Pris en charge | Non pris en charge |
| **IDE d'invite** | Inclus | Inclus | Aucun |
| **LLM pris en charge** | Grande variété | Seulement GPT | Grande variété |
| **Déploiement local** | Pris en charge | Non pris en charge | Non applicable |
## Fonctionnalités
![](./images/models.png)
**1\. Support LLM**: Intégration avec la famille de modèles GPT d'OpenAI, ou les modèles de la famille open source Llama2. En fait, Dify prend en charge les modèles commerciaux grand public et les modèles open source (déployés localement ou basés sur MaaS).
**2\. IDE d'invite**: Orchestration visuelle d'applications et de services basés sur LLMs avec votre équipe.
**3\. Moteur RAG**: Comprend diverses capacités RAG basées sur l'indexation de texte intégral ou les embeddings de base de données vectorielles, permettant le chargement direct de PDF, TXT et autres formats de texte.
**4\. AI Agent**: Basé sur l'appel de fonction et ReAct, le framework d'inférence de l'Agent permet aux utilisateurs de personnaliser les outils, ce que vous voyez est ce que vous obtenez. Dify propose plus d'une douzaine de capacités d'appel d'outils intégrées, telles que la recherche Google, DELL·E, Diffusion Stable, WolframAlpha, etc.
**5\. Opérations continues**: Surveillez et analysez les journaux et les performances des applications, améliorez en continu les invites, les datasets ou les modèles à l'aide de données de production.
## Avant de commencer
**Étoilez-nous, et vous recevrez des notifications instantanées pour toutes les nouvelles sorties sur GitHub !**
![star-us](https://github.com/langgenius/dify/assets/100913391/95f37259-7370-4456-a9f0-0bc01ef8642f)
- [Site web](https://dify.ai)
- [Documentation](https://docs.dify.ai)
- [Documentation de déploiement](https://docs.dify.ai/getting-started/install-self-hosted)
- [FAQ](https://docs.dify.ai/getting-started/faq)
https://github.com/langgenius/dify/assets/13230914/356df23e-1604-483d-80a6-9517ece318aa
## Installer la version Communauté
### Configuration système
Avant d'installer Dify, assurez-vous que votre machine répond aux exigences minimales suivantes:
**2. Prise en charge complète des modèles**:
Intégration transparente avec des centaines de LLM propriétaires / open source provenant de dizaines de fournisseurs d'inférence et de solutions auto-hébergées, couvrant GPT, Mistral, Llama2, et tous les modèles compatibles avec l'API OpenAI. Une liste complète des fournisseurs de modèles pris en charge se trouve [ici](https://docs.dify.ai/getting-started/readme/model-providers).
- CPU >= 2 cœurs
- RAM >= 4 Go
![providers-v5](https://github.com/langgenius/dify/assets/13230914/5a17bdbe-097a-4100-8363-40255b70f6e3)
### Démarrage rapide
**3. IDE de prompt**:
Interface intuitive pour créer des prompts, comparer les performances des modèles et ajouter des fonctionnalités supplémentaires telles que la synthèse vocale à une application basée sur des chats.
**4. Pipeline RAG**:
Des capacités RAG étendues qui couvrent tout, de l'ingestion de documents à la récupération, avec un support prêt à l'emploi pour l'extraction de texte à partir de PDF, PPT et autres formats de document courants.
**5. Capac
ités d'agent**:
Vous pouvez définir des agents basés sur l'appel de fonction LLM ou ReAct, et ajouter des outils pré-construits ou personnalisés pour l'agent. Dify fournit plus de 50 outils intégrés pour les agents d'IA, tels que la recherche Google, DELL·E, Stable Diffusion et WolframAlpha.
**6. LLMOps**:
Surveillez et analysez les journaux d'application et les performances au fil du temps. Vous pouvez continuellement améliorer les prompts, les ensembles de données et les modèles en fonction des données de production et des annotations.
**7. Backend-as-a-Service**:
Toutes les offres de Dify sont accompagnées d'API correspondantes, vous permettant d'intégrer facilement Dify dans votre propre logique métier.
## Comparaison des fonctionnalités
<table style="width: 100%;">
<tr>
<th align="center">Fonctionnalité</th>
<th align="center">Dify.AI</th>
<th align="center">LangChain</th>
<th align="center">Flowise</th>
<th align="center">OpenAI Assistants API</th>
</tr>
<tr>
<td align="center">Approche de programmation</td>
<td align="center">API + Application</td>
<td align="center">Code Python</td>
<td align="center">Application</td>
<td align="center">API</td>
</tr>
<tr>
<td align="center">LLMs pris en charge</td>
<td align="center">Grande variété</td>
<td align="center">Grande variété</td>
<td align="center">Grande variété</td>
<td align="center">Uniquement OpenAI</td>
</tr>
<tr>
<td align="center">Moteur RAG</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Agent</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Flux de travail</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Observabilité</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Fonctionnalité d'entreprise (SSO/Contrôle d'accès)</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Déploiement local</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
</table>
## Utiliser Dify
- **Cloud </br>**
Nous hébergeons un service [Dify Cloud](https://dify.ai) pour que tout le monde puisse l'essayer sans aucune configuration. Il fournit toutes les capacités de la version auto-hébergée et comprend 200 appels GPT-4 gratuits dans le plan bac à sable.
- **Auto-hébergement Dify Community Edition</br>**
Lancez rapidement Dify dans votre environnement avec ce [guide de démarrage](#quick-start).
Utilisez notre [documentation](https://docs.dify.ai) pour plus de références et des instructions plus détaillées.
- **Dify pour les entreprises / organisations</br>**
Nous proposons des fonctionnalités supplémentaires adaptées aux entreprises. [Planifiez une réunion avec nous](https://cal.com/guchenhe/30min) ou [envoyez-nous un e-mail](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry) pour discuter des besoins de l'entreprise. </br>
> Pour les startups et les petites entreprises utilisant AWS, consultez [Dify Premium sur AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) et déployez-le dans votre propre VPC AWS en un clic. C'est une offre AMI abordable avec la possibilité de créer des applications avec un logo et une marque personnalisés.
## Rester en avance
Mettez une étoile à Dify sur GitHub et soyez instantanément informé des nouvelles versions.
![star-us](https://github.com/langgenius/dify/assets/13230914/b823edc1-6388-4e25-ad45-2f6b187adbb4)
## Démarrage rapide
> Avant d'installer Dify, assurez-vous que votre machine répond aux exigences système minimales suivantes:
>
>- CPU >= 2 cœurs
>- RAM >= 4 Go
</br>
La manière la plus simple de démarrer le serveur Dify est d'exécuter notre fichier [docker-compose.yml](docker/docker-compose.yaml). Avant d'exécuter la commande d'installation, assurez-vous que [Docker](https://docs.docker.com/get-docker/) et [Docker Compose](https://docs.docker.com/compose/install/) sont installés sur votre machine:
La façon la plus simple de démarrer le serveur Dify est d'exécuter notre fichier [docker-compose.yml](docker/docker-compose.yaml). Avant d'exécuter la commande d'installation, assurez-vous que [Docker](https://docs.docker.com/get-docker/) et [Docker Compose](https://docs.docker.com/compose/install/) sont installés sur votre machine:
```bash
cd docker
docker compose up -d
```
Après l'exécution, vous pouvez accéder au tableau de bord Dify dans votre navigateur à [http://localhost/install](http://localhost/install) et commencer le processus d'initialisation.
Après l'exécution, vous pouvez accéder au tableau de bord Dify dans votre navigateur à l'adresse [http://localhost/install](http://localhost/install) et démarrer le processus d'installation initiale.
> Si vous souhaitez contribuer à Dify ou effectuer un développement supplémentaire, consultez notre [guide de déploiement à partir du code source](https://docs.dify.ai/getting-started/install-self-hosted/local-source-code)
### Chart Helm
## Prochaines étapes
Un grand merci à @BorisPolonsky pour nous avoir fourni une version [Helm Chart](https://helm.sh/) qui permet le déploiement de Dify sur Kubernetes.
Vous pouvez accéder à https://github.com/BorisPolonsky/dify-helm pour des informations de déploiement.
Si vous devez personnaliser la configuration, veuillez
### Configuration
vous référer aux commentaires dans notre fichier [docker-compose.yml](docker/docker-compose.yaml) et définir manuellement la configuration de l'environnement. Après avoir apporté les modifications, veuillez exécuter à nouveau `docker-compose up -d`. Vous pouvez voir la liste complète des variables d'environnement [ici](https://docs.dify.ai/getting-started/install-self-hosted/environments).
Si vous avez besoin de personnaliser la configuration, veuillez vous référer aux commentaires de notre fichier [docker-compose.yml](docker/docker-compose.yaml) et définir manuellement la configuration de l'environnement. Après avoir apporté les modifications, veuillez exécuter à nouveau `docker-compose up -d`. Vous trouverez la liste complète des variables d'environnement dans notre [documentation](https://docs.dify.ai/getting-started/install-self-hosted/environments).
Si vous souhaitez configurer une installation hautement disponible, il existe des [Helm Charts](https://helm.sh/) contribués par la communauté qui permettent de déployer Dify sur Kubernetes.
## Historique d'étoiles
- [Helm Chart par @LeoQuote](https://github.com/douban/charts/tree/master/charts/dify)
- [Helm Chart par @BorisPolonsky](https://github.com/BorisPolonsky/dify-helm)
[![Diagramme de l'historique des étoiles](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Contribuer
## Communauté & Support
Pour ceux qui souhaitent contribuer du code, consultez notre [Guide de contribution](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
Dans le même temps, veuillez envisager de soutenir Dify en le partageant sur les réseaux sociaux et lors d'événements et de conférences.
Nous vous invitons à contribuer à Dify pour aider à améliorer Dify de diverses manières, en soumettant du code, des problèmes, de nouvelles idées ou en partageant les applications d'IA intéressantes et utiles que vous avez créées sur la base de Dify. En même temps, nous vous invitons également à partager Dify lors de différents événements, conférences et réseaux sociaux.
- [Problèmes GitHub](https://github.com/langgenius/dify/issues). Idéal pour : les bogues et les erreurs que vous rencontrez en utilisant Dify.AI, voir le [Guide de contribution](CONTRIBUTING.md).
- [Support par courriel](mailto:hello@dify.ai?subject=[GitHub]Questions%20About%20Dify). Idéal pour : les questions que vous avez au sujet de l'utilisation de Dify.AI.
- [Discord](https://discord.gg/FngNHpbcY7). Idéal pour : partager vos applications et discuter avec la communauté.
- [Twitter](https://twitter.com/dify_ai). Idéal pour : partager vos applications et discuter avec la communauté.
- [Licence commerciale](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry). Idéal pour : les demandes commerciales de licence de Dify.AI pour un usage commercial.
> Nous recherchons des contributeurs pour aider à traduire Dify dans des langues autres que le mandarin ou l'anglais. Si vous êtes intéressé à aider, veuillez consulter le [README i18n](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) pour plus d'informations, et laissez-nous un commentaire dans le canal `global-users` de notre [Serveur communautaire Discord](https://discord.gg/8Tpq4AcN9c).
## Divulgation de la sécurité
**Contributeurs**
Pour protéger votre vie privée, veuillez éviter de publier des problèmes de sécurité sur GitHub. Envoyez plutôt vos questions à security@dify.ai et nous vous fournirons une réponse plus détaillée.
<a href="https://github.com/langgenius/dify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=langgenius/dify" />
</a>
## Licence
## Communauté & Contact
* [Discussion GitHub](https://github.com/langgenius/dify/discussions). Meilleur pour: partager des commentaires et poser des questions.
* [Problèmes GitHub](https://github.com/langgenius/dify/issues). Meilleur pour: les bogues que vous rencontrez en utilisant Dify.AI et les propositions de fonctionnalités. Consultez notre [Guide de contribution](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
* [E-mail](mailto:support@dify.ai?subject=[GitHub]Questions%20About%20Dify). Meilleur pour: les questions que vous avez sur l'utilisation de Dify.AI.
* [Discord](https://discord.gg/FngNHpbcY7). Meilleur pour: partager vos applications et passer du temps avec la communauté.
* [Twitter](https://twitter.com/dify_ai). Meilleur pour: partager vos applications et passer du temps avec la communauté.
Ou, planifiez directement une réunion avec un membre de l'équipe:
<table>
<tr>
<th>Point de contact</th>
<th>Objectif</th>
</tr>
<tr>
<td><a href='https://cal.com/guchenhe/15min' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/9ebcd111-1205-4d71-83d5-948d70b809f5' alt='Git-Hub-README-Button-3x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Demandes commerciales & retours produit</td>
</tr>
<tr>
<td><a href='https://cal.com/pinkbanana' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/d1edd00a-d7e4-4513-be6c-e57038e143fd' alt='Git-Hub-README-Button-2x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Contributions, problèmes & demandes de fonctionnalités</td>
</tr>
</table>
## Historique des étoiles
[![Graphique de l'historique des étoiles](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Divulgation de sécurité
Pour protéger votre vie privée, veuillez éviter de publier des problèmes de sécurité sur GitHub. Au lieu de cela, envoyez vos questions à security@dify.ai et nous vous fournirons une réponse plus détaillée.
## Licence
Ce référentiel est disponible sous la [Licence open source Dify](LICENSE), qui est essentiellement l'Apache 2.0 avec quelques restrictions supplémentaires.
Ce référentiel est disponible sous la [Licence open source Dify](LICENSE), qui est essentiellement Apache 2.0 avec quelques restrictions supplémentaires.
+86 -205
View File
@@ -1,249 +1,130 @@
![cover-v5-optimized](https://github.com/langgenius/dify/assets/13230914/f9e19af5-61ba-4119-b926-d10c4c06ebab)
[![](./images/describe.png)](https://dify.ai)
<p align="center">
<a href="https://cloud.dify.ai">Dify Cloud</a> ·
<a href="https://docs.dify.ai/getting-started/install-self-hosted">自己ホスティング</a> ·
<a href="https://docs.dify.ai">ドキュメント</a> ·
<a href="https://cal.com/guchenhe/dify-demo">デモのスケジュール</a>
<a href="./README.md">English</a> |
<a href="./README_CN.md">简体中文</a> |
<a href="./README_JA.md">日本語</a> |
<a href="./README_ES.md">Español</a> |
<a href="./README_KL.md">Klingon</a> |
<a href="./README_FR.md">Français</a>
</p>
<p align="center">
<a href="https://dify.ai" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/Product-F04438"></a>
<a href="https://dify.ai/pricing" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/free-pricing?logo=free&color=%20%23155EEF&label=pricing&labelColor=%20%23528bff"></a>
<img alt="Static Badge" src="https://img.shields.io/badge/AI-Dify?logo=AI&logoColor=%20%23f5f5f5&label=Dify&labelColor=%20%23155EEF&color=%23EAECF0"></a>
<a href="https://discord.gg/FngNHpbcY7" target="_blank">
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
alt="Discordでチャット"></a>
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=dify_ai" target="_blank">
<img src="https://img.shields.io/twitter/follow/dify_ai?logo=X&color=%20%23f5f5f5"
alt="Twitterでフォロー"></a>
<img src="https://img.shields.io/twitter/follow/dify_ai?style=social&logo=X"
alt="follow on Twitter"></a>
<a href="https://hub.docker.com/u/langgenius" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web?labelColor=%20%23FDB062&color=%20%23f79009"></a>
<a href="https://github.com/langgenius/dify/graphs/commit-activity" target="_blank">
<img alt="先月のコミット" src="https://img.shields.io/github/commit-activity/m/langgenius/dify?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langgenius/dify/" target="_blank">
<img alt="クローズされた問題" src="https://img.shields.io/github/issues-search?query=repo%3Alanggenius%2Fdify%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langgenius/dify/discussions/" target="_blank">
<img alt="ディスカッション投稿" src="https://img.shields.io/github/discussions/langgenius/dify?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="先月のコミット" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README_CN.md"><img alt="先月のコミット" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README_JA.md"><img alt="先月のコミット" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README_ES.md"><img alt="先月のコミット" src="https://img.shields.io/badge/Español-d9d9d9"></a>
<a href="./README_KL.md"><img alt="先月のコミット" src="https://img.shields.io/badge/Français-d9d9d9"></a>
<a href="./README_FR.md"><img alt="先月のコミット" src="https://img.shields.io/badge/Klingon-d9d9d9"></a>
<a href="https://dify.ai/blog/dify-ai-unveils-ai-agent-creating-gpts-and-assistants-with-various-llms" target="_blank">
Dify.AI Unveils AI Agent: Creating GPTs and Assistants with Various LLMs
</a>
</p>
#
<p align="center">
<a href="https://trendshift.io/repositories/2152" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2152" alt="langgenius%2Fdify | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</p>
"Difyは、既にDify.AI上で10万以上のアプリケーションが構築されているLLMアプリケーション開発プラットフォームです。バックエンド・アズ・ア・サービスとLLMOpsの概念を統合し、組み込みのRAGエンジンを含む、生成AIネイティブアプリケーションを構築するためのコアテックスタックをカバーしています。Difyを使用すると、どのLLMに基づいても、Assistants APIやGPTのような機能を自己デプロイすることができます。"
DifyはオープンソースのLLMアプリケーション開発プラットフォームです。直感的なインターフェースには、AIワークフロー、RAGパイプライン、エージェント機能、モデル管理、観測機能などが組み合わさっており、プロトタイプから本番までの移行を迅速に行うことができます。以下は、主要機能のリストです:
</br> </br>
Please note that translating complex technical terms can sometimes result in slight variations in meaning due to differences in language nuances.
**1. ワークフロー**:
ビジュアルキャンバス上で強力なAIワークフローを構築してテストし、以下の機能を活用してプロトタイプを超えることができます。
![](./images/demo.png)
## クラウドサービスの利用
[Dify.AI Cloud](https://dify.ai) を使用すると、オープンソース版の全機能を利用でき、さらに200GPTのトライアルクレジットが無料で提供されます。
## Difyの利点
Difyはモデルニュートラルであり、LangChainのようなハードコードされた開発ライブラリと比較して、完全にエンジニアリングされた技術スタックを特徴としています。OpenAIのAssistants APIとは異なり、Difyではサービスの完全なローカルデプロイメントが可能です。
| 機能 | Dify.AI | Assistants API | LangChain |
|---------|---------|----------------|-----------|
| **プログラミングアプローチ** | API指向 | API指向 | Pythonコード指向 |
| **エコシステム戦略** | オープンソース | 閉鎖的かつ商業的 | オープンソース |
| **RAGエンジン** | サポート済み | サポート済み | 非サポート |
| **プロンプトIDE** | 含まれる | 含まれる | なし |
| **サポートされるLLMs** | 豊富な種類 | GPTのみ | 豊富な種類 |
| **ローカルデプロイメント** | サポート済み | 非サポート | 該当なし |
## 機能
![](./images/models.png)
**1\. LLMサポート**: OpenAIのGPTファミリーモデルやLlama2ファミリーのオープンソースモデルとの統合。 実際、Difyは主要な商用モデルとオープンソースモデル(ローカルでデプロイまたはMaaSベース)をサポートしています。
**2\. プロンプトIDE**: チームとのLLMベースのアプリケーションとサービスの視覚的なオーケストレーション。
**3\. RAGエンジン**: フルテキストインデックスまたはベクトルデータベース埋め込みに基づくさまざまなRAG機能を含み、PDF、TXT、その他のテキストフォーマットの直接アップロードを可能にします。
**4. AIエージェント**: 関数呼び出しとReActに基づくAgent推論フレームワークにより、ユーザーはツールをカスタマイズすることができます。Difyは、Google検索、DELL·E、Stable Diffusion、WolframAlphaなど、十数種類の組み込みツール呼び出し機能を提供しています。
**5\. 継続的運用**: アプリケーションログとパフォーマンスを監視および分析し、運用データを使用してプロンプト、データセット、またはモデルを継続的に改善します。
## 開始する前に
**私たちをスターして、GitHub上でのすべての新しいリリースに対する即時通知を受け取ります!**
![私たちをスターして](https://github.com/langgenius/dify/assets/100913391/95f37259-7370-4456-a9f0-0bc01ef8642f)
- [Website](https://dify.ai)
- [Docs](https://docs.dify.ai)
- [Deployment Docs](https://docs.dify.ai/getting-started/install-self-hosted)
- [FAQ](https://docs.dify.ai/getting-started/faq)
https://github.com/langgenius/dify/assets/13230914/356df23e-1604-483d-80a6-9517ece318aa
## コミュニティエディションのインストール
### システム要件
Difyをインストールする前に、以下の最低限のシステム要件を満たしていることを確認してください:
**2. 網羅的なモデルサポート**:
数百のプロプライエタリ/オープンソースのLLMと、数十の推論プロバイダーおよびセルフホスティングソリューションとのシームレスな統合を提供します。GPT、Mistral、Llama2、およびOpenAI API互換のモデルをカバーします。サポートされているモデルプロバイダーの完全なリストは[こちら](https://docs
- CPU >= 2コア
- RAM >= 4GB
.dify.ai/getting-started/readme/model-providers)をご覧ください。
### クイックスタート
![providers-v5](https://github.com/langgenius/dify/assets/13230914/5a17bdbe-097a-4100-8363-40255b70f6e3)
**3. プロンプトIDE**:
チャットベースのアプリにテキスト読み上げなどの追加機能を追加するプロンプトを作成し、モデルのパフォーマンスを比較する直感的なインターフェース。
**4. RAGパイプライン**:
文書の取り込みから取得までをカバーする幅広いRAG機能で、PDF、PPTなどの一般的なドキュメント形式からのテキスト抽出に対するアウトオブボックスのサポートを提供します。
**5. エージェント機能**:
LLM関数呼び出しまたはReActに基づいてエージェントを定義し、エージェント向けの事前構築済みまたはカスタムのツールを追加できます。Difyには、Google検索、DELL·E、Stable Diffusion、WolframAlphaなどのAIエージェント用の50以上の組み込みツールが用意されています。
**6. LLMOps**:
アプリケーションログとパフォーマンスを時間の経過とともにモニタリングおよび分析します。本番データと注釈に基づいて、プロンプト、データセット、およびモデルを継続的に改善できます。
**7. Backend-as-a-Service**:
Difyのすべての提供には、それに対応するAPIが付属しており、独自のビジネスロジックにDifyをシームレスに統合できます。
## 機能比較
<table style="width: 100%;">
<tr>
<th align="center">機能</th>
<th align="center">Dify.AI</th>
<th align="center">LangChain</th>
<th align="center">Flowise</th>
<th align="center">OpenAI Assistants API</th>
</tr>
<tr>
<td align="center">プログラミングアプローチ</td>
<td align="center">API + アプリ指向</td>
<td align="center">Pythonコード</td>
<td align="center">アプリ指向</td>
<td align="center">API指向</td>
</tr>
<tr>
<td align="center">サポートされているLLM</td>
<td align="center">豊富なバリエーション</td>
<td align="center">豊富なバリエーション</td>
<td align="center">豊富なバリエーション</td>
<td align="center">OpenAIのみ</td>
</tr>
<tr>
<td align="center">RAGエンジン</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">エージェント</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">ワークフロー</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">観測性</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">エンタープライズ機能(SSO/アクセス制御)</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">ローカル展開</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
</table>
## Difyの使用方法
- **クラウド </br>**
[こちら](https://dify.ai)のDify Cloudサービスを利用して、セットアップが不要で誰でも試すことができます。サンドボックスプランでは、200回の無料のGPT-4呼び出しが含まれています。
- **Dify Community Editionのセルフホスティング</br>**
この[スターターガイド](#quick-start)を使用して、環境でDifyをすばやく実行できます。
さらなる参照や詳細な手順については、[ドキュメント](https://docs.dify.ai)をご覧ください。
- **エンタープライズ/組織向けのDify</br>**
追加のエンタープライズ向け機能を提供しています。[こちらからミーティ
ングを予約](https://cal.com/guchenhe/30min)したり、[メールを送信](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry)してエンタープライズのニーズについて相談してください。 </br>
> AWSを使用しているスタートアップや中小企業の場合は、[AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6)のDify Premiumをチェックして、ワンクリックで独自のAWS VPCにデプロイできます。カスタムロゴとブランディングでアプリを作成するオプションを備えた手頃な価格のAMIオファリングです。
## 先を見る
GitHubでDifyにスターを付け、新しいリリースをすぐに通知されます。
![star-us](https://github.com/langgenius/dify/assets/13230914/b823edc1-6388-4e25-ad45-2f6b187adbb4)
## クイックスタート
> Difyをインストールする前に、マシンが以下の最小システム要件を満たしていることを確認してください:
>
>- CPU >= 2コア
>- RAM >= 4GB
</br>
Difyサーバーを起動する最も簡単な方法は、当社の[docker-compose.yml](docker/docker-compose.yaml)ファイルを実行することです。インストールコマンドを実行する前に、マシンに[Docker](https://docs.docker.com/get-docker/)と[Docker Compose](https://docs.docker.com/compose/install/)がインストールされていることを確認してください。
Difyサーバーを始める最も簡単な方法は、[docker-compose.yml](docker/docker-compose.yaml) ファイルを実行することです。インストールコマンドを実行する前に、マシンに [Docker](https://docs.docker.com/get-docker/) と [Docker Compose](https://docs.docker.com/compose/install/) がインストールされていることを確認してください:
```bash
cd docker
docker compose up -d
```
実行後、ブラウザで[http://localhost/install](http://localhost/install)にアクセスし、初期化プロセスを開始できます。
実行後、ブラウザで [http://localhost/install](http://localhost/install) にアクセスし、初期化インストールプロセスを開始できます。
> Difyに貢献したり、追加の開発を行う場合は、[ソースコードからのデプロイガイド](https://docs.dify.ai/getting-started/install-self-hosted/local-source-code)を参照してください。
### Helm Chart
## 次のステップ
@BorisPolonskyによる[Helm Chart](https://helm.sh/) バージョンを提供してくれて、大変感謝しています。これにより、DifyはKubernetes上にデプロイすることができます。
デプロイ情報については、https://github.com/BorisPolonsky/dify-helm をご覧ください。
環境設定をカスタマイズする場合は、[docker-compose.yml](docker/docker-compose.yaml)ファイル内のコメントを参照して、環境設定を手動で設定してください。変更を加えた後は、再び `docker-compose up -d` を実行してください。環境変数の完全なリストは[こちら](https://docs.dify.ai/getting-started/install-self-hosted/environments)をご覧ください。
### 設定
高可用性のセットアップを構成する場合は、コミュニティによって提供されている[Helm Charts](https://helm.sh/)があり、これによりKubernetes上にDifyを展開できます。
- [Helm Chart by @LeoQuote](https://github.com/douban/charts/tree/master/charts/dify)
- [Helm Chart by @BorisPolonsky](https://github.com/BorisPolonsky/dify-helm)
設定をカスタマイズする必要がある場合は、[docker-compose.yml](docker/docker-compose.yaml) ファイルのコメントを参照し、環境設定を手動で行ってください。変更を行った後は、もう一度 `docker-compose up -d` を実行してください。環境変数の完全なリストは、[ドキュメント](https://docs.dify.ai/getting-started/install-self-hosted/environments)で確認できます。
## 貢献
## スターヒストリー
コードに貢献したい方は、[Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md)を参照してください。
同時に、DifyをSNSやイベント、カンファレンスで共有してサポートしていただけると幸いです。
[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## コミュニティとサポート
> Difyを英語または中国語以外の言語に翻訳してくれる貢献者を募集しています。興味がある場合は、詳細については[i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md)を参照してください。また、[Discordコミュニティサーバー](https://discord.gg/8Tpq4AcN9c)の`global-users`チャンネルにコメントを残してください
Difyに貢献していただき、コードの提出、問題の報告、新しいアイデアの提供、またはDifyを基に作成した興味深く有用なAIアプリケーションの共有により、Difyをより良いものにするお手伝いを歓迎します。同時に、さまざまなイベント、会議、ソーシャルメディアでDifyを共有することも歓迎します
**貢献者**
- [GitHub Issues](https://github.com/langgenius/dify/issues)。最適な使用法:Dify.AIの使用中に遭遇するバグやエラー、[貢献ガイド](CONTRIBUTING.md)を参照。
- [Email サポート](mailto:hello@dify.ai?subject=[GitHub]Questions%20About%20Dify)。最適な使用法:Dify.AIの使用に関する質問。
- [Discord](https://discord.gg/FngNHpbcY7)。最適な使用法:アプリケーションの共有とコミュニティとの交流。
- [Twitter](https://twitter.com/dify_ai)。最適な使用法:アプリケーションの共有とコミュニティとの交流。
- [ビジネスライセンス](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry)。最適な使用法:Dify.AIを商業利用するためのビジネス関連の問い合わせ。
<a href="https://github.com/langgenius/dify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=langgenius/dify" />
</a>
## コミュニティ & お問い合わせ
* [Github Discussion](https://github.com/langgenius/dify/discussions). 主に: フィードバックの共有や質問。
* [GitHub Issues](https://github.com/langgenius/dify/issues). 主に: Dify.AIの使用中に遭遇したバグや機能提案。
* [Email](mailto:support@dify.ai?subject=[GitHub]Questions%20About%20Dify). 主に: Dify.AIの使用に関する質問。
* [Discord](https://discord.gg/FngNHpbcY7). 主に: アプリケーションの共有やコミュニティとの交流。
* [Twitter](https://twitter.com/dify_ai). 主に: アプリケーションの共有やコミュニティとの交流。
または、直接チームメンバーとミーティングをスケジュールします:
<table>
<tr>
<th>連絡先</th>
<th>目的</th>
</tr>
<tr>
<td><a href='https://cal.com
/guchenhe/30min'>ミーティング</a></td>
<td>無料の30分間のミーティングをスケジュールしてください。</td>
</tr>
<tr>
<td><a href='mailto:support@dify.ai?subject=[GitHub]Technical%20Support'>技術サポート</a></td>
<td>技術的な問題やサポートに関する質問</td>
</tr>
<tr>
<td><a href='mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry'>営業担当</a></td>
<td>法人ライセンスに関するお問い合わせ</td>
</tr>
</table>
## セキュリティ
プライバシー保護のため、GitHub へのセキュリティ問題の投稿は避けてください。代わりに、あなたの質問を security@dify.ai に送ってください。より詳細な回答を提供します。
## ライセンス
プロジェクトはMITライセンスの下で利用可能です。[LICENSE](LICENSE)をご参照ください
このリポジトリは、基本的にApache 2.0にいくつかの追加制限を加えた[Difyオープンソースライセンス](LICENSE)の下で利用できます
+64 -195
View File
@@ -1,250 +1,119 @@
![cover-v5-optimized](https://github.com/langgenius/dify/assets/13230914/f9e19af5-61ba-4119-b926-d10c4c06ebab)
[![](./images/describe.png)](https://dify.ai)
<p align="center">
<a href="https://cloud.dify.ai">Dify Cloud</a> ·
<a href="https://docs.dify.ai/getting-started/install-self-hosted">Self-hosting</a> ·
<a href="https://docs.dify.ai">Documentation</a> ·
<a href="https://cal.com/guchenhe/dify-demo">Schedule demo</a>
<a href="./README.md">English</a> |
<a href="./README_CN.md">简体中文</a> |
<a href="./README_JA.md">日本語</a> |
<a href="./README_ES.md">Español</a> |
<a href="./README_KL.md">Klingon</a> |
<a href="./README_FR.md">Français</a>
</p>
<p align="center">
<a href="https://dify.ai" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/Product-F04438"></a>
<a href="https://dify.ai/pricing" target="_blank">
<img alt="Static Badge" src="https://img.shields.io/badge/free-pricing?logo=free&color=%20%23155EEF&label=pricing&labelColor=%20%23528bff"></a>
<img alt="Static Badge" src="https://img.shields.io/badge/AI-Dify?logo=AI&logoColor=%20%23f5f5f5&label=Dify&labelColor=%20%23155EEF&color=%23EAECF0"></a>
<a href="https://discord.gg/FngNHpbcY7" target="_blank">
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb"
<img src="https://img.shields.io/discord/1082486657678311454?logo=discord"
alt="chat on Discord"></a>
<a href="https://twitter.com/intent/follow?screen_name=dify_ai" target="_blank">
<img src="https://img.shields.io/twitter/follow/dify_ai?logo=X&color=%20%23f5f5f5"
<img src="https://img.shields.io/twitter/follow/dify_ai?style=social&logo=X"
alt="follow on Twitter"></a>
<a href="https://hub.docker.com/u/langgenius" target="_blank">
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web?labelColor=%20%23FDB062&color=%20%23f79009"></a>
<a href="https://github.com/langgenius/dify/graphs/commit-activity" target="_blank">
<img alt="Commits last month" src="https://img.shields.io/github/commit-activity/m/langgenius/dify?labelColor=%20%2332b583&color=%20%2312b76a"></a>
<a href="https://github.com/langgenius/dify/" target="_blank">
<img alt="Issues closed" src="https://img.shields.io/github/issues-search?query=repo%3Alanggenius%2Fdify%20is%3Aclosed&label=issues%20closed&labelColor=%20%237d89b0&color=%20%235d6b98"></a>
<a href="https://github.com/langgenius/dify/discussions/" target="_blank">
<img alt="Discussion posts" src="https://img.shields.io/github/discussions/langgenius/dify?labelColor=%20%239b8afb&color=%20%237a5af8"></a>
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/langgenius/dify-web"></a>
</p>
<p align="center">
<a href="./README.md"><img alt="Commits last month" src="https://img.shields.io/badge/English-d9d9d9"></a>
<a href="./README_CN.md"><img alt="Commits last month" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
<a href="./README_JA.md"><img alt="Commits last month" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
<a href="./README_ES.md"><img alt="Commits last month" src="https://img.shields.io/badge/Español-d9d9d9"></a>
<a href="./README_KL.md"><img alt="Commits last month" src="https://img.shields.io/badge/Français-d9d9d9"></a>
<a href="./README_FR.md"><img alt="Commits last month" src="https://img.shields.io/badge/Klingon-d9d9d9"></a>
</p>
**Dify** Hoch LLM qorwI' pIqoDvam pagh laHta' je **100,000** pIqoDvamvam Dify.AI De'wI'. Dify leghpu' Backend chu' a Service teH LLMOps vItlhutlh, generative AI-native pIqoD teq wa'vam, vIyoD Built-in RAG engine. Dify, **'ej chenmoHmoH Hoch 'oHna' Assistant API 'ej GPTmey HoStaHbogh LLMmey.**
#
![](./images/demo.png)
<p align="center">
<a href="https://trendshift.io/repositories/2152" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2152" alt="langgenius%2Fdify | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</p>
Dify is an open-source LLM app development platform. Its intuitive interface combines AI workflow, RAG pipeline, agent capabilities, model management, observability features and more, letting you quickly go from prototype to production. Here's a list of the core features:
</br> </br>
## ngIl QaQ
**1. Workflow**:
Build and test powerful AI workflows on a visual canvas, leveraging all the following features and beyond.
[Dify.AI ngIl](https://dify.ai) pIm neHlaH 'ej ghaH. cha'logh wa' DIvI' 200 GPT trial credits.
## Dify WovmoH
https://github.com/langgenius/dify/assets/13230914/356df23e-1604-483d-80a6-9517ece318aa
Dify Daq rIn neutrality 'ej Hoch, LangChain tInHar HubwI'. maH Daqbe'law' Qawqar, OpenAI's Assistant API Daq local neH deployment.
| Qo'logh | Dify.AI | Assistants API | LangChain |
|---------|---------|----------------|-----------|
| **qet QaS** | API-oriented | API-oriented | Python Code-oriented |
| **Ecosystem Strategy** | Open Source | Closed and Commercial | Open Source |
| **RAG Engine** | Ha'qu' | Ha'qu' | ghoS Ha'qu' |
| **Prompt IDE** | jaH Include | jaH Include | qeylIS qaq |
| **qet LLMmey** | bo'Degh Hoch | GPTmey tIn | bo'Degh Hoch |
| **local deployment** | Ha'qu' | tInHa'qu' | tInHa'qu' ghogh |
## ruch
**2. Comprehensive model support**:
Seamless integration with hundreds of proprietary / open-source LLMs from dozens of inference providers and self-hosted solutions, covering GPT, Mistral, Llama2, and any OpenAI API-compatible models. A full list of supported model providers can be found [here](https://docs.dify.ai/getting-started/readme/model-providers).
![](./images/models.png)
![providers-v5](https://github.com/langgenius/dify/assets/13230914/5a17bdbe-097a-4100-8363-40255b70f6e3)
**1. LLM tIq**: OpenAI's GPT Hur nISmoHvam neH vIngeH, wa' Llama2 Hur nISmoHvam. Heghlu'lu'pu' Dify mIw 'oH choH qay'be'.Daq commercial Hurmey 'ej Open Source Hurmey (maqtaHvIS pagh locally neH neH deployment HoSvam).
**2. Prompt IDE**: cha'logh wa' LLMmey Hoch janlu'pu' 'ej lughpu' choH qay'be'.
**3. Prompt IDE**:
Intuitive interface for crafting prompts, comparing model performance, and adding additional features such as text-to-speech to a chat-based app.
**3. RAG Engine**: RAG vaD tIqpu' lo'taH indexing qor neH vector database wa' embeddings wIj, PDFs, TXTs, 'ej ghojmoHmoH HIq qorlIj je upload.
**4. RAG Pipeline**:
Extensive RAG capabilities that cover everything from document ingestion to retrieval, with out-of-box support for text extraction from PDFs, PPTs, and other common document formats.
**4. AI Agent**: Function Calling 'ej ReAct Daq Hurmey, Agent inference framework Hoch users customize tools, vaj 'oH QaQ. Dify Hoch loS ghaH 'ej wa'vatlh built-in tool calling capabilities, Google Search, DELL·E, Stable Diffusion, WolframAlpha, 'ej.
**5. Agent capabilities**:
You can define agents based on LLM Function Calling or ReAct, and add pre-built or custom tools for the agent. Dify provides 50+ built-in tools for AI agents, such as Google Search, DELL·E, Stable Diffusion and WolframAlpha.
**5. QaS muDHa'wI': cha'logh wa' pIq mI' logs 'ej quv yIn, vItlhutlh tIq 'e'wIj lo'taHmoHmoH Prompts, vItlhutlh, Hurmey ghaH production data jatlh.
**6. LLMOps**:
Monitor and analyze application logs and performance over time. You could continuously improve prompts, datasets, and models based on production data and annotations.
## Do'wI' qabmey lo'taH
**7. Backend-as-a-Service**:
All of Dify's offerings come with corresponding APIs, so you could effortlessly integrate Dify into your own business logic.
**maHvaD jatlhchugh, GitHub Daq Hoch chu' ghompu'vam tIqel yInob!**
![star-us](https://github.com/langgenius/dify/assets/100913391/95f37259-7370-4456-a9f0-0bc01ef8642f)
## Feature Comparison
<table style="width: 100%;">
<tr
- [Website](https://dify.ai)
- [Docs](https://docs.dify.ai)
- [lo'taHmoH Docs](https://docs.dify.ai/getting-started/install-self-hosted)
- [FAQ](https://docs.dify.ai/getting-started/faq)
>
<th align="center">Feature</th>
<th align="center">Dify.AI</th>
<th align="center">LangChain</th>
<th align="center">Flowise</th>
<th align="center">OpenAI Assistants API</th>
</tr>
<tr>
<td align="center">Programming Approach</td>
<td align="center">API + App-oriented</td>
<td align="center">Python Code</td>
<td align="center">App-oriented</td>
<td align="center">API-oriented</td>
</tr>
<tr>
<td align="center">Supported LLMs</td>
<td align="center">Rich Variety</td>
<td align="center">Rich Variety</td>
<td align="center">Rich Variety</td>
<td align="center">OpenAI-only</td>
</tr>
<tr>
<td align="center">RAG Engine</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Agent</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
</tr>
<tr>
<td align="center">Workflow</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Observability</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Enterprise Feature (SSO/Access control)</td>
<td align="center">✅</td>
<td align="center">❌</td>
<td align="center">❌</td>
<td align="center">❌</td>
</tr>
<tr>
<td align="center">Local Deployment</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">✅</td>
<td align="center">❌</td>
</tr>
</table>
## Community Edition tu' yo'
## Using Dify
### System Qab
- **Cloud </br>**
We host a [Dify Cloud](https://dify.ai) service for anyone to try with zero setup. It provides all the capabilities of the self-deployed version, and includes 200 free GPT-4 calls in the sandbox plan.
Dify yo' yo' qaqmeH SuS chenmoH 'oH qech!
- **Self-hosting Dify Community Edition</br>**
Quickly get Dify running in your environment with this [starter guide](#quick-start).
Use our [documentation](https://docs.dify.ai) for further references and more in-depth instructions.
- CPU >= 2 Cores
- RAM >= 4GB
- **Dify for Enterprise / Organizations</br>**
We provide additional enterprise-centric features. [Schedule a meeting with us](https://cal.com/guchenhe/30min) or [send us an email](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry) to discuss enterprise needs. </br>
> For startups and small businesses using AWS, check out [Dify Premium on AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) and deploy it to your own AWS VPC with one-click. It's an affordable AMI offering with the option to create apps with custom logo and branding.
### Quick Start
## Staying ahead
Star Dify on GitHub and be instantly notified of new releases.
![star-us](https://github.com/langgenius/dify/assets/13230914/b823edc1-6388-4e25-ad45-2f6b187adbb4)
## Quick Start
> Before installing Dify, make sure your machine meets the following minimum system requirements:
>
>- CPU >= 2 Core
>- RAM >= 4GB
</br>
The easiest way to start the Dify server is to run our [docker-compose.yml](docker/docker-compose.yaml) file. Before running the installation command, make sure that [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) are installed on your machine:
Dify server luHoHtaHlu' vIngeH lo'laHbe'chugh vIyoD [docker-compose.yml](docker/docker-compose.yaml) QorwI'ghach. toH yItlhutlh chenmoH luH!chugh 'ay' vaj vIneHmeH, 'ej [Docker](https://docs.docker.com/get-docker/) 'ej [Docker Compose](https://docs.docker.com/compose/install/) vaj 'oH 'e' vIneHmeH:
```bash
cd docker
docker compose up -d
```
After running, you can access the Dify dashboard in your browser at [http://localhost/install](http://localhost/install) and start the initialization process.
luHoHtaHmeH HoHtaHvIS, Dify dashboard vIneHmeH vIngeH lI'wI' [http://localhost/install](http://localhost/install) 'ej 'oH initialization 'e' vIneHmeH.
> If you'd like to contribute to Dify or do additional development, refer to our [guide to deploying from source code](https://docs.dify.ai/getting-started/install-self-hosted/local-source-code)
### Helm Chart
## Next steps
@BorisPolonsky Dify wIq tIq ['ay'var (Helm Chart)](https://helm.sh/) version Hur yIn chu' Dify luHoHchu'. Heghlu'lu' vIneHmeH [https://github.com/BorisPolonsky/dify-helm](https://github.com/BorisPolonsky/dify-helm) 'ej vaj QaS deployment information.
If you need to customize the configuration, please refer to the comments in our [docker-compose.yml](docker/docker-compose.yaml) file and manually set the environment configuration. After making the changes, please run `docker-compose up -d` again. You can see the full list of environment variables [here](https://docs.dify.ai/getting-started/install-self-hosted/environments).
### veS config
If you'd like to configure a highly-available setup, there are community-contributed [Helm Charts](https://helm.sh/) which allow Dify to be deployed on Kubernetes.
chenmoHDI' config lo'taH ghaH, vItlhutlh HIq wIgharghbe'lu'pu'. toH lo'taHvIS pagh vay' vIneHmeH, 'ej `docker-compose up -d` wa'DIch. tIqmoHmeH list full wa' lo'taHvo'lu'pu' ghaH [docs](https://docs.dify.ai/getting-started/install-self-hosted/environments).
- [Helm Chart by @LeoQuote](https://github.com/douban/charts/tree/master/charts/dify)
- [Helm Chart by @BorisPolonsky](https://github.com/BorisPolonsky/dify-helm)
## tIng qem
[![tIng qem Hur Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Contributing
## choHmoH 'ej vItlhutlh
For those who'd like to contribute code, see our [Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
At the same time, please consider supporting Dify by sharing it on social media and at events and conferences.
Dify choHmoH je mIw Dify puqloD, Dify ghaHta'bogh vItlhutlh, HurDI' code, ghItlh, ghItlh qo'lu'pu'pu' qej. tIqmeH, Hurmey je, Dify Hur tIqDI' woDDaj, DuD QangmeH 'ej HInobDaq vItlhutlh HImej Dify'e'.
- [GitHub vItlhutlh](https://github.com/langgenius/dify/issues). Hurmey: bugs 'ej errors Dify.AI tIqmeH. yImej [Contribution Guide](CONTRIBUTING.md).
- [Email QaH](mailto:hello@dify.ai?subject=[GitHub]Questions%20About%20Dify). Hurmey: questions vItlhutlh Dify.AI chaw'.
- [Discord](https://discord.gg/FngNHpbcY7). Hurmey: jIpuv 'ej jImej mIw Dify vItlhutlh.
- [Twitter](https://twitter.com/dify_ai). Hurmey: jIpuv 'ej jImej mIw Dify vItlhutlh.
- [Business License](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry). Hurmey: qurgh vItlhutlh Hurmey Dify.AI tIqbe'law'.
> We are looking for contributors to help with translating Dify to languages other than Mandarin or English. If you are interested in helping, please see the [i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) for more information, and leave us a comment in the `global-users` channel of our [Discord Community Server](https://discord.gg/8Tpq4AcN9c).
## bIQDaqmey bom
**Contributors**
<a href="https://github.com/langgenius/dify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=langgenius/dify" />
</a>
## Community & Contact
* [Github Discussion](https://github.com/langgenius/dify/discussions
). Best for: sharing feedback and asking questions.
* [GitHub Issues](https://github.com/langgenius/dify/issues). Best for: bugs you encounter using Dify.AI, and feature proposals. See our [Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
* [Email](mailto:support@dify.ai?subject=[GitHub]Questions%20About%20Dify). Best for: questions you have about using Dify.AI.
* [Discord](https://discord.gg/FngNHpbcY7). Best for: sharing your applications and hanging out with the community.
* [Twitter](https://twitter.com/dify_ai). Best for: sharing your applications and hanging out with the community.
Or, schedule a meeting directly with a team member:
<table>
<tr>
<th>Point of Contact</th>
<th>Purpose</th>
</tr>
<tr>
<td><a href='https://cal.com/guchenhe/15min' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/9ebcd111-1205-4d71-83d5-948d70b809f5' alt='Git-Hub-README-Button-3x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Business enquiries & product feedback</td>
</tr>
<tr>
<td><a href='https://cal.com/pinkbanana' target='_blank'><img class="schedule-button" src='https://github.com/langgenius/dify/assets/13230914/d1edd00a-d7e4-4513-be6c-e57038e143fd' alt='Git-Hub-README-Button-2x' style="width: 180px; height: auto; object-fit: contain;"/></a></td>
<td>Contributions, issues & feature requests</td>
</tr>
</table>
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=langgenius/dify&type=Date)](https://star-history.com/#langgenius/dify&Date)
## Security Disclosure
To protect your privacy, please avoid posting security issues on GitHub. Instead, send your questions to security@dify.ai and we will provide you with a more detailed answer.
taghlI' vIngeH'a'? pong security 'oH posting GitHub. yItlhutlh, toH security@dify.ai 'ej vIngeH'a'.
## License
This repository is available under the [Dify Open Source License](LICENSE), which is essentially Apache 2.0 with a few additional restrictions.
ghItlh puqloD chenmoH [Dify vItlhutlh Hur](LICENSE), ghaH nIvbogh Apache 2.0.
+1 -12
View File
@@ -57,7 +57,7 @@ AZURE_BLOB_ACCOUNT_URL=https://<your_account_name>.blob.core.windows.net
WEB_API_CORS_ALLOW_ORIGINS=http://127.0.0.1:3000,*
CONSOLE_CORS_ALLOW_ORIGINS=http://127.0.0.1:3000,*
# Vector database configuration, support: weaviate, qdrant, milvus, relyt
# Vector database configuration, support: weaviate, qdrant, milvus
VECTOR_STORE=weaviate
# Weaviate configuration
@@ -78,13 +78,6 @@ MILVUS_USER=root
MILVUS_PASSWORD=Milvus
MILVUS_SECURE=false
# Relyt configuration
RELYT_HOST=127.0.0.1
RELYT_PORT=5432
RELYT_USER=postgres
RELYT_PASSWORD=postgres
RELYT_DATABASE=postgres
# Upload configuration
UPLOAD_FILE_SIZE_LIMIT=15
UPLOAD_FILE_BATCH_LIMIT=5
@@ -156,7 +149,3 @@ TEMPLATE_TRANSFORM_MAX_LENGTH=80000
CODE_MAX_STRING_ARRAY_LENGTH=30
CODE_MAX_OBJECT_ARRAY_LENGTH=30
CODE_MAX_NUMBER_ARRAY_LENGTH=1000
# API Tool configuration
API_TOOL_DEFAULT_CONNECT_TIMEOUT=10
API_TOOL_DEFAULT_READ_TIMEOUT=60
+2 -2
View File
@@ -6,7 +6,7 @@
"configurations": [
{
"name": "Python: Celery",
"type": "debugpy",
"type": "python",
"request": "launch",
"module": "celery",
"justMyCode": true,
@@ -21,7 +21,7 @@
},
{
"name": "Python: Flask",
"type": "debugpy",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
+1 -2
View File
@@ -11,8 +11,7 @@ RUN apt-get update \
COPY requirements.txt /requirements.txt
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --prefix=/pkg -r requirements.txt
RUN pip install --prefix=/pkg -r requirements.txt
# production stage
FROM base AS production
+6 -21
View File
@@ -17,16 +17,16 @@
```bash
sed -i "/^SECRET_KEY=/c\SECRET_KEY=$(openssl rand -base64 42)" .env
```
4. If you use Anaconda, create a new environment and activate it
3.5 If you use annaconda, create a new environment and activate it
```bash
conda create --name dify python=3.10
conda activate dify
```
5. Install dependencies
4. Install dependencies
```bash
pip install -r requirements.txt
```
6. Run migrate
5. Run migrate
Before the first launch, migrate the database to the latest version.
@@ -47,24 +47,9 @@
pip install -r requirements.txt --upgrade --force-reinstall
```
7. Start backend:
6. Start backend:
```bash
flask run --host 0.0.0.0 --port=5001 --debug
```
8. Setup your application by visiting http://localhost:5001/console/api/setup or other apis...
9. If you need to debug local async processing, please start the worker service by running
`celery -A app.celery worker -P gevent -c 1 --loglevel INFO -Q dataset,generation,mail`.
The started celery app handles the async tasks, e.g. dataset importing and documents indexing.
## Testing
1. Install dependencies for both the backend and the test environment
```bash
pip install -r requirements.txt -r requirements-dev.txt
```
2. Run the tests locally with mocked system environment variables in `tool.pytest_env` section in `pyproject.toml`
```bash
dev/pytest/pytest_all_tests.sh
```
7. Setup your application by visiting http://localhost:5001/console/api/setup or other apis...
8. If you need to debug local async processing, you can run `celery -A app.celery worker -P gevent -c 1 --loglevel INFO -Q dataset,generation,mail`, celery can do dataset importing and other async tasks.
+12 -35
View File
@@ -1,16 +1,17 @@
import os
import sys
from logging.handlers import RotatingFileHandler
from werkzeug.exceptions import Unauthorized
if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
from gevent import monkey
monkey.patch_all()
# if os.environ.get("VECTOR_STORE") == 'milvus':
import grpc.experimental.gevent
grpc.experimental.gevent.init_gevent()
import langchain
langchain.verbose = True
import json
import logging
import threading
@@ -19,13 +20,9 @@ import warnings
from flask import Flask, Response, request
from flask_cors import CORS
from werkzeug.exceptions import Unauthorized
from commands import register_commands
from config import CloudEditionConfig, Config
# DO NOT REMOVE BELOW
from events import event_handlers
from extensions import (
ext_celery,
ext_code_based_extension,
@@ -42,9 +39,11 @@ from extensions import (
from extensions.ext_database import db
from extensions.ext_login import login_manager
from libs.passport import PassportService
from models import account, dataset, model, source, task, tool, tools, web
from services.account_service import AccountService
# DO NOT REMOVE BELOW
from events import event_handlers
from models import account, dataset, model, source, task, tool, tools, web
# DO NOT REMOVE ABOVE
@@ -52,7 +51,7 @@ warnings.simplefilter("ignore", ResourceWarning)
# fix windows platform
if os.name == "nt":
os.system('tzutil /s "UTC"')
os.system('tzutil /s "UTC"')
else:
os.environ['TZ'] = 'UTC'
time.tzset()
@@ -61,7 +60,6 @@ else:
class DifyApp(Flask):
pass
# -------------
# Configuration
# -------------
@@ -69,7 +67,6 @@ class DifyApp(Flask):
config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
# ----------------------------
# Application Factory Function
# ----------------------------
@@ -88,25 +85,7 @@ def create_app(test_config=None) -> Flask:
app.secret_key = app.config['SECRET_KEY']
log_handlers = None
log_file = app.config.get('LOG_FILE')
if log_file:
log_dir = os.path.dirname(log_file)
os.makedirs(log_dir, exist_ok=True)
log_handlers = [
RotatingFileHandler(
filename=log_file,
maxBytes=1024 * 1024 * 1024,
backupCount=5
),
logging.StreamHandler(sys.stdout)
]
logging.basicConfig(
level=app.config.get('LOG_LEVEL'),
format=app.config.get('LOG_FORMAT'),
datefmt=app.config.get('LOG_DATEFORMAT'),
handlers=log_handlers
)
logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
initialize_extensions(app)
register_blueprints(app)
@@ -135,7 +114,7 @@ def initialize_extensions(app):
@login_manager.request_loader
def load_user_from_request(request_from_flask_login):
"""Load user based on the request."""
if request.blueprint in ['console', 'inner_api']:
if request.blueprint == 'console':
# Check if the user_id contains a dot, indicating the old format
auth_header = request.headers.get('Authorization', '')
if not auth_header:
@@ -171,7 +150,6 @@ def unauthorized_handler():
def register_blueprints(app):
from controllers.console import bp as console_app_bp
from controllers.files import bp as files_bp
from controllers.inner_api import bp as inner_api_bp
from controllers.service_api import bp as service_api_bp
from controllers.web import bp as web_bp
@@ -209,13 +187,12 @@ def register_blueprints(app):
)
app.register_blueprint(files_bp)
app.register_blueprint(inner_api_bp)
# create app
app = create_app()
celery = app.extensions["celery"]
if app.config['TESTING']:
print("App is running in TESTING mode")
-8
View File
@@ -297,14 +297,6 @@ def migrate_knowledge_vector_database():
"vector_store": {"class_prefix": collection_name}
}
dataset.index_struct = json.dumps(index_struct_dict)
elif vector_type == "relyt":
dataset_id = dataset.id
collection_name = Dataset.gen_collection_name_by_id(dataset_id)
index_struct_dict = {
"type": 'relyt',
"vector_store": {"class_prefix": collection_name}
}
dataset.index_struct = json.dumps(index_struct_dict)
else:
raise ValueError(f"Vector store {config.get('VECTOR_STORE')} is not supported.")
+5 -29
View File
@@ -38,14 +38,11 @@ DEFAULTS = {
'QDRANT_CLIENT_TIMEOUT': 20,
'CELERY_BACKEND': 'database',
'LOG_LEVEL': 'INFO',
'LOG_FILE': '',
'LOG_FORMAT': '%(asctime)s.%(msecs)03d %(levelname)s [%(threadName)s] [%(filename)s:%(lineno)d] - %(message)s',
'LOG_DATEFORMAT': '%Y-%m-%d %H:%M:%S',
'HOSTED_OPENAI_QUOTA_LIMIT': 200,
'HOSTED_OPENAI_TRIAL_ENABLED': 'False',
'HOSTED_OPENAI_TRIAL_MODELS': 'gpt-3.5-turbo,gpt-3.5-turbo-1106,gpt-3.5-turbo-instruct,gpt-3.5-turbo-16k,gpt-3.5-turbo-16k-0613,gpt-3.5-turbo-0613,gpt-3.5-turbo-0125,text-davinci-003',
'HOSTED_OPENAI_PAID_ENABLED': 'False',
'HOSTED_OPENAI_PAID_MODELS': 'gpt-4,gpt-4-turbo-preview,gpt-4-turbo-2024-04-09,gpt-4-1106-preview,gpt-4-0125-preview,gpt-3.5-turbo,gpt-3.5-turbo-16k,gpt-3.5-turbo-16k-0613,gpt-3.5-turbo-1106,gpt-3.5-turbo-0613,gpt-3.5-turbo-0125,gpt-3.5-turbo-instruct,text-davinci-003',
'HOSTED_OPENAI_PAID_MODELS': 'gpt-4,gpt-4-turbo-preview,gpt-4-1106-preview,gpt-4-0125-preview,gpt-3.5-turbo,gpt-3.5-turbo-16k,gpt-3.5-turbo-16k-0613,gpt-3.5-turbo-1106,gpt-3.5-turbo-0613,gpt-3.5-turbo-0125,gpt-3.5-turbo-instruct,text-davinci-003',
'HOSTED_AZURE_OPENAI_ENABLED': 'False',
'HOSTED_AZURE_OPENAI_QUOTA_LIMIT': 200,
'HOSTED_ANTHROPIC_QUOTA_LIMIT': 600000,
@@ -67,13 +64,10 @@ DEFAULTS = {
'ETL_TYPE': 'dify',
'KEYWORD_STORE': 'jieba',
'BATCH_UPLOAD_LIMIT': 20,
'CODE_EXECUTION_ENDPOINT': 'http://sandbox:8194',
'CODE_EXECUTION_API_KEY': 'dify-sandbox',
'CODE_EXECUTION_ENDPOINT': '',
'CODE_EXECUTION_API_KEY': '',
'TOOL_ICON_CACHE_MAX_AGE': 3600,
'MILVUS_DATABASE': 'default',
'KEYWORD_DATA_SOURCE_TYPE': 'database',
'INNER_API': 'False',
'ENTERPRISE_ENABLED': 'False',
}
@@ -104,15 +98,12 @@ class Config:
# ------------------------
# General Configurations.
# ------------------------
self.CURRENT_VERSION = "0.6.4"
self.CURRENT_VERSION = "0.6.0-preview-workflow.2"
self.COMMIT_SHA = get_env('COMMIT_SHA')
self.EDITION = "SELF_HOSTED"
self.DEPLOY_ENV = get_env('DEPLOY_ENV')
self.TESTING = False
self.LOG_LEVEL = get_env('LOG_LEVEL')
self.LOG_FILE = get_env('LOG_FILE')
self.LOG_FORMAT = get_env('LOG_FORMAT')
self.LOG_DATEFORMAT = get_env('LOG_DATEFORMAT')
# The backend URL prefix of the console API.
# used to concatenate the login authorization callback or notion integration callback.
@@ -141,11 +132,6 @@ class Config:
# Alternatively you can set it with `SECRET_KEY` environment variable.
self.SECRET_KEY = get_env('SECRET_KEY')
# Enable or disable the inner API.
self.INNER_API = get_bool_env('INNER_API')
# The inner API key is used to authenticate the inner API.
self.INNER_API_KEY = get_env('INNER_API_KEY')
# cors settings
self.CONSOLE_CORS_ALLOW_ORIGINS = get_cors_allow_origins(
'CONSOLE_CORS_ALLOW_ORIGINS', self.CONSOLE_WEB_URL)
@@ -211,7 +197,7 @@ class Config:
# ------------------------
# Vector Store Configurations.
# Currently, only support: qdrant, milvus, zilliz, weaviate, relyt
# Currently, only support: qdrant, milvus, zilliz, weaviate
# ------------------------
self.VECTOR_STORE = get_env('VECTOR_STORE')
self.KEYWORD_STORE = get_env('KEYWORD_STORE')
@@ -226,7 +212,6 @@ class Config:
self.MILVUS_USER = get_env('MILVUS_USER')
self.MILVUS_PASSWORD = get_env('MILVUS_PASSWORD')
self.MILVUS_SECURE = get_env('MILVUS_SECURE')
self.MILVUS_DATABASE = get_env('MILVUS_DATABASE')
# weaviate settings
self.WEAVIATE_ENDPOINT = get_env('WEAVIATE_ENDPOINT')
@@ -234,13 +219,6 @@ class Config:
self.WEAVIATE_GRPC_ENABLED = get_bool_env('WEAVIATE_GRPC_ENABLED')
self.WEAVIATE_BATCH_SIZE = int(get_env('WEAVIATE_BATCH_SIZE'))
# relyt settings
self.RELYT_HOST = get_env('RELYT_HOST')
self.RELYT_PORT = get_env('RELYT_PORT')
self.RELYT_USER = get_env('RELYT_USER')
self.RELYT_PASSWORD = get_env('RELYT_PASSWORD')
self.RELYT_DATABASE = get_env('RELYT_DATABASE')
# ------------------------
# Mail Configurations.
# ------------------------
@@ -340,8 +318,6 @@ class Config:
self.TOOL_ICON_CACHE_MAX_AGE = get_env('TOOL_ICON_CACHE_MAX_AGE')
self.KEYWORD_DATA_SOURCE_TYPE = get_env('KEYWORD_DATA_SOURCE_TYPE')
self.ENTERPRISE_ENABLED = get_bool_env('ENTERPRISE_ENABLED')
class CloudEditionConfig(Config):
+1
View File
@@ -1,3 +1,4 @@
# -*- coding:utf-8 -*-
+6 -41
View File
@@ -1,57 +1,22 @@
from flask import Blueprint
from libs.external_api import ExternalApi
bp = Blueprint('console', __name__, url_prefix='/console/api')
api = ExternalApi(bp)
# Import other controllers
from . import admin, apikey, extension, feature, ping, setup, version
from . import admin, apikey, extension, feature, setup, version, ping
# Import app controllers
from .app import (
advanced_prompt_template,
agent,
annotation,
app,
audio,
completion,
conversation,
generator,
message,
model_config,
site,
statistic,
workflow,
workflow_app_log,
workflow_run,
workflow_statistic,
)
from .app import (advanced_prompt_template, annotation, app, audio, completion, conversation, generator, message,
model_config, site, statistic, workflow, workflow_run, workflow_app_log, workflow_statistic, agent)
# Import auth controllers
from .auth import activate, data_source_oauth, login, oauth
# Import billing controllers
from .billing import billing
# Import datasets controllers
from .datasets import data_source, datasets, datasets_document, datasets_segments, file, hit_testing
# Import enterprise controllers
from .enterprise import enterprise_sso
# Import explore controllers
from .explore import (
audio,
completion,
conversation,
installed_app,
message,
parameter,
recommended_app,
saved_message,
workflow,
)
from .explore import (audio, completion, conversation, installed_app, message, parameter, recommended_app,
saved_message, workflow)
# Import workspace controllers
from .workspace import account, members, model_providers, models, tool_providers, workspace
from .workspace import account, members, model_providers, models, tool_providers, workspace
+5 -4
View File
@@ -2,15 +2,13 @@ import json
from flask_login import current_user
from flask_restful import Resource, inputs, marshal_with, reqparse
from werkzeug.exceptions import BadRequest, Forbidden
from werkzeug.exceptions import Forbidden, BadRequest
from controllers.console import api
from controllers.console.app.wraps import get_app_model
from controllers.console.setup import setup_required
from controllers.console.wraps import account_initialization_required, cloud_edition_billing_resource_check
from core.agent.entities import AgentToolEntity
from core.tools.tool_manager import ToolManager
from core.tools.utils.configuration import ToolParameterConfigurationManager
from extensions.ext_database import db
from fields.app_fields import (
app_detail_fields,
@@ -18,8 +16,11 @@ from fields.app_fields import (
app_pagination_fields,
)
from libs.login import login_required
from models.model import App, AppMode, AppModelConfig
from services.app_service import AppService
from models.model import App, AppModelConfig, AppMode
from core.tools.utils.configuration import ToolParameterConfigurationManager
from core.tools.tool_manager import ToolManager
ALLOW_CREATE_APP_MODES = ['chat', 'agent-chat', 'advanced-chat', 'workflow', 'completion']
+3 -4
View File
@@ -1,4 +1,4 @@
from datetime import datetime, timezone
from datetime import datetime
import pytz
from flask_login import current_user
@@ -12,7 +12,6 @@ from controllers.console import api
from controllers.console.app.wraps import get_app_model
from controllers.console.setup import setup_required
from controllers.console.wraps import account_initialization_required
from core.app.entities.app_invoke_entities import InvokeFrom
from extensions.ext_database import db
from fields.conversation_fields import (
conversation_detail_fields,
@@ -203,7 +202,7 @@ class ChatConversationApi(Resource):
)
if app_model.mode == AppMode.ADVANCED_CHAT.value:
query = query.where(Conversation.invoke_from != InvokeFrom.DEBUGGER.value)
query = query.where(Conversation.override_model_configs.is_(None))
query = query.order_by(Conversation.created_at.desc())
@@ -262,7 +261,7 @@ def _get_conversation(app_model, conversation_id):
raise NotFound("Conversation Not Exists.")
if not conversation.read_at:
conversation.read_at = datetime.now(timezone.utc).replace(tzinfo=None)
conversation.read_at = datetime.utcnow()
conversation.read_account_id = current_user.id
db.session.commit()
+2 -2
View File
@@ -1,6 +1,6 @@
import base64
import datetime
import secrets
from datetime import datetime
from flask_restful import Resource, reqparse
@@ -66,7 +66,7 @@ class ActivateApi(Resource):
account.timezone = args['timezone']
account.interface_theme = 'light'
account.status = AccountStatus.ACTIVE.value
account.initialized_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
account.initialized_at = datetime.utcnow()
db.session.commit()
return {'result': 'success'}
+3 -6
View File
@@ -26,13 +26,10 @@ class LoginApi(Resource):
try:
account = AccountService.authenticate(args['email'], args['password'])
except services.errors.account.AccountLoginError as e:
return {'code': 'unauthorized', 'message': str(e)}, 401
except services.errors.account.AccountLoginError:
return {'code': 'unauthorized', 'message': 'Invalid email or password'}, 401
# SELF_HOSTED only have one workspace
tenants = TenantService.get_join_tenants(account)
if len(tenants) == 0:
return {'result': 'fail', 'data': 'workspace not found, please contact system admin to invite you to join in a workspace'}
TenantService.create_owner_tenant_if_not_exist(account)
AccountService.update_last_login(account, request)
+2 -2
View File
@@ -1,5 +1,5 @@
import logging
from datetime import datetime, timezone
from datetime import datetime
from typing import Optional
import requests
@@ -73,7 +73,7 @@ class OAuthCallback(Resource):
if account.status == AccountStatus.PENDING.value:
account.status = AccountStatus.ACTIVE.value
account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
account.initialized_at = datetime.utcnow()
db.session.commit()
TenantService.create_owner_tenant_if_not_exist(account)
@@ -80,7 +80,7 @@ class DataSourceApi(Resource):
if action == 'enable':
if data_source_binding.disabled:
data_source_binding.disabled = False
data_source_binding.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
data_source_binding.updated_at = datetime.datetime.utcnow()
db.session.add(data_source_binding)
db.session.commit()
else:
@@ -89,7 +89,7 @@ class DataSourceApi(Resource):
if action == 'disable':
if not data_source_binding.disabled:
data_source_binding.disabled = True
data_source_binding.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
data_source_binding.updated_at = datetime.datetime.utcnow()
db.session.add(data_source_binding)
db.session.commit()
else:
@@ -1,4 +1,4 @@
from datetime import datetime, timezone
from datetime import datetime
from flask import request
from flask_login import current_user
@@ -637,7 +637,7 @@ class DocumentProcessingApi(DocumentResource):
raise InvalidActionError('Document not in indexing state.')
document.paused_by = current_user.id
document.paused_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.paused_at = datetime.utcnow()
document.is_paused = True
db.session.commit()
@@ -717,7 +717,7 @@ class DocumentMetadataApi(DocumentResource):
document.doc_metadata[key] = value
document.doc_type = doc_type
document.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.updated_at = datetime.utcnow()
db.session.commit()
return {'result': 'success', 'message': 'Document metadata updated.'}, 200
@@ -755,7 +755,7 @@ class DocumentStatusApi(DocumentResource):
document.enabled = True
document.disabled_at = None
document.disabled_by = None
document.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.updated_at = datetime.utcnow()
db.session.commit()
# Set cache to prevent indexing the same document multiple times
@@ -772,9 +772,9 @@ class DocumentStatusApi(DocumentResource):
raise InvalidActionError('Document already disabled.')
document.enabled = False
document.disabled_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.disabled_at = datetime.utcnow()
document.disabled_by = current_user.id
document.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.updated_at = datetime.utcnow()
db.session.commit()
# Set cache to prevent indexing the same document multiple times
@@ -789,9 +789,9 @@ class DocumentStatusApi(DocumentResource):
raise InvalidActionError('Document already archived.')
document.archived = True
document.archived_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.archived_at = datetime.utcnow()
document.archived_by = current_user.id
document.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.updated_at = datetime.utcnow()
db.session.commit()
if document.enabled:
@@ -808,7 +808,7 @@ class DocumentStatusApi(DocumentResource):
document.archived = False
document.archived_at = None
document.archived_by = None
document.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
document.updated_at = datetime.utcnow()
db.session.commit()
# Set cache to prevent indexing the same document multiple times
@@ -1,5 +1,5 @@
import uuid
from datetime import datetime, timezone
from datetime import datetime
import pandas as pd
from flask import request
@@ -192,7 +192,7 @@ class DatasetDocumentSegmentApi(Resource):
raise InvalidActionError("Segment is already disabled.")
segment.enabled = False
segment.disabled_at = datetime.now(timezone.utc).replace(tzinfo=None)
segment.disabled_at = datetime.utcnow()
segment.disabled_by = current_user.id
db.session.commit()
@@ -12,7 +12,7 @@ from controllers.console.app.error import (
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
from controllers.console.datasets.error import DatasetNotInitializedError
from controllers.console.datasets.error import DatasetNotInitializedError, HighQualityDatasetOnlyError
from controllers.console.setup import setup_required
from controllers.console.wraps import account_initialization_required
from core.errors.error import (
@@ -45,6 +45,10 @@ class HitTestingApi(Resource):
except services.errors.account.NoPermissionError as e:
raise Forbidden(str(e))
# only high quality dataset can be used for hit testing
if dataset.indexing_technique != 'high_quality':
raise HighQualityDatasetOnlyError()
parser = reqparse.RequestParser()
parser.add_argument('query', type=str, location='json')
parser.add_argument('retrieval_model', type=dict, required=False, location='json')
@@ -1,59 +0,0 @@
from flask import current_app, redirect
from flask_restful import Resource, reqparse
from controllers.console import api
from controllers.console.setup import setup_required
from services.enterprise.enterprise_sso_service import EnterpriseSSOService
class EnterpriseSSOSamlLogin(Resource):
@setup_required
def get(self):
return EnterpriseSSOService.get_sso_saml_login()
class EnterpriseSSOSamlAcs(Resource):
@setup_required
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('SAMLResponse', type=str, required=True, location='form')
args = parser.parse_args()
saml_response = args['SAMLResponse']
try:
token = EnterpriseSSOService.post_sso_saml_acs(saml_response)
return redirect(f'{current_app.config.get("CONSOLE_WEB_URL")}/signin?console_token={token}')
except Exception as e:
return redirect(f'{current_app.config.get("CONSOLE_WEB_URL")}/signin?message={str(e)}')
class EnterpriseSSOOidcLogin(Resource):
@setup_required
def get(self):
return EnterpriseSSOService.get_sso_oidc_login()
class EnterpriseSSOOidcCallback(Resource):
@setup_required
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('state', type=str, required=True, location='args')
parser.add_argument('code', type=str, required=True, location='args')
parser.add_argument('oidc-state', type=str, required=True, location='cookies')
args = parser.parse_args()
try:
token = EnterpriseSSOService.get_sso_oidc_callback(args)
return redirect(f'{current_app.config.get("CONSOLE_WEB_URL")}/signin?console_token={token}')
except Exception as e:
return redirect(f'{current_app.config.get("CONSOLE_WEB_URL")}/signin?message={str(e)}')
api.add_resource(EnterpriseSSOSamlLogin, '/enterprise/sso/saml/login')
api.add_resource(EnterpriseSSOSamlAcs, '/enterprise/sso/saml/acs')
api.add_resource(EnterpriseSSOOidcLogin, '/enterprise/sso/oidc/login')
api.add_resource(EnterpriseSSOOidcCallback, '/enterprise/sso/oidc/callback')
@@ -1,5 +1,5 @@
import logging
from datetime import datetime, timezone
from datetime import datetime
from flask_login import current_user
from flask_restful import reqparse
@@ -47,7 +47,7 @@ class CompletionApi(InstalledAppResource):
streaming = args['response_mode'] == 'streaming'
args['auto_generate_name'] = False
installed_app.last_used_at = datetime.now(timezone.utc).replace(tzinfo=None)
installed_app.last_used_at = datetime.utcnow()
db.session.commit()
try:
@@ -110,7 +110,7 @@ class ChatApi(InstalledAppResource):
args['auto_generate_name'] = False
installed_app.last_used_at = datetime.now(timezone.utc).replace(tzinfo=None)
installed_app.last_used_at = datetime.utcnow()
db.session.commit()
try:
@@ -6,7 +6,6 @@ from werkzeug.exceptions import NotFound
from controllers.console import api
from controllers.console.explore.error import NotChatAppError
from controllers.console.explore.wraps import InstalledAppResource
from core.app.entities.app_invoke_entities import InvokeFrom
from fields.conversation_fields import conversation_infinite_scroll_pagination_fields, simple_conversation_fields
from libs.helper import uuid_value
from models.model import AppMode
@@ -40,8 +39,8 @@ class ConversationListApi(InstalledAppResource):
user=current_user,
last_id=args['last_id'],
limit=args['limit'],
invoke_from=InvokeFrom.EXPLORE,
pinned=pinned,
exclude_debug_conversation=True
)
except LastConversationNotExistsError:
raise NotFound("Last Conversation Not Exists.")
@@ -1,4 +1,4 @@
from datetime import datetime, timezone
from datetime import datetime
from flask_login import current_user
from flask_restful import Resource, inputs, marshal_with, reqparse
@@ -81,7 +81,7 @@ class InstalledAppsListApi(Resource):
tenant_id=current_tenant_id,
app_owner_tenant_id=app.tenant_id,
is_pinned=False,
last_used_at=datetime.now(timezone.utc).replace(tzinfo=None)
last_used_at=datetime.utcnow()
)
db.session.add(new_installed_app)
db.session.commit()
-7
View File
@@ -1,7 +1,6 @@
from flask_login import current_user
from flask_restful import Resource
from services.enterprise.enterprise_feature_service import EnterpriseFeatureService
from services.feature_service import FeatureService
from . import api
@@ -15,10 +14,4 @@ class FeatureApi(Resource):
return FeatureService.get_features(current_user.current_tenant_id).dict()
class EnterpriseFeatureApi(Resource):
def get(self):
return EnterpriseFeatureService.get_enterprise_features().dict()
api.add_resource(FeatureApi, '/features')
api.add_resource(EnterpriseFeatureApi, '/enterprise-features')
-2
View File
@@ -58,8 +58,6 @@ class SetupApi(Resource):
password=args['password']
)
TenantService.create_owner_tenant_if_not_exist(account)
setup()
AccountService.update_last_login(account, request)
+3 -3
View File
@@ -1,4 +1,4 @@
import datetime
from datetime import datetime
import pytz
from flask import current_app, request
@@ -59,7 +59,7 @@ class AccountInitApi(Resource):
raise InvalidInvitationCodeError()
invitation_code.status = 'used'
invitation_code.used_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
invitation_code.used_at = datetime.utcnow()
invitation_code.used_by_tenant_id = account.current_tenant_id
invitation_code.used_by_account_id = account.id
@@ -67,7 +67,7 @@ class AccountInitApi(Resource):
account.timezone = args['timezone']
account.interface_theme = 'light'
account.status = 'active'
account.initialized_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
account.initialized_at = datetime.utcnow()
db.session.commit()
return {'result': 'success'}
+1 -12
View File
@@ -3,7 +3,6 @@ import logging
from flask import request
from flask_login import current_user
from flask_restful import Resource, fields, inputs, marshal, marshal_with, reqparse
from werkzeug.exceptions import Unauthorized
import services
from controllers.console import api
@@ -20,7 +19,7 @@ from controllers.console.wraps import account_initialization_required, cloud_edi
from extensions.ext_database import db
from libs.helper import TimestampField
from libs.login import login_required
from models.account import Tenant, TenantStatus
from models.account import Tenant
from services.account_service import TenantService
from services.file_service import FileService
from services.workspace_service import WorkspaceService
@@ -117,16 +116,6 @@ class TenantApi(Resource):
tenant = current_user.current_tenant
if tenant.status == TenantStatus.ARCHIVE:
tenants = TenantService.get_join_tenants(current_user)
# if there is any tenant, switch to the first one
if len(tenants) > 0:
TenantService.switch_tenant(current_user, tenants[0].id)
tenant = tenants[0]
# else, raise Unauthorized
else:
raise Unauthorized('workspace is archived')
return WorkspaceService.get_tenant_info(tenant), 200
+1 -1
View File
@@ -1,5 +1,5 @@
# -*- coding:utf-8 -*-
from flask import Blueprint
from libs.external_api import ExternalApi
bp = Blueprint('files', __name__)
-9
View File
@@ -1,9 +0,0 @@
from flask import Blueprint
from libs.external_api import ExternalApi
bp = Blueprint('inner_api', __name__, url_prefix='/inner/api')
api = ExternalApi(bp)
from .workspace import workspace
@@ -1,37 +0,0 @@
from flask_restful import Resource, reqparse
from controllers.console.setup import setup_required
from controllers.inner_api import api
from controllers.inner_api.wraps import inner_api_only
from events.tenant_event import tenant_was_created
from models.account import Account
from services.account_service import TenantService
class EnterpriseWorkspace(Resource):
@setup_required
@inner_api_only
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True, location='json')
parser.add_argument('owner_email', type=str, required=True, location='json')
args = parser.parse_args()
account = Account.query.filter_by(email=args['owner_email']).first()
if account is None:
return {
'message': 'owner account not found.'
}, 404
tenant = TenantService.create_tenant(args['name'])
TenantService.create_tenant_member(tenant, account, role='owner')
tenant_was_created.send(tenant)
return {
'message': 'enterprise workspace created.'
}
api.add_resource(EnterpriseWorkspace, '/enterprise/workspace')
-61
View File
@@ -1,61 +0,0 @@
from base64 import b64encode
from functools import wraps
from hashlib import sha1
from hmac import new as hmac_new
from flask import abort, current_app, request
from extensions.ext_database import db
from models.model import EndUser
def inner_api_only(view):
@wraps(view)
def decorated(*args, **kwargs):
if not current_app.config['INNER_API']:
abort(404)
# get header 'X-Inner-Api-Key'
inner_api_key = request.headers.get('X-Inner-Api-Key')
if not inner_api_key or inner_api_key != current_app.config['INNER_API_KEY']:
abort(404)
return view(*args, **kwargs)
return decorated
def inner_api_user_auth(view):
@wraps(view)
def decorated(*args, **kwargs):
if not current_app.config['INNER_API']:
return view(*args, **kwargs)
# get header 'X-Inner-Api-Key'
authorization = request.headers.get('Authorization')
if not authorization:
return view(*args, **kwargs)
parts = authorization.split(':')
if len(parts) != 2:
return view(*args, **kwargs)
user_id, token = parts
if ' ' in user_id:
user_id = user_id.split(' ')[1]
inner_api_key = request.headers.get('X-Inner-Api-Key')
data_to_sign = f'DIFY {user_id}'
signature = hmac_new(inner_api_key.encode('utf-8'), data_to_sign.encode('utf-8'), sha1)
signature = b64encode(signature.digest()).decode('utf-8')
if signature != token:
return view(*args, **kwargs)
kwargs['user'] = db.session.query(EndUser).filter(EndUser.id == user_id).first()
return view(*args, **kwargs)
return decorated
+1 -1
View File
@@ -1,5 +1,5 @@
# -*- coding:utf-8 -*-
from flask import Blueprint
from libs.external_api import ExternalApi
bp = Blueprint('service_api', __name__, url_prefix='/v1')
+5 -12
View File
@@ -1,11 +1,14 @@
import json
from flask import current_app
from flask_restful import Resource, fields, marshal_with
from flask_restful import fields, marshal_with, Resource
from controllers.service_api import api
from controllers.service_api.app.error import AppUnavailableError
from controllers.service_api.wraps import validate_app_token
from models.model import App, AppMode
from extensions.ext_database import db
from models.model import App, AppModelConfig, AppMode
from models.tools import ApiToolProvider
from services.app_service import AppService
@@ -89,16 +92,6 @@ class AppMetaApi(Resource):
"""Get app meta"""
return AppService().get_app_meta(app_model)
class AppInfoApi(Resource):
@validate_app_token
def get(self, app_model: App):
"""Get app infomation"""
return {
'name':app_model.name,
'description':app_model.description
}
api.add_resource(AppParameterApi, '/parameters')
api.add_resource(AppMetaApi, '/meta')
api.add_resource(AppInfoApi, '/info')
@@ -6,7 +6,6 @@ import services
from controllers.service_api import api
from controllers.service_api.app.error import NotChatAppError
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from core.app.entities.app_invoke_entities import InvokeFrom
from fields.conversation_fields import conversation_infinite_scroll_pagination_fields, simple_conversation_fields
from libs.helper import uuid_value
from models.model import App, AppMode, EndUser
@@ -28,13 +27,7 @@ class ConversationApi(Resource):
args = parser.parse_args()
try:
return ConversationService.pagination_by_last_id(
app_model=app_model,
user=end_user,
last_id=args['last_id'],
limit=args['limit'],
invoke_from=InvokeFrom.SERVICE_API
)
return ConversationService.pagination_by_last_id(app_model, end_user, args['last_id'], args['limit'])
except services.errors.conversation.LastConversationNotExistsError:
raise NotFound("Last Conversation Not Exists.")
@@ -174,7 +174,7 @@ class DocumentAddByFileApi(DatasetApiResource):
if not dataset:
raise ValueError('Dataset is not exist.')
if not dataset.indexing_technique and not args.get('indexing_technique'):
if not dataset.indexing_technique and not args['indexing_technique']:
raise ValueError('indexing_technique is required.')
# save file info
+3 -8
View File
@@ -1,5 +1,5 @@
from collections.abc import Callable
from datetime import datetime, timezone
from datetime import datetime
from enum import Enum
from functools import wraps
from typing import Optional
@@ -12,7 +12,7 @@ from werkzeug.exceptions import Forbidden, NotFound, Unauthorized
from extensions.ext_database import db
from libs.login import _get_user
from models.account import Account, Tenant, TenantAccountJoin, TenantStatus
from models.account import Account, Tenant, TenantAccountJoin
from models.model import ApiToken, App, EndUser
from services.feature_service import FeatureService
@@ -47,10 +47,6 @@ def validate_app_token(view: Optional[Callable] = None, *, fetch_user_arg: Optio
if not app_model.enable_api:
raise NotFound()
tenant = db.session.query(Tenant).filter(Tenant.id == app_model.tenant_id).first()
if tenant.status == TenantStatus.ARCHIVE:
raise NotFound()
kwargs['app_model'] = app_model
if fetch_user_arg:
@@ -141,7 +137,6 @@ def validate_dataset_token(view=None):
.filter(Tenant.id == api_token.tenant_id) \
.filter(TenantAccountJoin.tenant_id == Tenant.id) \
.filter(TenantAccountJoin.role.in_(['owner'])) \
.filter(Tenant.status == TenantStatus.NORMAL) \
.one_or_none() # TODO: only owner information is required, so only one is returned.
if tenant_account_join:
tenant, ta = tenant_account_join
@@ -188,7 +183,7 @@ def validate_and_get_api_token(scope=None):
if not api_token:
raise Unauthorized("Access token is invalid")
api_token.last_used_at = datetime.now(timezone.utc).replace(tzinfo=None)
api_token.last_used_at = datetime.utcnow()
db.session.commit()
return api_token
+1 -1
View File
@@ -1,5 +1,5 @@
# -*- coding:utf-8 -*-
from flask import Blueprint
from libs.external_api import ExternalApi
bp = Blueprint('web', __name__, url_prefix='/api')
+1 -1
View File
@@ -7,7 +7,7 @@ from controllers.web import api
from controllers.web.error import AppUnavailableError
from controllers.web.wraps import WebApiResource
from extensions.ext_database import db
from models.model import App, AppMode, AppModelConfig
from models.model import App, AppModelConfig, AppMode
from models.tools import ApiToolProvider
from services.app_service import AppService
+1 -3
View File
@@ -5,7 +5,6 @@ from werkzeug.exceptions import NotFound
from controllers.web import api
from controllers.web.error import NotChatAppError
from controllers.web.wraps import WebApiResource
from core.app.entities.app_invoke_entities import InvokeFrom
from fields.conversation_fields import conversation_infinite_scroll_pagination_fields, simple_conversation_fields
from libs.helper import uuid_value
from models.model import AppMode
@@ -38,8 +37,7 @@ class ConversationListApi(WebApiResource):
user=end_user,
last_id=args['last_id'],
limit=args['limit'],
invoke_from=InvokeFrom.WEB_APP,
pinned=pinned,
pinned=pinned
)
except LastConversationNotExistsError:
raise NotFound("Last Conversation Not Exists.")
-4
View File
@@ -6,7 +6,6 @@ from werkzeug.exceptions import Forbidden
from controllers.web import api
from controllers.web.wraps import WebApiResource
from extensions.ext_database import db
from models.account import TenantStatus
from models.model import Site
from services.feature_service import FeatureService
@@ -55,9 +54,6 @@ class AppSiteApi(WebApiResource):
if not site:
raise Forbidden()
if app_model.tenant.status == TenantStatus.ARCHIVE:
raise Forbidden()
can_replace_logo = FeatureService.get_features(app_model.tenant_id).can_replace_logo
return AppSiteInfo(app_model.tenant, app_model, site, end_user.id, can_replace_logo)
+7 -79
View File
@@ -1,11 +1,10 @@
import json
import logging
import uuid
from datetime import datetime, timezone
from datetime import datetime
from typing import Optional, Union, cast
from core.agent.entities import AgentEntity, AgentToolEntity
from core.app.app_config.features.file_upload.manager import FileUploadConfigManager
from core.app.apps.agent_chat.app_config_manager import AgentChatAppConfig
from core.app.apps.base_app_queue_manager import AppQueueManager
from core.app.apps.base_app_runner import AppRunner
@@ -15,7 +14,6 @@ from core.app.entities.app_invoke_entities import (
)
from core.callback_handler.agent_tool_callback_handler import DifyAgentCallbackHandler
from core.callback_handler.index_tool_callback_handler import DatasetIndexToolCallbackHandler
from core.file.message_file_parser import MessageFileParser
from core.memory.token_buffer_memory import TokenBufferMemory
from core.model_manager import ModelInstance
from core.model_runtime.entities.llm_entities import LLMUsage
@@ -24,7 +22,6 @@ from core.model_runtime.entities.message_entities import (
PromptMessage,
PromptMessageTool,
SystemPromptMessage,
TextPromptMessageContent,
ToolPromptMessage,
UserPromptMessage,
)
@@ -40,7 +37,7 @@ from core.tools.tool.dataset_retriever_tool import DatasetRetrieverTool
from core.tools.tool.tool import Tool
from core.tools.tool_manager import ToolManager
from extensions.ext_database import db
from models.model import Conversation, Message, MessageAgentThought
from models.model import Message, MessageAgentThought
from models.tools import ToolConversationVariables
logger = logging.getLogger(__name__)
@@ -48,7 +45,6 @@ logger = logging.getLogger(__name__)
class BaseAgentRunner(AppRunner):
def __init__(self, tenant_id: str,
application_generate_entity: AgentChatAppGenerateEntity,
conversation: Conversation,
app_config: AgentChatAppConfig,
model_config: ModelConfigWithCredentialsEntity,
config: AgentEntity,
@@ -76,7 +72,6 @@ class BaseAgentRunner(AppRunner):
"""
self.tenant_id = tenant_id
self.application_generate_entity = application_generate_entity
self.conversation = conversation
self.app_config = app_config
self.model_config = model_config
self.config = config
@@ -123,12 +118,6 @@ class BaseAgentRunner(AppRunner):
else:
self.stream_tool_call = False
# check if model supports vision
if model_schema and ModelFeature.VISION in (model_schema.features or []):
self.files = application_generate_entity.files
else:
self.files = []
def _repack_app_generate_entity(self, app_generate_entity: AgentChatAppGenerateEntity) \
-> AgentChatAppGenerateEntity:
"""
@@ -238,34 +227,6 @@ class BaseAgentRunner(AppRunner):
return prompt_tool
def _init_prompt_tools(self) -> tuple[dict[str, Tool], list[PromptMessageTool]]:
"""
Init tools
"""
tool_instances = {}
prompt_messages_tools = []
for tool in self.app_config.agent.tools if self.app_config.agent else []:
try:
prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
except Exception:
# api tool may be deleted
continue
# save tool entity
tool_instances[tool.tool_name] = tool_entity
# save prompt tool
prompt_messages_tools.append(prompt_tool)
# convert dataset tools into ModelRuntime Tool format
for dataset_tool in self.dataset_tools:
prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
# save prompt tool
prompt_messages_tools.append(prompt_tool)
# save tool entity
tool_instances[dataset_tool.identity.name] = dataset_tool
return tool_instances, prompt_messages_tools
def update_prompt_message_tool(self, tool: Tool, prompt_tool: PromptMessageTool) -> PromptMessageTool:
"""
update prompt message tool
@@ -353,7 +314,7 @@ class BaseAgentRunner(AppRunner):
tool_name: str,
tool_input: Union[str, dict],
thought: str,
observation: Union[str, dict],
observation: Union[str, str],
tool_invoke_meta: Union[str, dict],
answer: str,
messages_ids: list[str],
@@ -440,7 +401,7 @@ class BaseAgentRunner(AppRunner):
ToolConversationVariables.conversation_id == self.message.conversation_id,
).first()
db_variables.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
db_variables.updated_at = datetime.utcnow()
db_variables.variables_str = json.dumps(jsonable_encoder(tool_variables.pool))
db.session.commit()
db.session.close()
@@ -451,19 +412,15 @@ class BaseAgentRunner(AppRunner):
"""
result = []
# check if there is a system message in the beginning of the conversation
for prompt_message in prompt_messages:
if isinstance(prompt_message, SystemPromptMessage):
result.append(prompt_message)
if prompt_messages and isinstance(prompt_messages[0], SystemPromptMessage):
result.append(prompt_messages[0])
messages: list[Message] = db.session.query(Message).filter(
Message.conversation_id == self.message.conversation_id,
).order_by(Message.created_at.asc()).all()
for message in messages:
if message.id == self.message.id:
continue
result.append(self.organize_agent_user_prompt(message))
result.append(UserPromptMessage(content=message.query))
agent_thoughts: list[MessageAgentThought] = message.agent_thoughts
if agent_thoughts:
for agent_thought in agent_thoughts:
@@ -514,32 +471,3 @@ class BaseAgentRunner(AppRunner):
db.session.close()
return result
def organize_agent_user_prompt(self, message: Message) -> UserPromptMessage:
message_file_parser = MessageFileParser(
tenant_id=self.tenant_id,
app_id=self.app_config.app_id,
)
files = message.message_files
if files:
file_extra_config = FileUploadConfigManager.convert(message.app_model_config.to_dict())
if file_extra_config:
file_objs = message_file_parser.transform_message_files(
files,
file_extra_config
)
else:
file_objs = []
if not file_objs:
return UserPromptMessage(content=message.query)
else:
prompt_message_contents = [TextPromptMessageContent(data=message.query)]
for file_obj in file_objs:
prompt_message_contents.append(file_obj.prompt_message_content)
return UserPromptMessage(content=prompt_message_contents)
else:
return UserPromptMessage(content=message.query)
+445 -179
View File
@@ -1,36 +1,33 @@
import json
from abc import ABC, abstractmethod
import re
from collections.abc import Generator
from typing import Union
from typing import Literal, Union
from core.agent.base_agent_runner import BaseAgentRunner
from core.agent.entities import AgentScratchpadUnit
from core.agent.output_parser.cot_output_parser import CotAgentOutputParser
from core.agent.entities import AgentPromptEntity, AgentScratchpadUnit
from core.app.apps.base_app_queue_manager import PublishFrom
from core.app.entities.queue_entities import QueueAgentThoughtEvent, QueueMessageEndEvent, QueueMessageFileEvent
from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage
from core.model_runtime.entities.message_entities import (
AssistantPromptMessage,
PromptMessage,
PromptMessageTool,
SystemPromptMessage,
ToolPromptMessage,
UserPromptMessage,
)
from core.model_runtime.utils.encoders import jsonable_encoder
from core.tools.entities.tool_entities import ToolInvokeMeta
from core.tools.tool.tool import Tool
from core.tools.tool_engine import ToolEngine
from models.model import Message
from models.model import Conversation, Message
class CotAgentRunner(BaseAgentRunner, ABC):
class CotAgentRunner(BaseAgentRunner):
_is_first_iteration = True
_ignore_observation_providers = ['wenxin']
_historic_prompt_messages: list[PromptMessage] = None
_agent_scratchpad: list[AgentScratchpadUnit] = None
_instruction: str = None
_query: str = None
_prompt_messages_tools: list[PromptMessage] = None
def run(self, message: Message,
def run(self, conversation: Conversation,
message: Message,
query: str,
inputs: dict[str, str],
) -> Union[Generator, LLMResult]:
@@ -39,7 +36,9 @@ class CotAgentRunner(BaseAgentRunner, ABC):
"""
app_generate_entity = self.application_generate_entity
self._repack_app_generate_entity(app_generate_entity)
self._init_react_state(query)
agent_scratchpad: list[AgentScratchpadUnit] = []
self._init_agent_scratchpad(agent_scratchpad, self.history_prompt_messages)
# check model mode
if 'Observation' not in app_generate_entity.model_config.stop:
@@ -48,19 +47,38 @@ class CotAgentRunner(BaseAgentRunner, ABC):
app_config = self.app_config
# init instruction
# override inputs
inputs = inputs or {}
instruction = app_config.prompt_template.simple_prompt_template
self._instruction = self._fill_in_inputs_from_external_data_tools(instruction, inputs)
instruction = self._fill_in_inputs_from_external_data_tools(instruction, inputs)
iteration_step = 1
max_iteration_steps = min(app_config.agent.max_iteration, 5) + 1
prompt_messages = self.history_prompt_messages
# convert tools into ModelRuntime Tool format
tool_instances, self._prompt_messages_tools = self._init_prompt_tools()
prompt_messages_tools: list[PromptMessageTool] = []
tool_instances = {}
for tool in app_config.agent.tools if app_config.agent else []:
try:
prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
except Exception:
# api tool may be deleted
continue
# save tool entity
tool_instances[tool.tool_name] = tool_entity
# save prompt tool
prompt_messages_tools.append(prompt_tool)
# convert dataset tools into ModelRuntime Tool format
for dataset_tool in self.dataset_tools:
prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
# save prompt tool
prompt_messages_tools.append(prompt_tool)
# save tool entity
tool_instances[dataset_tool.identity.name] = dataset_tool
prompt_messages = self._organize_prompt_messages()
function_call_state = True
llm_usage = {
'usage': None
@@ -85,7 +103,7 @@ class CotAgentRunner(BaseAgentRunner, ABC):
if iteration_step == max_iteration_steps:
# the last iteration, remove all tools
self._prompt_messages_tools = []
prompt_messages_tools = []
message_file_ids = []
@@ -102,8 +120,18 @@ class CotAgentRunner(BaseAgentRunner, ABC):
agent_thought_id=agent_thought.id
), PublishFrom.APPLICATION_MANAGER)
# update prompt messages
prompt_messages = self._organize_cot_prompt_messages(
mode=app_generate_entity.model_config.mode,
prompt_messages=prompt_messages,
tools=prompt_messages_tools,
agent_scratchpad=agent_scratchpad,
agent_prompt_message=app_config.agent.prompt,
instruction=instruction,
input=query
)
# recalc llm max tokens
prompt_messages = self._organize_prompt_messages()
self.recalc_llm_max_tokens(self.model_config, prompt_messages)
# invoke model
chunks: Generator[LLMResultChunk, None, None] = model_instance.invoke_llm(
@@ -121,7 +149,7 @@ class CotAgentRunner(BaseAgentRunner, ABC):
raise ValueError("failed to invoke llm")
usage_dict = {}
react_chunks = CotAgentOutputParser.handle_react_stream_output(chunks)
react_chunks = self._handle_stream_react(chunks, usage_dict)
scratchpad = AgentScratchpadUnit(
agent_response='',
thought='',
@@ -137,12 +165,30 @@ class CotAgentRunner(BaseAgentRunner, ABC):
), PublishFrom.APPLICATION_MANAGER)
for chunk in react_chunks:
if isinstance(chunk, AgentScratchpadUnit.Action):
action = chunk
# detect action
scratchpad.agent_response += json.dumps(chunk.dict())
scratchpad.action_str = json.dumps(chunk.dict())
scratchpad.action = action
if isinstance(chunk, dict):
scratchpad.agent_response += json.dumps(chunk)
try:
if scratchpad.action:
raise Exception("")
scratchpad.action_str = json.dumps(chunk)
scratchpad.action = AgentScratchpadUnit.Action(
action_name=chunk['action'],
action_input=chunk['action_input']
)
except:
scratchpad.thought += json.dumps(chunk)
yield LLMResultChunk(
model=self.model_config.model,
prompt_messages=prompt_messages,
system_fingerprint='',
delta=LLMResultChunkDelta(
index=0,
message=AssistantPromptMessage(
content=json.dumps(chunk, ensure_ascii=False) # if ensure_ascii=True, the text in webui maybe garbled text
),
usage=None
)
)
else:
scratchpad.agent_response += chunk
scratchpad.thought += chunk
@@ -160,29 +206,27 @@ class CotAgentRunner(BaseAgentRunner, ABC):
)
scratchpad.thought = scratchpad.thought.strip() or 'I am thinking about how to help you'
self._agent_scratchpad.append(scratchpad)
agent_scratchpad.append(scratchpad)
# get llm usage
if 'usage' in usage_dict:
increase_usage(llm_usage, usage_dict['usage'])
else:
usage_dict['usage'] = LLMUsage.empty_usage()
self.save_agent_thought(
agent_thought=agent_thought,
tool_name=scratchpad.action.action_name if scratchpad.action else '',
tool_input={
scratchpad.action.action_name: scratchpad.action.action_input
} if scratchpad.action else {},
tool_invoke_meta={},
thought=scratchpad.thought,
observation='',
answer=scratchpad.agent_response,
messages_ids=[],
llm_usage=usage_dict['usage']
)
self.save_agent_thought(agent_thought=agent_thought,
tool_name=scratchpad.action.action_name if scratchpad.action else '',
tool_input={
scratchpad.action.action_name: scratchpad.action.action_input
} if scratchpad.action else '',
tool_invoke_meta={},
thought=scratchpad.thought,
observation='',
answer=scratchpad.agent_response,
messages_ids=[],
llm_usage=usage_dict['usage'])
if not scratchpad.is_final():
if scratchpad.action and scratchpad.action.action_name.lower() != "final answer":
self.queue_manager.publish(QueueAgentThoughtEvent(
agent_thought_id=agent_thought.id
), PublishFrom.APPLICATION_MANAGER)
@@ -194,43 +238,106 @@ class CotAgentRunner(BaseAgentRunner, ABC):
if scratchpad.action.action_name.lower() == "final answer":
# action is final answer, return final answer directly
try:
if isinstance(scratchpad.action.action_input, dict):
final_answer = json.dumps(scratchpad.action.action_input)
elif isinstance(scratchpad.action.action_input, str):
final_answer = scratchpad.action.action_input
else:
final_answer = f'{scratchpad.action.action_input}'
final_answer = scratchpad.action.action_input if \
isinstance(scratchpad.action.action_input, str) else \
json.dumps(scratchpad.action.action_input)
except json.JSONDecodeError:
final_answer = f'{scratchpad.action.action_input}'
else:
function_call_state = True
# action is tool call, invoke tool
tool_invoke_response, tool_invoke_meta = self._handle_invoke_action(
action=scratchpad.action,
tool_instances=tool_instances,
message_file_ids=message_file_ids
)
scratchpad.observation = tool_invoke_response
scratchpad.agent_response = tool_invoke_response
tool_call_name = scratchpad.action.action_name
tool_call_args = scratchpad.action.action_input
tool_instance = tool_instances.get(tool_call_name)
if not tool_instance:
answer = f"there is not a tool named {tool_call_name}"
self.save_agent_thought(
agent_thought=agent_thought,
tool_name='',
tool_input='',
tool_invoke_meta=ToolInvokeMeta.error_instance(
f"there is not a tool named {tool_call_name}"
).to_dict(),
thought=None,
observation={
tool_call_name: answer
},
answer=answer,
messages_ids=[]
)
self.queue_manager.publish(QueueAgentThoughtEvent(
agent_thought_id=agent_thought.id
), PublishFrom.APPLICATION_MANAGER)
else:
if isinstance(tool_call_args, str):
try:
tool_call_args = json.loads(tool_call_args)
except json.JSONDecodeError:
pass
self.save_agent_thought(
agent_thought=agent_thought,
tool_name=scratchpad.action.action_name,
tool_input={scratchpad.action.action_name: scratchpad.action.action_input},
thought=scratchpad.thought,
observation={scratchpad.action.action_name: tool_invoke_response},
tool_invoke_meta=tool_invoke_meta.to_dict(),
answer=scratchpad.agent_response,
messages_ids=message_file_ids,
llm_usage=usage_dict['usage']
)
# invoke tool
tool_invoke_response, message_files, tool_invoke_meta = ToolEngine.agent_invoke(
tool=tool_instance,
tool_parameters=tool_call_args,
user_id=self.user_id,
tenant_id=self.tenant_id,
message=self.message,
invoke_from=self.application_generate_entity.invoke_from,
agent_tool_callback=self.agent_callback
)
# publish files
for message_file, save_as in message_files:
if save_as:
self.variables_pool.set_file(tool_name=tool_call_name, value=message_file.id, name=save_as)
self.queue_manager.publish(QueueAgentThoughtEvent(
agent_thought_id=agent_thought.id
), PublishFrom.APPLICATION_MANAGER)
# publish message file
self.queue_manager.publish(QueueMessageFileEvent(
message_file_id=message_file.id
), PublishFrom.APPLICATION_MANAGER)
# add message file ids
message_file_ids.append(message_file.id)
# publish files
for message_file, save_as in message_files:
if save_as:
self.variables_pool.set_file(tool_name=tool_call_name,
value=message_file.id,
name=save_as)
self.queue_manager.publish(QueueMessageFileEvent(
message_file_id=message_file.id
), PublishFrom.APPLICATION_MANAGER)
message_file_ids = [message_file.id for message_file, _ in message_files]
observation = tool_invoke_response
# save scratchpad
scratchpad.observation = observation
# save agent thought
self.save_agent_thought(
agent_thought=agent_thought,
tool_name=tool_call_name,
tool_input={
tool_call_name: tool_call_args
},
tool_invoke_meta={
tool_call_name: tool_invoke_meta.to_dict()
},
thought=None,
observation={
tool_call_name: observation
},
answer=scratchpad.agent_response,
messages_ids=message_file_ids,
)
self.queue_manager.publish(QueueAgentThoughtEvent(
agent_thought_id=agent_thought.id
), PublishFrom.APPLICATION_MANAGER)
# update prompt tool message
for prompt_tool in self._prompt_messages_tools:
for prompt_tool in prompt_messages_tools:
self.update_prompt_message_tool(tool_instances[prompt_tool.name], prompt_tool)
iteration_step += 1
@@ -272,63 +379,96 @@ class CotAgentRunner(BaseAgentRunner, ABC):
system_fingerprint=''
)), PublishFrom.APPLICATION_MANAGER)
def _handle_invoke_action(self, action: AgentScratchpadUnit.Action,
tool_instances: dict[str, Tool],
message_file_ids: list[str]) -> tuple[str, ToolInvokeMeta]:
"""
handle invoke action
:param action: action
:param tool_instances: tool instances
:return: observation, meta
"""
# action is tool call, invoke tool
tool_call_name = action.action_name
tool_call_args = action.action_input
tool_instance = tool_instances.get(tool_call_name)
if not tool_instance:
answer = f"there is not a tool named {tool_call_name}"
return answer, ToolInvokeMeta.error_instance(answer)
if isinstance(tool_call_args, str):
def _handle_stream_react(self, llm_response: Generator[LLMResultChunk, None, None], usage: dict) \
-> Generator[Union[str, dict], None, None]:
def parse_json(json_str):
try:
tool_call_args = json.loads(tool_call_args)
except json.JSONDecodeError:
pass
return json.loads(json_str.strip())
except:
return json_str
def extra_json_from_code_block(code_block) -> Generator[Union[dict, str], None, None]:
code_blocks = re.findall(r'```(.*?)```', code_block, re.DOTALL)
if not code_blocks:
return
for block in code_blocks:
json_text = re.sub(r'^[a-zA-Z]+\n', '', block.strip(), flags=re.MULTILINE)
yield parse_json(json_text)
code_block_cache = ''
code_block_delimiter_count = 0
in_code_block = False
json_cache = ''
json_quote_count = 0
in_json = False
got_json = False
for response in llm_response:
response = response.delta.message.content
if not isinstance(response, str):
continue
# invoke tool
tool_invoke_response, message_files, tool_invoke_meta = ToolEngine.agent_invoke(
tool=tool_instance,
tool_parameters=tool_call_args,
user_id=self.user_id,
tenant_id=self.tenant_id,
message=self.message,
invoke_from=self.application_generate_entity.invoke_from,
agent_tool_callback=self.agent_callback
)
# stream
index = 0
while index < len(response):
steps = 1
delta = response[index:index+steps]
if delta == '`':
code_block_cache += delta
code_block_delimiter_count += 1
else:
if not in_code_block:
if code_block_delimiter_count > 0:
yield code_block_cache
code_block_cache = ''
else:
code_block_cache += delta
code_block_delimiter_count = 0
# publish files
for message_file, save_as in message_files:
if save_as:
self.variables_pool.set_file(tool_name=tool_call_name, value=message_file.id, name=save_as)
if code_block_delimiter_count == 3:
if in_code_block:
yield from extra_json_from_code_block(code_block_cache)
code_block_cache = ''
in_code_block = not in_code_block
code_block_delimiter_count = 0
# publish message file
self.queue_manager.publish(QueueMessageFileEvent(
message_file_id=message_file.id
), PublishFrom.APPLICATION_MANAGER)
# add message file ids
message_file_ids.append(message_file.id)
if not in_code_block:
# handle single json
if delta == '{':
json_quote_count += 1
in_json = True
json_cache += delta
elif delta == '}':
json_cache += delta
if json_quote_count > 0:
json_quote_count -= 1
if json_quote_count == 0:
in_json = False
got_json = True
index += steps
continue
else:
if in_json:
json_cache += delta
return tool_invoke_response, tool_invoke_meta
if got_json:
got_json = False
yield parse_json(json_cache)
json_cache = ''
json_quote_count = 0
in_json = False
if not in_code_block and not in_json:
yield delta.replace('`', '')
def _convert_dict_to_action(self, action: dict) -> AgentScratchpadUnit.Action:
"""
convert dict to action
"""
return AgentScratchpadUnit.Action(
action_name=action['action'],
action_input=action['action_input']
)
index += steps
if code_block_cache:
yield code_block_cache
if json_cache:
yield parse_json(json_cache)
def _fill_in_inputs_from_external_data_tools(self, instruction: str, inputs: dict) -> str:
"""
@@ -342,46 +482,15 @@ class CotAgentRunner(BaseAgentRunner, ABC):
return instruction
def _init_react_state(self, query) -> None:
def _init_agent_scratchpad(self,
agent_scratchpad: list[AgentScratchpadUnit],
messages: list[PromptMessage]
) -> list[AgentScratchpadUnit]:
"""
init agent scratchpad
"""
self._query = query
self._agent_scratchpad = []
self._historic_prompt_messages = self._organize_historic_prompt_messages()
@abstractmethod
def _organize_prompt_messages(self) -> list[PromptMessage]:
"""
organize prompt messages
"""
def _format_assistant_message(self, agent_scratchpad: list[AgentScratchpadUnit]) -> str:
"""
format assistant message
"""
message = ''
for scratchpad in agent_scratchpad:
if scratchpad.is_final():
message += f"Final Answer: {scratchpad.agent_response}"
else:
message += f"Thought: {scratchpad.thought}\n\n"
if scratchpad.action_str:
message += f"Action: {scratchpad.action_str}\n\n"
if scratchpad.observation:
message += f"Observation: {scratchpad.observation}\n\n"
return message
def _organize_historic_prompt_messages(self) -> list[PromptMessage]:
"""
organize historic prompt messages
"""
result: list[PromptMessage] = []
scratchpad: list[AgentScratchpadUnit] = []
current_scratchpad: AgentScratchpadUnit = None
for message in self.history_prompt_messages:
for message in messages:
if isinstance(message, AssistantPromptMessage):
current_scratchpad = AgentScratchpadUnit(
agent_response=message.content,
@@ -396,29 +505,186 @@ class CotAgentRunner(BaseAgentRunner, ABC):
action_name=message.tool_calls[0].function.name,
action_input=json.loads(message.tool_calls[0].function.arguments)
)
current_scratchpad.action_str = json.dumps(
current_scratchpad.action.to_dict()
)
except:
pass
scratchpad.append(current_scratchpad)
agent_scratchpad.append(current_scratchpad)
elif isinstance(message, ToolPromptMessage):
if current_scratchpad:
current_scratchpad.observation = message.content
elif isinstance(message, UserPromptMessage):
result.append(message)
if scratchpad:
result.append(AssistantPromptMessage(
content=self._format_assistant_message(scratchpad)
))
scratchpad = []
if scratchpad:
result.append(AssistantPromptMessage(
content=self._format_assistant_message(scratchpad)
))
return result
return agent_scratchpad
def _check_cot_prompt_messages(self, mode: Literal["completion", "chat"],
agent_prompt_message: AgentPromptEntity,
):
"""
check chain of thought prompt messages, a standard prompt message is like:
Respond to the human as helpfully and accurately as possible.
{{instruction}}
You have access to the following tools:
{{tools}}
Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
Valid action values: "Final Answer" or {{tool_names}}
Provide only ONE action per $JSON_BLOB, as shown:
```
{
"action": $TOOL_NAME,
"action_input": $ACTION_INPUT
}
```
"""
# parse agent prompt message
first_prompt = agent_prompt_message.first_prompt
next_iteration = agent_prompt_message.next_iteration
if not isinstance(first_prompt, str) or not isinstance(next_iteration, str):
raise ValueError("first_prompt or next_iteration is required in CoT agent mode")
# check instruction, tools, and tool_names slots
if not first_prompt.find("{{instruction}}") >= 0:
raise ValueError("{{instruction}} is required in first_prompt")
if not first_prompt.find("{{tools}}") >= 0:
raise ValueError("{{tools}} is required in first_prompt")
if not first_prompt.find("{{tool_names}}") >= 0:
raise ValueError("{{tool_names}} is required in first_prompt")
if mode == "completion":
if not first_prompt.find("{{query}}") >= 0:
raise ValueError("{{query}} is required in first_prompt")
if not first_prompt.find("{{agent_scratchpad}}") >= 0:
raise ValueError("{{agent_scratchpad}} is required in first_prompt")
if mode == "completion":
if not next_iteration.find("{{observation}}") >= 0:
raise ValueError("{{observation}} is required in next_iteration")
def _convert_scratchpad_list_to_str(self, agent_scratchpad: list[AgentScratchpadUnit]) -> str:
"""
convert agent scratchpad list to str
"""
next_iteration = self.app_config.agent.prompt.next_iteration
result = ''
for scratchpad in agent_scratchpad:
result += (scratchpad.thought or '') + (scratchpad.action_str or '') + \
next_iteration.replace("{{observation}}", scratchpad.observation or 'It seems that no response is available')
return result
def _organize_cot_prompt_messages(self, mode: Literal["completion", "chat"],
prompt_messages: list[PromptMessage],
tools: list[PromptMessageTool],
agent_scratchpad: list[AgentScratchpadUnit],
agent_prompt_message: AgentPromptEntity,
instruction: str,
input: str,
) -> list[PromptMessage]:
"""
organize chain of thought prompt messages, a standard prompt message is like:
Respond to the human as helpfully and accurately as possible.
{{instruction}}
You have access to the following tools:
{{tools}}
Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
Valid action values: "Final Answer" or {{tool_names}}
Provide only ONE action per $JSON_BLOB, as shown:
```
{{{{
"action": $TOOL_NAME,
"action_input": $ACTION_INPUT
}}}}
```
"""
self._check_cot_prompt_messages(mode, agent_prompt_message)
# parse agent prompt message
first_prompt = agent_prompt_message.first_prompt
# parse tools
tools_str = self._jsonify_tool_prompt_messages(tools)
# parse tools name
tool_names = '"' + '","'.join([tool.name for tool in tools]) + '"'
# get system message
system_message = first_prompt.replace("{{instruction}}", instruction) \
.replace("{{tools}}", tools_str) \
.replace("{{tool_names}}", tool_names)
# organize prompt messages
if mode == "chat":
# override system message
overridden = False
prompt_messages = prompt_messages.copy()
for prompt_message in prompt_messages:
if isinstance(prompt_message, SystemPromptMessage):
prompt_message.content = system_message
overridden = True
break
# convert tool prompt messages to user prompt messages
for idx, prompt_message in enumerate(prompt_messages):
if isinstance(prompt_message, ToolPromptMessage):
prompt_messages[idx] = UserPromptMessage(
content=prompt_message.content
)
if not overridden:
prompt_messages.insert(0, SystemPromptMessage(
content=system_message,
))
# add assistant message
if len(agent_scratchpad) > 0 and not self._is_first_iteration:
prompt_messages.append(AssistantPromptMessage(
content=(agent_scratchpad[-1].thought or '') + (agent_scratchpad[-1].action_str or ''),
))
# add user message
if len(agent_scratchpad) > 0 and not self._is_first_iteration:
prompt_messages.append(UserPromptMessage(
content=(agent_scratchpad[-1].observation or 'It seems that no response is available'),
))
self._is_first_iteration = False
return prompt_messages
elif mode == "completion":
# parse agent scratchpad
agent_scratchpad_str = self._convert_scratchpad_list_to_str(agent_scratchpad)
self._is_first_iteration = False
# parse prompt messages
return [UserPromptMessage(
content=first_prompt.replace("{{instruction}}", instruction)
.replace("{{tools}}", tools_str)
.replace("{{tool_names}}", tool_names)
.replace("{{query}}", input)
.replace("{{agent_scratchpad}}", agent_scratchpad_str),
)]
else:
raise ValueError(f"mode {mode} is not supported")
def _jsonify_tool_prompt_messages(self, tools: list[PromptMessageTool]) -> str:
"""
jsonify tool prompt messages
"""
tools = jsonable_encoder(tools)
try:
return json.dumps(tools, ensure_ascii=False)
except json.JSONDecodeError:
return json.dumps(tools)
-71
View File
@@ -1,71 +0,0 @@
import json
from core.agent.cot_agent_runner import CotAgentRunner
from core.model_runtime.entities.message_entities import (
AssistantPromptMessage,
PromptMessage,
SystemPromptMessage,
UserPromptMessage,
)
from core.model_runtime.utils.encoders import jsonable_encoder
class CotChatAgentRunner(CotAgentRunner):
def _organize_system_prompt(self) -> SystemPromptMessage:
"""
Organize system prompt
"""
prompt_entity = self.app_config.agent.prompt
first_prompt = prompt_entity.first_prompt
system_prompt = first_prompt \
.replace("{{instruction}}", self._instruction) \
.replace("{{tools}}", json.dumps(jsonable_encoder(self._prompt_messages_tools))) \
.replace("{{tool_names}}", ', '.join([tool.name for tool in self._prompt_messages_tools]))
return SystemPromptMessage(content=system_prompt)
def _organize_prompt_messages(self) -> list[PromptMessage]:
"""
Organize
"""
# organize system prompt
system_message = self._organize_system_prompt()
# organize historic prompt messages
historic_messages = self._historic_prompt_messages
# organize current assistant messages
agent_scratchpad = self._agent_scratchpad
if not agent_scratchpad:
assistant_messages = []
else:
assistant_message = AssistantPromptMessage(content='')
for unit in agent_scratchpad:
if unit.is_final():
assistant_message.content += f"Final Answer: {unit.agent_response}"
else:
assistant_message.content += f"Thought: {unit.thought}\n\n"
if unit.action_str:
assistant_message.content += f"Action: {unit.action_str}\n\n"
if unit.observation:
assistant_message.content += f"Observation: {unit.observation}\n\n"
assistant_messages = [assistant_message]
# query messages
query_messages = UserPromptMessage(content=self._query)
if assistant_messages:
messages = [
system_message,
*historic_messages,
query_messages,
*assistant_messages,
UserPromptMessage(content='continue')
]
else:
messages = [system_message, *historic_messages, query_messages]
# join all messages
return messages
@@ -1,69 +0,0 @@
import json
from core.agent.cot_agent_runner import CotAgentRunner
from core.model_runtime.entities.message_entities import AssistantPromptMessage, PromptMessage, UserPromptMessage
from core.model_runtime.utils.encoders import jsonable_encoder
class CotCompletionAgentRunner(CotAgentRunner):
def _organize_instruction_prompt(self) -> str:
"""
Organize instruction prompt
"""
prompt_entity = self.app_config.agent.prompt
first_prompt = prompt_entity.first_prompt
system_prompt = first_prompt.replace("{{instruction}}", self._instruction) \
.replace("{{tools}}", json.dumps(jsonable_encoder(self._prompt_messages_tools))) \
.replace("{{tool_names}}", ', '.join([tool.name for tool in self._prompt_messages_tools]))
return system_prompt
def _organize_historic_prompt(self) -> str:
"""
Organize historic prompt
"""
historic_prompt_messages = self._historic_prompt_messages
historic_prompt = ""
for message in historic_prompt_messages:
if isinstance(message, UserPromptMessage):
historic_prompt += f"Question: {message.content}\n\n"
elif isinstance(message, AssistantPromptMessage):
historic_prompt += message.content + "\n\n"
return historic_prompt
def _organize_prompt_messages(self) -> list[PromptMessage]:
"""
Organize prompt messages
"""
# organize system prompt
system_prompt = self._organize_instruction_prompt()
# organize historic prompt messages
historic_prompt = self._organize_historic_prompt()
# organize current assistant messages
agent_scratchpad = self._agent_scratchpad
assistant_prompt = ''
for unit in agent_scratchpad:
if unit.is_final():
assistant_prompt += f"Final Answer: {unit.agent_response}"
else:
assistant_prompt += f"Thought: {unit.thought}\n\n"
if unit.action_str:
assistant_prompt += f"Action: {unit.action_str}\n\n"
if unit.observation:
assistant_prompt += f"Observation: {unit.observation}\n\n"
# query messages
query_prompt = f"Question: {self._query}"
# join all messages
prompt = system_prompt \
.replace("{{historic_messages}}", historic_prompt) \
.replace("{{agent_scratchpad}}", assistant_prompt) \
.replace("{{query}}", query_prompt)
return [UserPromptMessage(content=prompt)]
-17
View File
@@ -34,29 +34,12 @@ class AgentScratchpadUnit(BaseModel):
action_name: str
action_input: Union[dict, str]
def to_dict(self) -> dict:
"""
Convert to dictionary.
"""
return {
'action': self.action_name,
'action_input': self.action_input,
}
agent_response: Optional[str] = None
thought: Optional[str] = None
action_str: Optional[str] = None
observation: Optional[str] = None
action: Optional[Action] = None
def is_final(self) -> bool:
"""
Check if the scratchpad unit is final.
"""
return self.action is None or (
'final' in self.action.action_name.lower() and
'answer' in self.action.action_name.lower()
)
class AgentEntity(BaseModel):
"""
+65 -82
View File
@@ -1,7 +1,6 @@
import json
import logging
from collections.abc import Generator
from copy import deepcopy
from typing import Any, Union
from core.agent.base_agent_runner import BaseAgentRunner
@@ -11,21 +10,21 @@ from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk,
from core.model_runtime.entities.message_entities import (
AssistantPromptMessage,
PromptMessage,
PromptMessageContentType,
PromptMessageTool,
SystemPromptMessage,
TextPromptMessageContent,
ToolPromptMessage,
UserPromptMessage,
)
from core.tools.entities.tool_entities import ToolInvokeMeta
from core.tools.tool_engine import ToolEngine
from models.model import Message
from models.model import Conversation, Message, MessageAgentThought
logger = logging.getLogger(__name__)
class FunctionCallAgentRunner(BaseAgentRunner):
def run(self,
message: Message, query: str, **kwargs: Any
def run(self, conversation: Conversation,
message: Message,
query: str,
) -> Generator[LLMResultChunk, None, None]:
"""
Run FunctionCall agent application
@@ -36,17 +35,40 @@ class FunctionCallAgentRunner(BaseAgentRunner):
prompt_template = app_config.prompt_template.simple_prompt_template or ''
prompt_messages = self.history_prompt_messages
prompt_messages = self._init_system_message(prompt_template, prompt_messages)
prompt_messages = self._organize_user_query(query, prompt_messages)
prompt_messages = self.organize_prompt_messages(
prompt_template=prompt_template,
query=query,
prompt_messages=prompt_messages
)
# convert tools into ModelRuntime Tool format
tool_instances, prompt_messages_tools = self._init_prompt_tools()
prompt_messages_tools: list[PromptMessageTool] = []
tool_instances = {}
for tool in app_config.agent.tools if app_config.agent else []:
try:
prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
except Exception:
# api tool may be deleted
continue
# save tool entity
tool_instances[tool.tool_name] = tool_entity
# save prompt tool
prompt_messages_tools.append(prompt_tool)
# convert dataset tools into ModelRuntime Tool format
for dataset_tool in self.dataset_tools:
prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
# save prompt tool
prompt_messages_tools.append(prompt_tool)
# save tool entity
tool_instances[dataset_tool.identity.name] = dataset_tool
iteration_step = 1
max_iteration_steps = min(app_config.agent.max_iteration, 5) + 1
# continue to run until there is not any tool call
function_call_state = True
agent_thoughts: list[MessageAgentThought] = []
llm_usage = {
'usage': None
}
@@ -185,25 +207,19 @@ class FunctionCallAgentRunner(BaseAgentRunner):
)
)
assistant_message = AssistantPromptMessage(
content='',
tool_calls=[]
)
if tool_calls:
assistant_message.tool_calls=[
AssistantPromptMessage.ToolCall(
prompt_messages.append(AssistantPromptMessage(
content='',
name='',
tool_calls=[AssistantPromptMessage.ToolCall(
id=tool_call[0],
type='function',
function=AssistantPromptMessage.ToolCall.ToolCallFunction(
name=tool_call[1],
arguments=json.dumps(tool_call[2], ensure_ascii=False)
)
) for tool_call in tool_calls
]
else:
assistant_message.content = response
prompt_messages.append(assistant_message)
) for tool_call in tool_calls]
))
# save thought
self.save_agent_thought(
@@ -223,6 +239,12 @@ class FunctionCallAgentRunner(BaseAgentRunner):
final_answer += response + '\n'
# update prompt messages
if response.strip():
prompt_messages.append(AssistantPromptMessage(
content=response,
))
# call tools
tool_responses = []
for tool_call_id, tool_call_name, tool_call_args in tool_calls:
@@ -265,7 +287,9 @@ class FunctionCallAgentRunner(BaseAgentRunner):
}
tool_responses.append(tool_response)
prompt_messages = self._organize_assistant_message(
prompt_messages = self.organize_prompt_messages(
prompt_template=prompt_template,
query=None,
tool_call_id=tool_call_id,
tool_call_name=tool_call_name,
tool_response=tool_response['tool_response'],
@@ -300,8 +324,6 @@ class FunctionCallAgentRunner(BaseAgentRunner):
iteration_step += 1
prompt_messages = self._clear_user_prompt_image_messages(prompt_messages)
self.update_db_variables(self.variables_pool, self.db_variables_pool)
# publish end event
self.queue_manager.publish(QueueMessageEndEvent(llm_result=LLMResult(
@@ -364,68 +386,29 @@ class FunctionCallAgentRunner(BaseAgentRunner):
return tool_calls
def _init_system_message(self, prompt_template: str, prompt_messages: list[PromptMessage] = None) -> list[PromptMessage]:
def organize_prompt_messages(self, prompt_template: str,
query: str = None,
tool_call_id: str = None, tool_call_name: str = None, tool_response: str = None,
prompt_messages: list[PromptMessage] = None
) -> list[PromptMessage]:
"""
Initialize system message
Organize prompt messages
"""
if not prompt_messages and prompt_template:
return [
SystemPromptMessage(content=prompt_template),
]
if prompt_messages and not isinstance(prompt_messages[0], SystemPromptMessage) and prompt_template:
prompt_messages.insert(0, SystemPromptMessage(content=prompt_template))
return prompt_messages
def _organize_user_query(self, query, prompt_messages: list[PromptMessage] = None) -> list[PromptMessage]:
"""
Organize user query
"""
if self.files:
prompt_message_contents = [TextPromptMessageContent(data=query)]
for file_obj in self.files:
prompt_message_contents.append(file_obj.prompt_message_content)
prompt_messages.append(UserPromptMessage(content=prompt_message_contents))
if not prompt_messages:
prompt_messages = [
SystemPromptMessage(content=prompt_template),
UserPromptMessage(content=query),
]
else:
prompt_messages.append(UserPromptMessage(content=query))
return prompt_messages
def _organize_assistant_message(self, tool_call_id: str = None, tool_call_name: str = None, tool_response: str = None,
prompt_messages: list[PromptMessage] = None) -> list[PromptMessage]:
"""
Organize assistant message
"""
prompt_messages = deepcopy(prompt_messages)
if tool_response is not None:
prompt_messages.append(
ToolPromptMessage(
content=tool_response,
tool_call_id=tool_call_id,
name=tool_call_name,
if tool_response:
prompt_messages = prompt_messages.copy()
prompt_messages.append(
ToolPromptMessage(
content=tool_response,
tool_call_id=tool_call_id,
name=tool_call_name,
)
)
)
return prompt_messages
def _clear_user_prompt_image_messages(self, prompt_messages: list[PromptMessage]) -> list[PromptMessage]:
"""
As for now, gpt supports both fc and vision at the first iteration.
We need to remove the image messages from the prompt messages at the first iteration.
"""
prompt_messages = deepcopy(prompt_messages)
for prompt_message in prompt_messages:
if isinstance(prompt_message, UserPromptMessage):
if isinstance(prompt_message.content, list):
prompt_message.content = '\n'.join([
content.data if content.type == PromptMessageContentType.TEXT else
'[image]' if content.type == PromptMessageContentType.IMAGE else
'[file]'
for content in prompt_message.content
])
return prompt_messages
@@ -1,183 +0,0 @@
import json
import re
from collections.abc import Generator
from typing import Union
from core.agent.entities import AgentScratchpadUnit
from core.model_runtime.entities.llm_entities import LLMResultChunk
class CotAgentOutputParser:
@classmethod
def handle_react_stream_output(cls, llm_response: Generator[LLMResultChunk, None, None]) -> \
Generator[Union[str, AgentScratchpadUnit.Action], None, None]:
def parse_action(json_str):
try:
action = json.loads(json_str)
action_name = None
action_input = None
for key, value in action.items():
if 'input' in key.lower():
action_input = value
else:
action_name = value
if action_name is not None and action_input is not None:
return AgentScratchpadUnit.Action(
action_name=action_name,
action_input=action_input,
)
else:
return json_str or ''
except:
return json_str or ''
def extra_json_from_code_block(code_block) -> Generator[Union[dict, str], None, None]:
code_blocks = re.findall(r'```(.*?)```', code_block, re.DOTALL)
if not code_blocks:
return
for block in code_blocks:
json_text = re.sub(r'^[a-zA-Z]+\n', '', block.strip(), flags=re.MULTILINE)
yield parse_action(json_text)
code_block_cache = ''
code_block_delimiter_count = 0
in_code_block = False
json_cache = ''
json_quote_count = 0
in_json = False
got_json = False
action_cache = ''
action_str = 'action:'
action_idx = 0
thought_cache = ''
thought_str = 'thought:'
thought_idx = 0
for response in llm_response:
response = response.delta.message.content
if not isinstance(response, str):
continue
# stream
index = 0
while index < len(response):
steps = 1
delta = response[index:index+steps]
last_character = response[index-1] if index > 0 else ''
if delta == '`':
code_block_cache += delta
code_block_delimiter_count += 1
else:
if not in_code_block:
if code_block_delimiter_count > 0:
yield code_block_cache
code_block_cache = ''
else:
code_block_cache += delta
code_block_delimiter_count = 0
if not in_code_block and not in_json:
if delta.lower() == action_str[action_idx] and action_idx == 0:
if last_character not in ['\n', ' ', '']:
index += steps
yield delta
continue
action_cache += delta
action_idx += 1
if action_idx == len(action_str):
action_cache = ''
action_idx = 0
index += steps
continue
elif delta.lower() == action_str[action_idx] and action_idx > 0:
action_cache += delta
action_idx += 1
if action_idx == len(action_str):
action_cache = ''
action_idx = 0
index += steps
continue
else:
if action_cache:
yield action_cache
action_cache = ''
action_idx = 0
if delta.lower() == thought_str[thought_idx] and thought_idx == 0:
if last_character not in ['\n', ' ', '']:
index += steps
yield delta
continue
thought_cache += delta
thought_idx += 1
if thought_idx == len(thought_str):
thought_cache = ''
thought_idx = 0
index += steps
continue
elif delta.lower() == thought_str[thought_idx] and thought_idx > 0:
thought_cache += delta
thought_idx += 1
if thought_idx == len(thought_str):
thought_cache = ''
thought_idx = 0
index += steps
continue
else:
if thought_cache:
yield thought_cache
thought_cache = ''
thought_idx = 0
if code_block_delimiter_count == 3:
if in_code_block:
yield from extra_json_from_code_block(code_block_cache)
code_block_cache = ''
in_code_block = not in_code_block
code_block_delimiter_count = 0
if not in_code_block:
# handle single json
if delta == '{':
json_quote_count += 1
in_json = True
json_cache += delta
elif delta == '}':
json_cache += delta
if json_quote_count > 0:
json_quote_count -= 1
if json_quote_count == 0:
in_json = False
got_json = True
index += steps
continue
else:
if in_json:
json_cache += delta
if got_json:
got_json = False
yield parse_action(json_cache)
json_cache = ''
json_quote_count = 0
in_json = False
if not in_code_block and not in_json:
yield delta.replace('`', '')
index += steps
if code_block_cache:
yield code_block_cache
if json_cache:
yield parse_action(json_cache)
@@ -1,5 +1,4 @@
import logging
import os
import threading
import uuid
from collections.abc import Generator
@@ -190,8 +189,6 @@ class AdvancedChatAppGenerator(MessageBasedAppGenerator):
logger.exception("Validation Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except (ValueError, InvokeError) as e:
if os.environ.get("DEBUG") and os.environ.get("DEBUG").lower() == 'true':
logger.exception("Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except Exception as e:
logger.exception("Unknown Error when generating")
@@ -98,7 +98,6 @@ class AdvancedChatAppGenerateTaskPipeline(BasedGenerateTaskPipeline, WorkflowCyc
)
self._stream_generate_routes = self._get_stream_generate_routes()
self._conversation_name_generate_thread = None
def process(self) -> Union[ChatbotAppBlockingResponse, Generator[ChatbotAppStreamResponse, None, None]]:
"""
@@ -109,12 +108,6 @@ class AdvancedChatAppGenerateTaskPipeline(BasedGenerateTaskPipeline, WorkflowCyc
db.session.refresh(self._user)
db.session.close()
# start generate conversation name thread
self._conversation_name_generate_thread = self._generate_conversation_name(
self._conversation,
self._application_generate_entity.query
)
generator = self._process_stream_response()
if self._stream:
return self._to_stream_response(generator)
@@ -222,16 +215,16 @@ class AdvancedChatAppGenerateTaskPipeline(BasedGenerateTaskPipeline, WorkflowCyc
elif isinstance(event, QueueStopEvent | QueueWorkflowSucceededEvent | QueueWorkflowFailedEvent):
workflow_run = self._handle_workflow_finished(event)
if workflow_run:
yield self._workflow_finish_to_stream_response(
task_id=self._application_generate_entity.task_id,
workflow_run=workflow_run
)
if workflow_run.status == WorkflowRunStatus.FAILED.value:
err_event = QueueErrorEvent(error=ValueError(f'Run failed: {workflow_run.error}'))
yield self._error_to_stream_response(self._handle_error(err_event, self._message))
break
yield self._workflow_finish_to_stream_response(
task_id=self._application_generate_entity.task_id,
workflow_run=workflow_run
)
if isinstance(event, QueueStopEvent):
# Save message
self._save_message()
@@ -285,9 +278,6 @@ class AdvancedChatAppGenerateTaskPipeline(BasedGenerateTaskPipeline, WorkflowCyc
else:
continue
if self._conversation_name_generate_thread:
self._conversation_name_generate_thread.join()
def _save_message(self) -> None:
"""
Save message.
@@ -1,5 +1,4 @@
import logging
import os
import threading
import uuid
from collections.abc import Generator
@@ -199,8 +198,6 @@ class AgentChatAppGenerator(MessageBasedAppGenerator):
logger.exception("Validation Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except (ValueError, InvokeError) as e:
if os.environ.get("DEBUG") and os.environ.get("DEBUG").lower() == 'true':
logger.exception("Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except Exception as e:
logger.exception("Unknown Error when generating")
+44 -37
View File
@@ -1,8 +1,7 @@
import logging
from typing import cast
from core.agent.cot_chat_agent_runner import CotChatAgentRunner
from core.agent.cot_completion_agent_runner import CotCompletionAgentRunner
from core.agent.cot_agent_runner import CotAgentRunner
from core.agent.entities import AgentEntity
from core.agent.fc_agent_runner import FunctionCallAgentRunner
from core.app.apps.agent_chat.app_config_manager import AgentChatAppConfig
@@ -12,8 +11,8 @@ from core.app.entities.app_invoke_entities import AgentChatAppGenerateEntity, Mo
from core.app.entities.queue_entities import QueueAnnotationReplyEvent
from core.memory.token_buffer_memory import TokenBufferMemory
from core.model_manager import ModelInstance
from core.model_runtime.entities.llm_entities import LLMMode, LLMUsage
from core.model_runtime.entities.model_entities import ModelFeature, ModelPropertyKey
from core.model_runtime.entities.llm_entities import LLMUsage
from core.model_runtime.entities.model_entities import ModelFeature
from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
from core.moderation.base import ModerationException
from core.tools.entities.tool_entities import ToolRuntimeVariablePool
@@ -208,40 +207,48 @@ class AgentChatAppRunner(AppRunner):
# start agent runner
if agent_entity.strategy == AgentEntity.Strategy.CHAIN_OF_THOUGHT:
# check LLM mode
if model_schema.model_properties.get(ModelPropertyKey.MODE) == LLMMode.CHAT.value:
runner_cls = CotChatAgentRunner
elif model_schema.model_properties.get(ModelPropertyKey.MODE) == LLMMode.COMPLETION.value:
runner_cls = CotCompletionAgentRunner
else:
raise ValueError(f"Invalid LLM mode: {model_schema.model_properties.get(ModelPropertyKey.MODE)}")
assistant_cot_runner = CotAgentRunner(
tenant_id=app_config.tenant_id,
application_generate_entity=application_generate_entity,
app_config=app_config,
model_config=application_generate_entity.model_config,
config=agent_entity,
queue_manager=queue_manager,
message=message,
user_id=application_generate_entity.user_id,
memory=memory,
prompt_messages=prompt_message,
variables_pool=tool_variables,
db_variables=tool_conversation_variables,
model_instance=model_instance
)
invoke_result = assistant_cot_runner.run(
conversation=conversation,
message=message,
query=query,
inputs=inputs,
)
elif agent_entity.strategy == AgentEntity.Strategy.FUNCTION_CALLING:
runner_cls = FunctionCallAgentRunner
else:
raise ValueError(f"Invalid agent strategy: {agent_entity.strategy}")
runner = runner_cls(
tenant_id=app_config.tenant_id,
application_generate_entity=application_generate_entity,
conversation=conversation,
app_config=app_config,
model_config=application_generate_entity.model_config,
config=agent_entity,
queue_manager=queue_manager,
message=message,
user_id=application_generate_entity.user_id,
memory=memory,
prompt_messages=prompt_message,
variables_pool=tool_variables,
db_variables=tool_conversation_variables,
model_instance=model_instance
)
invoke_result = runner.run(
message=message,
query=query,
inputs=inputs,
)
assistant_fc_runner = FunctionCallAgentRunner(
tenant_id=app_config.tenant_id,
application_generate_entity=application_generate_entity,
app_config=app_config,
model_config=application_generate_entity.model_config,
config=agent_entity,
queue_manager=queue_manager,
message=message,
user_id=application_generate_entity.user_id,
memory=memory,
prompt_messages=prompt_message,
variables_pool=tool_variables,
db_variables=tool_conversation_variables,
model_instance=model_instance
)
invoke_result = assistant_fc_runner.run(
conversation=conversation,
message=message,
query=query,
)
# handle invoke result
self._handle_invoke_result(
@@ -26,10 +26,7 @@ class AppGenerateResponseConverter(ABC):
else:
def _generate():
for chunk in cls.convert_stream_full_response(response):
if chunk == 'ping':
yield f'event: {chunk}\n\n'
else:
yield f'data: {chunk}\n\n'
yield f'data: {chunk}\n\n'
return _generate()
else:
@@ -38,10 +35,7 @@ class AppGenerateResponseConverter(ABC):
else:
def _generate():
for chunk in cls.convert_stream_simple_response(response):
if chunk == 'ping':
yield f'event: {chunk}\n\n'
else:
yield f'data: {chunk}\n\n'
yield f'data: {chunk}\n\n'
return _generate()
-3
View File
@@ -1,5 +1,4 @@
import logging
import os
import threading
import uuid
from collections.abc import Generator
@@ -196,8 +195,6 @@ class ChatAppGenerator(MessageBasedAppGenerator):
logger.exception("Validation Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except (ValueError, InvokeError) as e:
if os.environ.get("DEBUG") and os.environ.get("DEBUG").lower() == 'true':
logger.exception("Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except Exception as e:
logger.exception("Unknown Error when generating")
-2
View File
@@ -156,8 +156,6 @@ class ChatAppRunner(AppRunner):
dataset_retrieval = DatasetRetrieval()
context = dataset_retrieval.retrieve(
app_id=app_record.id,
user_id=application_generate_entity.user_id,
tenant_id=app_record.tenant_id,
model_config=application_generate_entity.model_config,
config=app_config.dataset,
@@ -1,5 +1,4 @@
import logging
import os
import threading
import uuid
from collections.abc import Generator
@@ -185,8 +184,6 @@ class CompletionAppGenerator(MessageBasedAppGenerator):
logger.exception("Validation Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except (ValueError, InvokeError) as e:
if os.environ.get("DEBUG") and os.environ.get("DEBUG").lower() == 'true':
logger.exception("Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except Exception as e:
logger.exception("Unknown Error when generating")
@@ -116,8 +116,6 @@ class CompletionAppRunner(AppRunner):
dataset_retrieval = DatasetRetrieval()
context = dataset_retrieval.retrieve(
app_id=app_record.id,
user_id=application_generate_entity.user_id,
tenant_id=app_record.tenant_id,
model_config=application_generate_entity.model_config,
config=dataset_config,
@@ -1,5 +1,4 @@
import logging
import os
import threading
import uuid
from collections.abc import Generator
@@ -138,8 +137,6 @@ class WorkflowAppGenerator(BaseAppGenerator):
logger.exception("Validation Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except (ValueError, InvokeError) as e:
if os.environ.get("DEBUG") and os.environ.get("DEBUG").lower() == 'true':
logger.exception("Error when generating")
queue_manager.publish_error(e, PublishFrom.APPLICATION_MANAGER)
except Exception as e:
logger.exception("Unknown Error when generating")
+1 -1
View File
@@ -122,7 +122,7 @@ class MessageEndStreamResponse(StreamResponse):
"""
event: StreamEvent = StreamEvent.MESSAGE_END
id: str
metadata: dict = {}
metadata: Optional[dict] = None
class MessageFileStreamResponse(StreamResponse):
@@ -97,8 +97,6 @@ class EasyUIBasedGenerateTaskPipeline(BasedGenerateTaskPipeline, MessageCycleMan
)
)
self._conversation_name_generate_thread = None
def process(self) -> Union[
ChatbotAppBlockingResponse,
CompletionAppBlockingResponse,
@@ -112,13 +110,6 @@ class EasyUIBasedGenerateTaskPipeline(BasedGenerateTaskPipeline, MessageCycleMan
db.session.refresh(self._message)
db.session.close()
if self._application_generate_entity.app_config.app_mode != AppMode.COMPLETION:
# start generate conversation name thread
self._conversation_name_generate_thread = self._generate_conversation_name(
self._conversation,
self._application_generate_entity.query
)
generator = self._process_stream_response()
if self._stream:
return self._to_stream_response(generator)
@@ -265,9 +256,6 @@ class EasyUIBasedGenerateTaskPipeline(BasedGenerateTaskPipeline, MessageCycleMan
else:
continue
if self._conversation_name_generate_thread:
self._conversation_name_generate_thread.join()
def _save_message(self) -> None:
"""
Save message.
@@ -1,8 +1,5 @@
from threading import Thread
from typing import Optional, Union
from flask import Flask, current_app
from core.app.entities.app_invoke_entities import (
AdvancedChatAppGenerateEntity,
AgentChatAppGenerateEntity,
@@ -22,10 +19,9 @@ from core.app.entities.task_entities import (
MessageReplaceStreamResponse,
MessageStreamResponse,
)
from core.llm_generator.llm_generator import LLMGenerator
from core.tools.tool_file_manager import ToolFileManager
from extensions.ext_database import db
from models.model import AppMode, Conversation, MessageAnnotation, MessageFile
from models.model import MessageAnnotation, MessageFile
from services.annotation_service import AppAnnotationService
@@ -38,59 +34,6 @@ class MessageCycleManage:
]
_task_state: Union[EasyUITaskState, AdvancedChatTaskState]
def _generate_conversation_name(self, conversation: Conversation, query: str) -> Optional[Thread]:
"""
Generate conversation name.
:param conversation: conversation
:param query: query
:return: thread
"""
is_first_message = self._application_generate_entity.conversation_id is None
extras = self._application_generate_entity.extras
auto_generate_conversation_name = extras.get('auto_generate_conversation_name', True)
if auto_generate_conversation_name and is_first_message:
# start generate thread
thread = Thread(target=self._generate_conversation_name_worker, kwargs={
'flask_app': current_app._get_current_object(),
'conversation_id': conversation.id,
'query': query
})
thread.start()
return thread
return None
def _generate_conversation_name_worker(self,
flask_app: Flask,
conversation_id: str,
query: str):
with flask_app.app_context():
# get conversation and message
conversation = (
db.session.query(Conversation)
.filter(Conversation.id == conversation_id)
.first()
)
if conversation.mode != AppMode.COMPLETION.value:
app_model = conversation.app
if not app_model:
return
# generate conversation name
try:
name = LLMGenerator.generate_conversation_name(app_model.tenant_id, query)
conversation.name = name
except:
pass
db.session.merge(conversation)
db.session.commit()
db.session.close()
def _handle_annotation_reply(self, event: QueueAnnotationReplyEvent) -> Optional[MessageAnnotation]:
"""
Handle annotation reply.
@@ -1,6 +1,6 @@
import json
import time
from datetime import datetime, timezone
from datetime import datetime
from typing import Any, Optional, Union, cast
from core.app.entities.app_invoke_entities import AdvancedChatAppGenerateEntity, InvokeFrom, WorkflowAppGenerateEntity
@@ -120,7 +120,7 @@ class WorkflowCycleManage:
workflow_run.elapsed_time = time.perf_counter() - start_at
workflow_run.total_tokens = total_tokens
workflow_run.total_steps = total_steps
workflow_run.finished_at = datetime.now(timezone.utc).replace(tzinfo=None)
workflow_run.finished_at = datetime.utcnow()
db.session.commit()
db.session.refresh(workflow_run)
@@ -149,7 +149,7 @@ class WorkflowCycleManage:
workflow_run.elapsed_time = time.perf_counter() - start_at
workflow_run.total_tokens = total_tokens
workflow_run.total_steps = total_steps
workflow_run.finished_at = datetime.now(timezone.utc).replace(tzinfo=None)
workflow_run.finished_at = datetime.utcnow()
db.session.commit()
db.session.refresh(workflow_run)
@@ -223,7 +223,7 @@ class WorkflowCycleManage:
workflow_node_execution.outputs = json.dumps(outputs) if outputs else None
workflow_node_execution.execution_metadata = json.dumps(jsonable_encoder(execution_metadata)) \
if execution_metadata else None
workflow_node_execution.finished_at = datetime.now(timezone.utc).replace(tzinfo=None)
workflow_node_execution.finished_at = datetime.utcnow()
db.session.commit()
db.session.refresh(workflow_node_execution)
@@ -251,7 +251,7 @@ class WorkflowCycleManage:
workflow_node_execution.status = WorkflowNodeExecutionStatus.FAILED.value
workflow_node_execution.error = error
workflow_node_execution.elapsed_time = time.perf_counter() - start_at
workflow_node_execution.finished_at = datetime.now(timezone.utc).replace(tzinfo=None)
workflow_node_execution.finished_at = datetime.utcnow()
workflow_node_execution.inputs = json.dumps(inputs) if inputs else None
workflow_node_execution.process_data = json.dumps(process_data) if process_data else None
workflow_node_execution.outputs = json.dumps(outputs) if outputs else None
@@ -1,32 +1,12 @@
import os
from typing import Any, Optional, TextIO, Union
from typing import Any, Optional, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.input import print_text
from pydantic import BaseModel
_TEXT_COLOR_MAPPING = {
"blue": "36;1",
"yellow": "33;1",
"pink": "38;5;200",
"green": "32;1",
"red": "31;1",
}
def get_colored_text(text: str, color: str) -> str:
"""Get colored text."""
color_str = _TEXT_COLOR_MAPPING[color]
return f"\u001b[{color_str}m\033[1;3m{text}\u001b[0m"
def print_text(
text: str, color: Optional[str] = None, end: str = "", file: Optional[TextIO] = None
) -> None:
"""Print text with highlighting and no end characters."""
text_to_print = get_colored_text(text, color) if color else text
print(text_to_print, end=end, file=file)
if file:
file.flush() # ensure all printed content are written to file
class DifyAgentCallbackHandler(BaseModel):
class DifyAgentCallbackHandler(BaseCallbackHandler, BaseModel):
"""Callback Handler that prints to std out."""
color: Optional[str] = ''
current_loop = 1
+1 -1
View File
@@ -84,7 +84,7 @@ class DatasetDocumentStore:
if not isinstance(doc, Document):
raise ValueError("doc must be a Document")
segment_document = self.get_document_segment(doc_id=doc.metadata['doc_id'])
segment_document = self.get_document(doc_id=doc.metadata['doc_id'], raise_error=False)
# NOTE: doc could already exist in the store, but we overwrite it
if not allow_update and segment_document:
+10 -17
View File
@@ -41,8 +41,7 @@ class CacheEmbedding(Embeddings):
embedding_queue_embeddings = []
try:
model_type_instance = cast(TextEmbeddingModel, self._model_instance.model_type_instance)
model_schema = model_type_instance.get_model_schema(self._model_instance.model,
self._model_instance.credentials)
model_schema = model_type_instance.get_model_schema(self._model_instance.model, self._model_instance.credentials)
max_chunks = model_schema.model_properties[ModelPropertyKey.MAX_CHUNKS] \
if model_schema and ModelPropertyKey.MAX_CHUNKS in model_schema.model_properties else 1
for i in range(0, len(embedding_queue_texts), max_chunks):
@@ -61,21 +60,15 @@ class CacheEmbedding(Embeddings):
db.session.rollback()
except Exception as e:
logging.exception('Failed transform embedding: ', e)
cache_embeddings = []
try:
for i, embedding in zip(embedding_queue_indices, embedding_queue_embeddings):
text_embeddings[i] = embedding
hash = helper.generate_text_hash(texts[i])
if hash not in cache_embeddings:
embedding_cache = Embedding(model_name=self._model_instance.model,
hash=hash,
provider_name=self._model_instance.provider)
embedding_cache.set_embedding(embedding)
db.session.add(embedding_cache)
cache_embeddings.append(hash)
db.session.commit()
except IntegrityError:
db.session.rollback()
for i, embedding in zip(embedding_queue_indices, embedding_queue_embeddings):
text_embeddings[i] = embedding
hash = helper.generate_text_hash(texts[i])
embedding_cache = Embedding(model_name=self._model_instance.model,
hash=hash,
provider_name=self._model_instance.provider)
embedding_cache.set_embedding(embedding)
db.session.add(embedding_cache)
db.session.commit()
except Exception as ex:
db.session.rollback()
logger.error('Failed to embed documents: ', ex)
+107 -1
View File
@@ -1,8 +1,19 @@
import enum
from typing import Any
from typing import Any, cast
from langchain.schema import AIMessage, BaseMessage, FunctionMessage, HumanMessage, SystemMessage
from pydantic import BaseModel
from core.model_runtime.entities.message_entities import (
AssistantPromptMessage,
ImagePromptMessageContent,
PromptMessage,
SystemPromptMessage,
TextPromptMessageContent,
ToolPromptMessage,
UserPromptMessage,
)
class PromptMessageFileType(enum.Enum):
IMAGE = 'image'
@@ -27,3 +38,98 @@ class ImagePromptMessageFile(PromptMessageFile):
type: PromptMessageFileType = PromptMessageFileType.IMAGE
detail: DETAIL = DETAIL.LOW
class LCHumanMessageWithFiles(HumanMessage):
# content: Union[str, list[Union[str, Dict]]]
content: str
files: list[PromptMessageFile]
def lc_messages_to_prompt_messages(messages: list[BaseMessage]) -> list[PromptMessage]:
prompt_messages = []
for message in messages:
if isinstance(message, HumanMessage):
if isinstance(message, LCHumanMessageWithFiles):
file_prompt_message_contents = []
for file in message.files:
if file.type == PromptMessageFileType.IMAGE:
file = cast(ImagePromptMessageFile, file)
file_prompt_message_contents.append(ImagePromptMessageContent(
data=file.data,
detail=ImagePromptMessageContent.DETAIL.HIGH
if file.detail.value == "high" else ImagePromptMessageContent.DETAIL.LOW
))
prompt_message_contents = [TextPromptMessageContent(data=message.content)]
prompt_message_contents.extend(file_prompt_message_contents)
prompt_messages.append(UserPromptMessage(content=prompt_message_contents))
else:
prompt_messages.append(UserPromptMessage(content=message.content))
elif isinstance(message, AIMessage):
message_kwargs = {
'content': message.content
}
if 'function_call' in message.additional_kwargs:
message_kwargs['tool_calls'] = [
AssistantPromptMessage.ToolCall(
id=message.additional_kwargs['function_call']['id'],
type='function',
function=AssistantPromptMessage.ToolCall.ToolCallFunction(
name=message.additional_kwargs['function_call']['name'],
arguments=message.additional_kwargs['function_call']['arguments']
)
)
]
prompt_messages.append(AssistantPromptMessage(**message_kwargs))
elif isinstance(message, SystemMessage):
prompt_messages.append(SystemPromptMessage(content=message.content))
elif isinstance(message, FunctionMessage):
prompt_messages.append(ToolPromptMessage(content=message.content, tool_call_id=message.name))
return prompt_messages
def prompt_messages_to_lc_messages(prompt_messages: list[PromptMessage]) -> list[BaseMessage]:
messages = []
for prompt_message in prompt_messages:
if isinstance(prompt_message, UserPromptMessage):
if isinstance(prompt_message.content, str):
messages.append(HumanMessage(content=prompt_message.content))
else:
message_contents = []
for content in prompt_message.content:
if isinstance(content, TextPromptMessageContent):
message_contents.append(content.data)
elif isinstance(content, ImagePromptMessageContent):
message_contents.append({
'type': 'image',
'data': content.data,
'detail': content.detail.value
})
messages.append(HumanMessage(content=message_contents))
elif isinstance(prompt_message, AssistantPromptMessage):
message_kwargs = {
'content': prompt_message.content
}
if prompt_message.tool_calls:
message_kwargs['additional_kwargs'] = {
'function_call': {
'id': prompt_message.tool_calls[0].id,
'name': prompt_message.tool_calls[0].function.name,
'arguments': prompt_message.tool_calls[0].function.arguments
}
}
messages.append(AIMessage(**message_kwargs))
elif isinstance(prompt_message, SystemPromptMessage):
messages.append(SystemMessage(content=prompt_message.content))
elif isinstance(prompt_message, ToolPromptMessage):
messages.append(FunctionMessage(name=prompt_message.tool_call_id, content=prompt_message.content))
return messages
+2 -2
View File
@@ -203,7 +203,7 @@ class ProviderConfiguration(BaseModel):
if provider_record:
provider_record.encrypted_config = json.dumps(credentials)
provider_record.is_valid = True
provider_record.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
provider_record.updated_at = datetime.datetime.utcnow()
db.session.commit()
else:
provider_record = Provider(
@@ -351,7 +351,7 @@ class ProviderConfiguration(BaseModel):
if provider_model_record:
provider_model_record.encrypted_config = json.dumps(credentials)
provider_model_record.is_valid = True
provider_model_record.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
provider_model_record.updated_at = datetime.datetime.utcnow()
db.session.commit()
else:
provider_model_record = ProviderModel(
+18 -38
View File
@@ -1,17 +1,17 @@
from os import environ
from typing import Literal, Optional
from httpx import post
from pydantic import BaseModel
from yarl import URL
from config import get_env
from core.helper.code_executor.javascript_transformer import NodeJsTemplateTransformer
from core.helper.code_executor.jina2_transformer import Jinja2TemplateTransformer
from core.helper.code_executor.python_transformer import PythonTemplateTransformer
# Code Executor
CODE_EXECUTION_ENDPOINT = get_env('CODE_EXECUTION_ENDPOINT')
CODE_EXECUTION_API_KEY = get_env('CODE_EXECUTION_API_KEY')
CODE_EXECUTION_ENDPOINT = environ.get('CODE_EXECUTION_ENDPOINT', '')
CODE_EXECUTION_API_KEY = environ.get('CODE_EXECUTION_API_KEY', '')
CODE_EXECUTION_TIMEOUT= (10, 60)
@@ -27,28 +27,36 @@ class CodeExecutionResponse(BaseModel):
message: str
data: Data
class CodeExecutor:
@classmethod
def execute_code(cls, language: Literal['python3', 'javascript', 'jinja2'], preload: str, code: str) -> str:
def execute_code(cls, language: Literal['python3', 'javascript', 'jinja2'], code: str, inputs: dict) -> dict:
"""
Execute code
:param language: code language
:param code: code
:param inputs: inputs
:return:
"""
url = URL(CODE_EXECUTION_ENDPOINT) / 'v1' / 'sandbox' / 'run'
template_transformer = None
if language == 'python3':
template_transformer = PythonTemplateTransformer
elif language == 'jinja2':
template_transformer = Jinja2TemplateTransformer
elif language == 'javascript':
template_transformer = NodeJsTemplateTransformer
else:
raise CodeExecutionException('Unsupported language')
runner = template_transformer.transform_caller(code, inputs)
url = URL(CODE_EXECUTION_ENDPOINT) / 'v1' / 'sandbox' / 'run'
headers = {
'X-Api-Key': CODE_EXECUTION_API_KEY
}
data = {
'language': 'python3' if language == 'jinja2' else
'nodejs' if language == 'javascript' else
'python3' if language == 'python3' else None,
'code': code,
'preload': preload
'code': runner,
}
try:
@@ -75,32 +83,4 @@ class CodeExecutor:
if response.data.error:
raise CodeExecutionException(response.data.error)
return response.data.stdout
@classmethod
def execute_workflow_code_template(cls, language: Literal['python3', 'javascript', 'jinja2'], code: str, inputs: dict) -> dict:
"""
Execute code
:param language: code language
:param code: code
:param inputs: inputs
:return:
"""
template_transformer = None
if language == 'python3':
template_transformer = PythonTemplateTransformer
elif language == 'jinja2':
template_transformer = Jinja2TemplateTransformer
elif language == 'javascript':
template_transformer = NodeJsTemplateTransformer
else:
raise CodeExecutionException('Unsupported language')
runner, preload = template_transformer.transform_caller(code, inputs)
try:
response = cls.execute_code(language, preload, runner)
except CodeExecutionException as e:
raise e
return template_transformer.transform_response(response)
return template_transformer.transform_response(response.data.stdout)
@@ -18,27 +18,26 @@ result = `<<RESULT>>${output}<<RESULT>>`
console.log(result)
"""
NODEJS_PRELOAD = """"""
class NodeJsTemplateTransformer(TemplateTransformer):
@classmethod
def transform_caller(cls, code: str, inputs: dict) -> tuple[str, str]:
def transform_caller(cls, code: str, inputs: dict) -> str:
"""
Transform code to python runner
:param code: code
:param inputs: inputs
:return:
"""
# transform inputs to json string
inputs_str = json.dumps(inputs, indent=4, ensure_ascii=False)
inputs_str = json.dumps(inputs, indent=4)
# replace code and inputs
runner = NODEJS_RUNNER.replace('{{code}}', code)
runner = runner.replace('{{inputs}}', inputs_str)
return runner, NODEJS_PRELOAD
return runner
@classmethod
def transform_response(cls, response: str) -> dict:
"""
@@ -20,39 +20,9 @@ print(result)
"""
JINJA2_PRELOAD_TEMPLATE = """{% set fruits = ['Apple'] %}
{{ 'a' }}
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
{% if fruits|length > 1 %}
1
{% endif %}
{% for i in range(5) %}
{% if i == 3 %}{{ i }}{% else %}{% endif %}
{% endfor %}
{% for i in range(3) %}
{{ i + 1 }}
{% endfor %}
{% macro say_hello() %}a{{ 'b' }}{% endmacro %}
{{ s }}{{ say_hello() }}"""
JINJA2_PRELOAD = f"""
import jinja2
def _jinja2_preload_():
# prepare jinja2 environment, load template and render before to avoid sandbox issue
template = jinja2.Template('''{JINJA2_PRELOAD_TEMPLATE}''')
template.render(s='a')
if __name__ == '__main__':
_jinja2_preload_()
"""
class Jinja2TemplateTransformer(TemplateTransformer):
@classmethod
def transform_caller(cls, code: str, inputs: dict) -> tuple[str, str]:
def transform_caller(cls, code: str, inputs: dict) -> str:
"""
Transform code to python runner
:param code: code
@@ -62,10 +32,10 @@ class Jinja2TemplateTransformer(TemplateTransformer):
# transform jinja2 template to python code
runner = PYTHON_RUNNER.replace('{{code}}', code)
runner = runner.replace('{{inputs}}', json.dumps(inputs, indent=4, ensure_ascii=False))
return runner, JINJA2_PRELOAD
runner = runner.replace('{{inputs}}', json.dumps(inputs, indent=4))
return runner
@classmethod
def transform_response(cls, response: str) -> dict:
"""
@@ -81,4 +51,4 @@ class Jinja2TemplateTransformer(TemplateTransformer):
return {
'result': result
}
}
@@ -20,32 +20,10 @@ result = f'''<<RESULT>>
print(result)
"""
PYTHON_PRELOAD = """
# prepare general imports
import json
import datetime
import math
import random
import re
import string
import sys
import time
import traceback
import uuid
import os
import base64
import hashlib
import hmac
import binascii
import collections
import functools
import operator
import itertools
"""
class PythonTemplateTransformer(TemplateTransformer):
@classmethod
def transform_caller(cls, code: str, inputs: dict) -> tuple[str, str]:
def transform_caller(cls, code: str, inputs: dict) -> str:
"""
Transform code to python runner
:param code: code
@@ -54,13 +32,13 @@ class PythonTemplateTransformer(TemplateTransformer):
"""
# transform inputs to json string
inputs_str = json.dumps(inputs, indent=4, ensure_ascii=False)
inputs_str = json.dumps(inputs, indent=4)
# replace code and inputs
runner = PYTHON_RUNNER.replace('{{code}}', code)
runner = runner.replace('{{inputs}}', inputs_str)
return runner, PYTHON_PRELOAD
return runner
@classmethod
def transform_response(cls, response: str) -> dict:
@@ -4,12 +4,12 @@ from abc import ABC, abstractmethod
class TemplateTransformer(ABC):
@classmethod
@abstractmethod
def transform_caller(cls, code: str, inputs: dict) -> tuple[str, str]:
def transform_caller(cls, code: str, inputs: dict) -> str:
"""
Transform code to python runner
:param code: code
:param inputs: inputs
:return: runner, preload
:return:
"""
pass
+24 -53
View File
@@ -19,7 +19,6 @@ from core.model_manager import ModelInstance, ModelManager
from core.model_runtime.entities.model_entities import ModelType, PriceType
from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
from core.model_runtime.model_providers.__base.text_embedding_model import TextEmbeddingModel
from core.rag.datasource.keyword.keyword_factory import Keyword
from core.rag.extractor.entity.extract_setting import ExtractSetting
from core.rag.index_processor.index_processor_base import BaseIndexProcessor
from core.rag.index_processor.index_processor_factory import IndexProcessorFactory
@@ -81,7 +80,7 @@ class IndexingRunner:
except ProviderTokenNotInitError as e:
dataset_document.indexing_status = 'error'
dataset_document.error = str(e.description)
dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
dataset_document.stopped_at = datetime.datetime.utcnow()
db.session.commit()
except ObjectDeletedError:
logging.warning('Document deleted, document id: {}'.format(dataset_document.id))
@@ -89,7 +88,7 @@ class IndexingRunner:
logging.exception("consume document failed")
dataset_document.indexing_status = 'error'
dataset_document.error = str(e)
dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
dataset_document.stopped_at = datetime.datetime.utcnow()
db.session.commit()
def run_in_splitting_status(self, dataset_document: DatasetDocument):
@@ -140,13 +139,13 @@ class IndexingRunner:
except ProviderTokenNotInitError as e:
dataset_document.indexing_status = 'error'
dataset_document.error = str(e.description)
dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
dataset_document.stopped_at = datetime.datetime.utcnow()
db.session.commit()
except Exception as e:
logging.exception("consume document failed")
dataset_document.indexing_status = 'error'
dataset_document.error = str(e)
dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
dataset_document.stopped_at = datetime.datetime.utcnow()
db.session.commit()
def run_in_indexing_status(self, dataset_document: DatasetDocument):
@@ -202,13 +201,13 @@ class IndexingRunner:
except ProviderTokenNotInitError as e:
dataset_document.indexing_status = 'error'
dataset_document.error = str(e.description)
dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
dataset_document.stopped_at = datetime.datetime.utcnow()
db.session.commit()
except Exception as e:
logging.exception("consume document failed")
dataset_document.indexing_status = 'error'
dataset_document.error = str(e)
dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
dataset_document.stopped_at = datetime.datetime.utcnow()
db.session.commit()
def indexing_estimate(self, tenant_id: str, extract_settings: list[ExtractSetting], tmp_processing_rule: dict,
@@ -382,7 +381,7 @@ class IndexingRunner:
after_indexing_status="splitting",
extra_update_params={
DatasetDocument.word_count: sum([len(text_doc.page_content) for text_doc in text_docs]),
DatasetDocument.parsing_completed_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
DatasetDocument.parsing_completed_at: datetime.datetime.utcnow()
}
)
@@ -467,7 +466,7 @@ class IndexingRunner:
doc_store.add_documents(documents)
# update document status to indexing
cur_time = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
cur_time = datetime.datetime.utcnow()
self._update_document_index_status(
document_id=dataset_document.id,
after_indexing_status="indexing",
@@ -482,7 +481,7 @@ class IndexingRunner:
dataset_document_id=dataset_document.id,
update_params={
DocumentSegment.status: "indexing",
DocumentSegment.indexing_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
DocumentSegment.indexing_at: datetime.datetime.utcnow()
}
)
@@ -658,25 +657,18 @@ class IndexingRunner:
if embedding_model_instance:
embedding_model_type_instance = embedding_model_instance.model_type_instance
embedding_model_type_instance = cast(TextEmbeddingModel, embedding_model_type_instance)
# create keyword index
create_keyword_thread = threading.Thread(target=self._process_keyword_index,
args=(current_app._get_current_object(),
dataset.id, dataset_document.id, documents))
create_keyword_thread.start()
if dataset.indexing_technique == 'high_quality':
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for i in range(0, len(documents), chunk_size):
chunk_documents = documents[i:i + chunk_size]
futures.append(executor.submit(self._process_chunk, current_app._get_current_object(), index_processor,
chunk_documents, dataset,
dataset_document, embedding_model_instance,
embedding_model_type_instance))
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for i in range(0, len(documents), chunk_size):
chunk_documents = documents[i:i + chunk_size]
futures.append(executor.submit(self._process_chunk, current_app._get_current_object(), index_processor,
chunk_documents, dataset,
dataset_document, embedding_model_instance,
embedding_model_type_instance))
for future in futures:
tokens += future.result()
for future in futures:
tokens += future.result()
create_keyword_thread.join()
indexing_end_at = time.perf_counter()
# update document status to completed
@@ -685,32 +677,11 @@ class IndexingRunner:
after_indexing_status="completed",
extra_update_params={
DatasetDocument.tokens: tokens,
DatasetDocument.completed_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
DatasetDocument.completed_at: datetime.datetime.utcnow(),
DatasetDocument.indexing_latency: indexing_end_at - indexing_start_at,
}
)
def _process_keyword_index(self, flask_app, dataset_id, document_id, documents):
with flask_app.app_context():
dataset = Dataset.query.filter_by(id=dataset_id).first()
if not dataset:
raise ValueError("no dataset found")
keyword = Keyword(dataset)
keyword.create(documents)
if dataset.indexing_technique != 'high_quality':
document_ids = [document.metadata['doc_id'] for document in documents]
db.session.query(DocumentSegment).filter(
DocumentSegment.document_id == document_id,
DocumentSegment.index_node_id.in_(document_ids),
DocumentSegment.status == "indexing"
).update({
DocumentSegment.status: "completed",
DocumentSegment.enabled: True,
DocumentSegment.completed_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
})
db.session.commit()
def _process_chunk(self, flask_app, index_processor, chunk_documents, dataset, dataset_document,
embedding_model_instance, embedding_model_type_instance):
with flask_app.app_context():
@@ -729,7 +700,7 @@ class IndexingRunner:
)
# load index
index_processor.load(dataset, chunk_documents, with_keywords=False)
index_processor.load(dataset, chunk_documents)
document_ids = [document.metadata['doc_id'] for document in chunk_documents]
db.session.query(DocumentSegment).filter(
@@ -739,7 +710,7 @@ class IndexingRunner:
).update({
DocumentSegment.status: "completed",
DocumentSegment.enabled: True,
DocumentSegment.completed_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
DocumentSegment.completed_at: datetime.datetime.utcnow()
})
db.session.commit()
@@ -838,7 +809,7 @@ class IndexingRunner:
doc_store.add_documents(documents)
# update document status to indexing
cur_time = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
cur_time = datetime.datetime.utcnow()
self._update_document_index_status(
document_id=dataset_document.id,
after_indexing_status="indexing",
@@ -853,7 +824,7 @@ class IndexingRunner:
dataset_document_id=dataset_document.id,
update_params={
DocumentSegment.status: "indexing",
DocumentSegment.indexing_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
DocumentSegment.indexing_at: datetime.datetime.utcnow()
}
)
pass
+2 -2
View File
@@ -1,7 +1,8 @@
import json
import logging
from core.llm_generator.output_parser.errors import OutputParserException
from langchain.schema import OutputParserException
from core.llm_generator.output_parser.rule_config_generator import RuleConfigGeneratorOutputParser
from core.llm_generator.output_parser.suggested_questions_after_answer import SuggestedQuestionsAfterAnswerOutputParser
from core.llm_generator.prompts import CONVERSATION_TITLE_PROMPT, GENERATOR_QA_PROMPT
@@ -165,7 +166,6 @@ class LLMGenerator:
response = model_instance.invoke_llm(
prompt_messages=prompt_messages,
model_parameters={
'temperature': 0.01,
"max_tokens": 2000
},
stream=False
@@ -1,2 +0,0 @@
class OutputParserException(Exception):
pass
@@ -1,11 +1,12 @@
from typing import Any
from core.llm_generator.output_parser.errors import OutputParserException
from langchain.schema import BaseOutputParser, OutputParserException
from core.llm_generator.prompts import RULE_CONFIG_GENERATE_TEMPLATE
from libs.json_in_md_parser import parse_and_check_json_markdown
class RuleConfigGeneratorOutputParser:
class RuleConfigGeneratorOutputParser(BaseOutputParser):
def get_format_instructions(self) -> str:
return RULE_CONFIG_GENERATE_TEMPLATE
@@ -2,10 +2,12 @@ import json
import re
from typing import Any
from langchain.schema import BaseOutputParser
from core.llm_generator.prompts import SUGGESTED_QUESTIONS_AFTER_ANSWER_INSTRUCTION_PROMPT
class SuggestedQuestionsAfterAnswerOutputParser:
class SuggestedQuestionsAfterAnswerOutputParser(BaseOutputParser):
def get_format_instructions(self) -> str:
return SUGGESTED_QUESTIONS_AFTER_ANSWER_INSTRUCTION_PROMPT
+4 -6
View File
@@ -69,15 +69,13 @@ SUGGESTED_QUESTIONS_AFTER_ANSWER_INSTRUCTION_PROMPT = (
)
GENERATOR_QA_PROMPT = (
'<Task> The user will send a long text. Generate a Question and Answer pairs only using the knowledge in the long text. Please think step by step.'
'The user will send a long text. Please think step by step.'
'Step 1: Understand and summarize the main content of this text.\n'
'Step 2: What key information or concepts are mentioned in this text?\n'
'Step 3: Decompose or combine multiple pieces of information and concepts.\n'
'Step 4: Generate questions and answers based on these key information and concepts.\n'
'<Constraints> The questions should be clear and detailed, and the answers should be detailed and complete. '
'You must answer in {language}, in a style that is clear and detailed in {language}. No language other than {language} should be used. \n'
'<Format> Use the following format: Q1:\nA1:\nQ2:\nA2:...\n'
'<QA Pairs>'
'Step 4: Generate 20 questions and answers based on these key information and concepts.'
'The questions should be clear and detailed, and the answers should be detailed and complete.\n'
"Answer MUST according to the the language:{language} and in the following format: Q1:\nA1:\nQ2:\nA2:...\n"
)
RULE_CONFIG_GENERATE_TEMPLATE = """Given MY INTENDED AUDIENCES and HOPING TO SOLVE using a language model, please select \
+2 -13
View File
@@ -3,7 +3,6 @@ from core.file.message_file_parser import MessageFileParser
from core.model_manager import ModelInstance
from core.model_runtime.entities.message_entities import (
AssistantPromptMessage,
ImagePromptMessageContent,
PromptMessage,
PromptMessageRole,
TextPromptMessageContent,
@@ -125,17 +124,7 @@ class TokenBufferMemory:
else:
continue
if isinstance(m.content, list):
inner_msg = ""
for content in m.content:
if isinstance(content, TextPromptMessageContent):
inner_msg += f"{content.data}\n"
elif isinstance(content, ImagePromptMessageContent):
inner_msg += "[image]\n"
string_messages.append(f"{role}: {inner_msg.strip()}")
else:
message = f"{role}: {m.content}"
string_messages.append(message)
message = f"{role}: {m.content}"
string_messages.append(message)
return "\n".join(string_messages)
@@ -88,14 +88,6 @@ class PromptMessage(ABC, BaseModel):
content: Optional[str | list[PromptMessageContent]] = None
name: Optional[str] = None
def is_empty(self) -> bool:
"""
Check if prompt message is empty.
:return: True if prompt message is empty, False otherwise
"""
return not self.content
class UserPromptMessage(PromptMessage):
"""
@@ -126,16 +118,6 @@ class AssistantPromptMessage(PromptMessage):
role: PromptMessageRole = PromptMessageRole.ASSISTANT
tool_calls: list[ToolCall] = []
def is_empty(self) -> bool:
"""
Check if prompt message is empty.
:return: True if prompt message is empty, False otherwise
"""
if not super().is_empty() and not self.tool_calls:
return False
return True
class SystemPromptMessage(PromptMessage):
"""
@@ -150,14 +132,3 @@ class ToolPromptMessage(PromptMessage):
"""
role: PromptMessageRole = PromptMessageRole.TOOL
tool_call_id: str
def is_empty(self) -> bool:
"""
Check if prompt message is empty.
:return: True if prompt message is empty, False otherwise
"""
if not super().is_empty() and not self.tool_call_id:
return False
return True
@@ -5,7 +5,6 @@ model_type: llm
features:
- agent-thought
- vision
- tool-call
model_properties:
mode: chat
context_size: 200000
@@ -5,7 +5,6 @@ model_type: llm
features:
- agent-thought
- vision
- tool-call
model_properties:
mode: chat
context_size: 200000
@@ -5,7 +5,6 @@ model_type: llm
features:
- agent-thought
- vision
- tool-call
model_properties:
mode: chat
context_size: 200000
@@ -1,5 +1,4 @@
import base64
import json
import mimetypes
from collections.abc import Generator
from typing import Optional, Union, cast
@@ -16,7 +15,6 @@ from anthropic.types import (
MessageStreamEvent,
completion_create_params,
)
from anthropic.types.beta.tools import ToolsBetaMessage
from httpx import Timeout
from core.model_runtime.callbacks.base_callback import Callback
@@ -29,7 +27,6 @@ from core.model_runtime.entities.message_entities import (
PromptMessageTool,
SystemPromptMessage,
TextPromptMessageContent,
ToolPromptMessage,
UserPromptMessage,
)
from core.model_runtime.errors.invoke import (
@@ -73,11 +70,10 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
:return: full response or stream response chunk generator result
"""
# invoke model
return self._chat_generate(model, credentials, prompt_messages, model_parameters, tools, stop, stream, user)
return self._chat_generate(model, credentials, prompt_messages, model_parameters, stop, stream, user)
def _chat_generate(self, model: str, credentials: dict,
prompt_messages: list[PromptMessage], model_parameters: dict,
tools: Optional[list[PromptMessageTool]] = None, stop: Optional[list[str]] = None,
prompt_messages: list[PromptMessage], model_parameters: dict, stop: Optional[list[str]] = None,
stream: bool = True, user: Optional[str] = None) -> Union[LLMResult, Generator]:
"""
Invoke llm chat model
@@ -113,26 +109,14 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
if system:
extra_model_kwargs['system'] = system
if tools:
extra_model_kwargs['tools'] = [
self._transform_tool_prompt(tool) for tool in tools
]
response = client.beta.tools.messages.create(
model=model,
messages=prompt_message_dicts,
stream=stream,
**model_parameters,
**extra_model_kwargs
)
else:
# chat model
response = client.messages.create(
model=model,
messages=prompt_message_dicts,
stream=stream,
**model_parameters,
**extra_model_kwargs
)
# chat model
response = client.messages.create(
model=model,
messages=prompt_message_dicts,
stream=stream,
**model_parameters,
**extra_model_kwargs
)
if stream:
return self._handle_chat_generate_stream_response(model, credentials, response, prompt_messages)
@@ -164,13 +148,6 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
return self._invoke(model, credentials, prompt_messages, model_parameters, tools, stop, stream, user)
def _transform_tool_prompt(self, tool: PromptMessageTool) -> dict:
return {
'name': tool.name,
'description': tool.description,
'input_schema': tool.parameters
}
def _transform_chat_json_prompts(self, model: str, credentials: dict,
prompt_messages: list[PromptMessage], model_parameters: dict,
tools: list[PromptMessageTool] | None = None, stop: list[str] | None = None,
@@ -216,18 +193,7 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
prompt = self._convert_messages_to_prompt_anthropic(prompt_messages)
client = Anthropic(api_key="")
tokens = client.count_tokens(prompt)
tool_call_inner_prompts_tokens_map = {
'claude-3-opus-20240229': 395,
'claude-3-haiku-20240307': 264,
'claude-3-sonnet-20240229': 159
}
if model in tool_call_inner_prompts_tokens_map and tools:
tokens += tool_call_inner_prompts_tokens_map[model]
return tokens
return client.count_tokens(prompt)
def validate_credentials(self, model: str, credentials: dict) -> None:
"""
@@ -253,7 +219,7 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
except Exception as ex:
raise CredentialsValidateFailedError(str(ex))
def _handle_chat_generate_response(self, model: str, credentials: dict, response: Union[Message, ToolsBetaMessage],
def _handle_chat_generate_response(self, model: str, credentials: dict, response: Message,
prompt_messages: list[PromptMessage]) -> LLMResult:
"""
Handle llm chat response
@@ -266,24 +232,9 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
"""
# transform assistant message to prompt message
assistant_prompt_message = AssistantPromptMessage(
content='',
tool_calls=[]
content=response.content[0].text
)
for content in response.content:
if content.type == 'text':
assistant_prompt_message.content += content.text
elif content.type == 'tool_use':
tool_call = AssistantPromptMessage.ToolCall(
id=content.id,
type='function',
function=AssistantPromptMessage.ToolCall.ToolCallFunction(
name=content.name,
arguments=json.dumps(content.input)
)
)
assistant_prompt_message.tool_calls.append(tool_call)
# calculate num tokens
if response.usage:
# transform usage
@@ -405,90 +356,69 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
prompt_message_dicts = []
for message in prompt_messages:
if not isinstance(message, SystemPromptMessage):
if isinstance(message, UserPromptMessage):
message = cast(UserPromptMessage, message)
if isinstance(message.content, str):
message_dict = {"role": "user", "content": message.content}
prompt_message_dicts.append(message_dict)
else:
sub_messages = []
for message_content in message.content:
if message_content.type == PromptMessageContentType.TEXT:
message_content = cast(TextPromptMessageContent, message_content)
sub_message_dict = {
"type": "text",
"text": message_content.data
}
sub_messages.append(sub_message_dict)
elif message_content.type == PromptMessageContentType.IMAGE:
message_content = cast(ImagePromptMessageContent, message_content)
if not message_content.data.startswith("data:"):
# fetch image data from url
try:
image_content = requests.get(message_content.data).content
mime_type, _ = mimetypes.guess_type(message_content.data)
base64_data = base64.b64encode(image_content).decode('utf-8')
except Exception as ex:
raise ValueError(f"Failed to fetch image data from url {message_content.data}, {ex}")
else:
data_split = message_content.data.split(";base64,")
mime_type = data_split[0].replace("data:", "")
base64_data = data_split[1]
if mime_type not in ["image/jpeg", "image/png", "image/gif", "image/webp"]:
raise ValueError(f"Unsupported image type {mime_type}, "
f"only support image/jpeg, image/png, image/gif, and image/webp")
sub_message_dict = {
"type": "image",
"source": {
"type": "base64",
"media_type": mime_type,
"data": base64_data
}
}
sub_messages.append(sub_message_dict)
prompt_message_dicts.append({"role": "user", "content": sub_messages})
elif isinstance(message, AssistantPromptMessage):
message = cast(AssistantPromptMessage, message)
content = []
if message.tool_calls:
for tool_call in message.tool_calls:
content.append({
"type": "tool_use",
"id": tool_call.id,
"name": tool_call.function.name,
"input": json.loads(tool_call.function.arguments)
})
if message.content:
content.append({
"type": "text",
"text": message.content
})
if prompt_message_dicts[-1]["role"] == "assistant":
prompt_message_dicts[-1]["content"].extend(content)
else:
prompt_message_dicts.append({
"role": "assistant",
"content": content
})
elif isinstance(message, ToolPromptMessage):
message = cast(ToolPromptMessage, message)
message_dict = {
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": message.tool_call_id,
"content": message.content
}]
}
prompt_message_dicts.append(message_dict)
else:
raise ValueError(f"Got unknown type {message}")
prompt_message_dicts.append(self._convert_prompt_message_to_dict(message))
return system, prompt_message_dicts
def _convert_prompt_message_to_dict(self, message: PromptMessage) -> dict:
"""
Convert PromptMessage to dict
"""
if isinstance(message, UserPromptMessage):
message = cast(UserPromptMessage, message)
if isinstance(message.content, str):
message_dict = {"role": "user", "content": message.content}
else:
sub_messages = []
for message_content in message.content:
if message_content.type == PromptMessageContentType.TEXT:
message_content = cast(TextPromptMessageContent, message_content)
sub_message_dict = {
"type": "text",
"text": message_content.data
}
sub_messages.append(sub_message_dict)
elif message_content.type == PromptMessageContentType.IMAGE:
message_content = cast(ImagePromptMessageContent, message_content)
if not message_content.data.startswith("data:"):
# fetch image data from url
try:
image_content = requests.get(message_content.data).content
mime_type, _ = mimetypes.guess_type(message_content.data)
base64_data = base64.b64encode(image_content).decode('utf-8')
except Exception as ex:
raise ValueError(f"Failed to fetch image data from url {message_content.data}, {ex}")
else:
data_split = message_content.data.split(";base64,")
mime_type = data_split[0].replace("data:", "")
base64_data = data_split[1]
if mime_type not in ["image/jpeg", "image/png", "image/gif", "image/webp"]:
raise ValueError(f"Unsupported image type {mime_type}, "
f"only support image/jpeg, image/png, image/gif, and image/webp")
sub_message_dict = {
"type": "image",
"source": {
"type": "base64",
"media_type": mime_type,
"data": base64_data
}
}
sub_messages.append(sub_message_dict)
message_dict = {"role": "user", "content": sub_messages}
elif isinstance(message, AssistantPromptMessage):
message = cast(AssistantPromptMessage, message)
message_dict = {"role": "assistant", "content": message.content}
elif isinstance(message, SystemPromptMessage):
message = cast(SystemPromptMessage, message)
message_dict = {"role": "system", "content": message.content}
else:
raise ValueError(f"Got unknown type {message}")
return message_dict
def _convert_one_message_to_text(self, message: PromptMessage) -> str:
"""
Convert a single message to a string.
@@ -523,8 +453,6 @@ class AnthropicLargeLanguageModel(LargeLanguageModel):
message_text += f"{ai_prompt} [IMAGE]"
elif isinstance(message, SystemPromptMessage):
message_text = content
elif isinstance(message, ToolPromptMessage):
message_text = f"{human_prompt} {message.content}"
else:
raise ValueError(f"Got unknown type {message}")
@@ -99,12 +99,6 @@ model_credential_schema:
show_on:
- variable: __model_type
value: llm
- label:
en_US: gpt-4-turbo-2024-04-09
value: gpt-4-turbo-2024-04-09
show_on:
- variable: __model_type
value: llm
- label:
en_US: gpt-4-0125-preview
value: gpt-4-0125-preview

Some files were not shown because too many files have changed in this diff Show More