index.tsx 8.1 KB

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