index.tsx 8.4 KB

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