Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.tsx 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useMemo, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useContext } from 'use-context-selector'
  6. import produce from 'immer'
  7. import {
  8. RiAddLine,
  9. RiCloseLine,
  10. } from '@remixicon/react'
  11. import { useMount } from 'ahooks'
  12. import type { Collection, CustomCollectionBackend, Tool } from '../types'
  13. import Type from './type'
  14. import Category from './category'
  15. import Tools from './tools'
  16. import cn from '@/utils/classnames'
  17. import { basePath } from '@/utils/var'
  18. import I18n from '@/context/i18n'
  19. import Drawer from '@/app/components/base/drawer'
  20. import Button from '@/app/components/base/button'
  21. import Loading from '@/app/components/base/loading'
  22. import Input from '@/app/components/base/input'
  23. import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'
  24. import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'
  25. import {
  26. createCustomCollection,
  27. fetchAllBuiltInTools,
  28. fetchAllCustomTools,
  29. fetchAllWorkflowTools,
  30. removeBuiltInToolCredential,
  31. updateBuiltInToolCredential,
  32. } from '@/service/tools'
  33. import type { ToolWithProvider } from '@/app/components/workflow/types'
  34. import Toast from '@/app/components/base/toast'
  35. import ConfigContext from '@/context/debug-configuration'
  36. import type { ModelConfig } from '@/models/debug'
  37. type Props = {
  38. onHide: () => void
  39. }
  40. // Add and Edit
  41. const AddToolModal: FC<Props> = ({
  42. onHide,
  43. }) => {
  44. const { t } = useTranslation()
  45. const { locale } = useContext(I18n)
  46. const [currentType, setCurrentType] = useState('builtin')
  47. const [currentCategory, setCurrentCategory] = useState('')
  48. const [keywords, setKeywords] = useState<string>('')
  49. const handleKeywordsChange = (value: string) => {
  50. setKeywords(value)
  51. }
  52. const isMatchingKeywords = (text: string, keywords: string) => {
  53. return text.toLowerCase().includes(keywords.toLowerCase())
  54. }
  55. const [toolList, setToolList] = useState<ToolWithProvider[]>([])
  56. const [listLoading, setListLoading] = useState(true)
  57. const getAllTools = async () => {
  58. setListLoading(true)
  59. const buildInTools = await fetchAllBuiltInTools()
  60. if (basePath) {
  61. buildInTools.forEach((item) => {
  62. if (typeof item.icon == 'string' && !item.icon.includes(basePath))
  63. item.icon = `${basePath}${item.icon}`
  64. })
  65. }
  66. const customTools = await fetchAllCustomTools()
  67. const workflowTools = await fetchAllWorkflowTools()
  68. const mergedToolList = [
  69. ...buildInTools,
  70. ...customTools,
  71. ...workflowTools.filter((toolWithProvider) => {
  72. return !toolWithProvider.tools.some((tool) => {
  73. return !!tool.parameters.find(item => item.name === '__image')
  74. })
  75. }),
  76. ]
  77. setToolList(mergedToolList)
  78. setListLoading(false)
  79. }
  80. const filteredList = useMemo(() => {
  81. return toolList.filter((toolWithProvider) => {
  82. if (currentType === 'all')
  83. return true
  84. else
  85. return toolWithProvider.type === currentType
  86. }).filter((toolWithProvider) => {
  87. if (!currentCategory)
  88. return true
  89. else
  90. return toolWithProvider.labels.includes(currentCategory)
  91. }).filter((toolWithProvider) => {
  92. return (
  93. isMatchingKeywords(toolWithProvider.name, keywords)
  94. || toolWithProvider.tools.some((tool) => {
  95. return Object.values(tool.label).some((label) => {
  96. return isMatchingKeywords(label, keywords)
  97. })
  98. })
  99. )
  100. })
  101. }, [currentType, currentCategory, toolList, keywords])
  102. const {
  103. modelConfig,
  104. setModelConfig,
  105. } = useContext(ConfigContext)
  106. const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)
  107. const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {
  108. await createCustomCollection(data)
  109. Toast.notify({
  110. type: 'success',
  111. message: t('common.api.actionSuccess'),
  112. })
  113. setIsShowEditCustomCollectionModal(false)
  114. getAllTools()
  115. }
  116. const [showSettingAuth, setShowSettingAuth] = useState(false)
  117. const [collection, setCollection] = useState<Collection>()
  118. const toolSelectHandle = (collection: Collection, tool: Tool) => {
  119. const parameters: Record<string, string> = {}
  120. if (tool.parameters) {
  121. tool.parameters.forEach((item) => {
  122. parameters[item.name] = ''
  123. })
  124. }
  125. const nexModelConfig = produce(modelConfig, (draft: ModelConfig) => {
  126. draft.agentConfig.tools.push({
  127. provider_id: collection.id || collection.name,
  128. provider_type: collection.type,
  129. provider_name: collection.name,
  130. tool_name: tool.name,
  131. tool_label: tool.label[locale] || tool.label[locale.replaceAll('-', '_')],
  132. tool_parameters: parameters,
  133. enabled: true,
  134. })
  135. })
  136. setModelConfig(nexModelConfig)
  137. }
  138. const authSelectHandle = (provider: Collection) => {
  139. setCollection(provider)
  140. setShowSettingAuth(true)
  141. }
  142. const updateBuiltinAuth = async (value: Record<string, any>) => {
  143. if (!collection)
  144. return
  145. await updateBuiltInToolCredential(collection.name, value)
  146. Toast.notify({
  147. type: 'success',
  148. message: t('common.api.actionSuccess'),
  149. })
  150. await getAllTools()
  151. setShowSettingAuth(false)
  152. }
  153. const removeBuiltinAuth = async () => {
  154. if (!collection)
  155. return
  156. await removeBuiltInToolCredential(collection.name)
  157. Toast.notify({
  158. type: 'success',
  159. message: t('common.api.actionSuccess'),
  160. })
  161. await getAllTools()
  162. setShowSettingAuth(false)
  163. }
  164. useMount(() => {
  165. getAllTools()
  166. })
  167. return (
  168. <>
  169. <Drawer
  170. isOpen
  171. mask
  172. clickOutsideNotOpen
  173. onClose={onHide}
  174. footer={null}
  175. panelClassName={cn('mx-2 mb-3 mt-16 rounded-xl !p-0 sm:mr-2', 'mt-2 !w-[640px]', '!max-w-[640px]')}
  176. >
  177. <div
  178. className='flex w-full rounded-xl border-[0.5px] border-gray-200 bg-white shadow-xl'
  179. style={{
  180. height: 'calc(100vh - 16px)',
  181. }}
  182. >
  183. <div className='relative w-[200px] shrink-0 overflow-y-auto rounded-l-xl border-r-[0.5px] border-black/2 bg-gray-100 pb-3'>
  184. <div className='sticky left-0 right-0 top-0'>
  185. <div className='text-md sticky left-0 right-0 top-0 px-5 py-3 font-semibold text-gray-900'>{t('tools.addTool')}</div>
  186. <div className='px-3 pb-4 pt-2'>
  187. <Button variant='primary' className='w-[176px]' onClick={() => setIsShowEditCustomCollectionModal(true)}>
  188. <RiAddLine className='mr-1 h-4 w-4' />
  189. {t('tools.createCustomTool')}
  190. </Button>
  191. </div>
  192. </div>
  193. <div className='px-2 py-1'>
  194. <Type value={currentType} onSelect={setCurrentType} />
  195. <Category value={currentCategory} onSelect={setCurrentCategory} />
  196. </div>
  197. </div>
  198. <div className='relative grow overflow-y-auto rounded-r-xl bg-white'>
  199. <div className='sticky left-0 right-0 top-0 z-10 flex items-center gap-1 bg-white p-2'>
  200. <div className='grow'>
  201. <Input
  202. showLeftIcon
  203. showClearIcon
  204. value={keywords}
  205. onChange={e => handleKeywordsChange(e.target.value)}
  206. onClear={() => handleKeywordsChange('')}
  207. />
  208. </div>
  209. <div className='ml-2 mr-1 h-4 w-[1px] bg-gray-200'></div>
  210. <div className='cursor-pointer p-2' onClick={onHide}>
  211. <RiCloseLine className='h-4 w-4 text-gray-500' />
  212. </div>
  213. </div>
  214. {listLoading && (
  215. <div className='flex h-[200px] items-center justify-center bg-white'>
  216. <Loading />
  217. </div>
  218. )}
  219. {!listLoading && (
  220. <Tools
  221. showWorkflowEmpty={currentType === 'workflow'}
  222. tools={filteredList}
  223. addedTools={(modelConfig?.agentConfig?.tools as any) || []}
  224. onSelect={toolSelectHandle}
  225. onAuthSetup={authSelectHandle}
  226. />
  227. )}
  228. </div>
  229. </div>
  230. </Drawer>
  231. {isShowEditCollectionToolModal && (
  232. <EditCustomToolModal
  233. positionLeft
  234. payload={null}
  235. onHide={() => setIsShowEditCustomCollectionModal(false)}
  236. onAdd={doCreateCustomToolCollection}
  237. />
  238. )}
  239. {showSettingAuth && collection && (
  240. <ConfigCredential
  241. collection={collection}
  242. onCancel={() => setShowSettingAuth(false)}
  243. onSaved={updateBuiltinAuth}
  244. onRemove={removeBuiltinAuth}
  245. />
  246. )}
  247. </>
  248. )
  249. }
  250. export default React.memo(AddToolModal)