This commit is contained in:
2025-12-01 17:21:38 +08:00
parent 32fee2b8ab
commit fab8c13cb3
7511 changed files with 996300 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
export type CreateExternalAPIReq = {
name: string
settings: {
endpoint: string
api_key: string
}
}
export type FormSchema = {
variable: string
type: 'text' | 'secret'
label: {
[key: string]: string
}
required: boolean
}

View File

@@ -0,0 +1,92 @@
import React from 'react'
import type { FC } from 'react'
import { useTranslation } from 'react-i18next'
import { RiBookOpenLine } from '@remixicon/react'
import type { CreateExternalAPIReq, FormSchema } from '../declarations'
import Input from '@/app/components/base/input'
import cn from '@/utils/classnames'
import { useDocLink } from '@/context/i18n'
type FormProps = {
className?: string
itemClassName?: string
fieldLabelClassName?: string
value: CreateExternalAPIReq
onChange: (val: CreateExternalAPIReq) => void
formSchemas: FormSchema[]
inputClassName?: string
}
const Form: FC<FormProps> = React.memo(({
className,
itemClassName,
fieldLabelClassName,
value,
onChange,
formSchemas,
inputClassName,
}) => {
const { t, i18n } = useTranslation()
const docLink = useDocLink()
const handleFormChange = (key: string, val: string) => {
if (key === 'name') {
onChange({ ...value, [key]: val })
}
else {
onChange({
...value,
settings: {
...value.settings,
[key]: val,
},
})
}
}
const renderField = (formSchema: FormSchema) => {
const { variable, type, label, required } = formSchema
const fieldValue = variable === 'name' ? value[variable] : (value.settings[variable as keyof typeof value.settings] || '')
return (
<div key={variable} className={cn(itemClassName, 'flex flex-col items-start gap-1 self-stretch')}>
<div className="flex w-full items-center justify-between">
<label className={cn(fieldLabelClassName, 'system-sm-semibold text-text-secondary')} htmlFor={variable}>
{label[i18n.language] || label.en_US}
{required && <span className='ml-1 text-red-500'>*</span>}
</label>
{variable === 'endpoint' && (
<a
href={docLink('/guides/knowledge-base/connect-external-knowledge-base') || '/'}
target='_blank'
rel='noopener noreferrer'
className='body-xs-regular flex items-center text-text-accent'
>
<RiBookOpenLine className='mr-1 h-3 w-3 text-text-accent' />
{t('dataset.externalAPIPanelDocumentation')}
</a>
)}
</div>
<Input
type={type === 'secret' ? 'password' : 'text'}
id={variable}
name={variable}
value={fieldValue}
onChange={val => handleFormChange(variable, val.target.value)}
required={required}
className={cn(inputClassName)}
/>
</div>
)
}
return (
<form className={cn('flex flex-col items-start justify-center gap-4 self-stretch', className)}>
{formSchemas.map(formSchema => renderField(formSchema))}
</form>
)
})
Form.displayName = 'Form'
export default Form

View File

@@ -0,0 +1,218 @@
import type { FC } from 'react'
import {
memo,
useEffect,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import {
RiBook2Line,
RiCloseLine,
RiInformation2Line,
RiLock2Fill,
} from '@remixicon/react'
import type { CreateExternalAPIReq, FormSchema } from '../declarations'
import Form from './Form'
import ActionButton from '@/app/components/base/action-button'
import Confirm from '@/app/components/base/confirm'
import {
PortalToFollowElem,
PortalToFollowElemContent,
} from '@/app/components/base/portal-to-follow-elem'
import { createExternalAPI } from '@/service/datasets'
import { useToastContext } from '@/app/components/base/toast'
import Button from '@/app/components/base/button'
import Tooltip from '@/app/components/base/tooltip'
type AddExternalAPIModalProps = {
data?: CreateExternalAPIReq
onSave: (formValue: CreateExternalAPIReq) => void
onCancel: () => void
onEdit?: (formValue: CreateExternalAPIReq) => Promise<void>
datasetBindings?: { id: string; name: string }[]
isEditMode: boolean
}
const formSchemas: FormSchema[] = [
{
variable: 'name',
type: 'text',
label: {
en_US: 'Name',
},
required: true,
},
{
variable: 'endpoint',
type: 'text',
label: {
en_US: 'API Endpoint',
},
required: true,
},
{
variable: 'api_key',
type: 'secret',
label: {
en_US: 'API Key',
},
required: true,
},
]
const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCancel, datasetBindings, isEditMode, onEdit }) => {
const { t } = useTranslation()
const { notify } = useToastContext()
const [loading, setLoading] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const [formData, setFormData] = useState<CreateExternalAPIReq>({ name: '', settings: { endpoint: '', api_key: '' } })
useEffect(() => {
if (isEditMode && data)
setFormData(data)
}, [isEditMode, data])
const hasEmptyInputs = Object.values(formData).some(value =>
typeof value === 'string' ? value.trim() === '' : Object.values(value).some(v => v.trim() === ''),
)
const handleDataChange = (val: CreateExternalAPIReq) => {
setFormData(val)
}
const handleSave = async () => {
if (formData && formData.settings.api_key && formData.settings.api_key?.length < 5) {
notify({ type: 'error', message: t('common.apiBasedExtension.modal.apiKey.lengthError') })
setLoading(false)
return
}
try {
setLoading(true)
if (isEditMode && onEdit) {
await onEdit(
{
...formData,
settings: { ...formData.settings, api_key: formData.settings.api_key ? '[__HIDDEN__]' : formData.settings.api_key },
},
)
notify({ type: 'success', message: 'External API updated successfully' })
}
else {
const res = await createExternalAPI({ body: formData })
if (res && res.id) {
notify({ type: 'success', message: 'External API saved successfully' })
onSave(res)
}
}
onCancel()
}
catch (error) {
console.error('Error saving/updating external API:', error)
notify({ type: 'error', message: 'Failed to save/update External API' })
}
finally {
setLoading(false)
}
}
return (
<PortalToFollowElem open>
<PortalToFollowElemContent className='z-[60] h-full w-full'>
<div className='fixed inset-0 flex items-center justify-center bg-black/[.25]'>
<div className='shadows-shadow-xl relative flex w-[480px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg'>
<div className='flex flex-col items-start gap-2 self-stretch pb-3 pl-6 pr-14 pt-6'>
<div className='title-2xl-semi-bold grow self-stretch text-text-primary'>
{
isEditMode ? t('dataset.editExternalAPIFormTitle') : t('dataset.createExternalAPI')
}
</div>
{isEditMode && (datasetBindings?.length ?? 0) > 0 && (
<div className='system-xs-regular flex items-center text-text-tertiary'>
{t('dataset.editExternalAPIFormWarning.front')}
<span className='flex cursor-pointer items-center text-text-accent'>
&nbsp;{datasetBindings?.length} {t('dataset.editExternalAPIFormWarning.end')}&nbsp;
<Tooltip
popupClassName='flex items-center self-stretch w-[320px]'
popupContent={
<div className='p-1'>
<div className='flex items-start self-stretch pb-0.5 pl-2 pr-3 pt-1'>
<div className='system-xs-medium-uppercase text-text-tertiary'>{`${datasetBindings?.length} ${t('dataset.editExternalAPITooltipTitle')}`}</div>
</div>
{datasetBindings?.map(binding => (
<div key={binding.id} className='flex items-center gap-1 self-stretch px-2 py-1'>
<RiBook2Line className='h-4 w-4 text-text-secondary' />
<div className='system-sm-medium text-text-secondary'>{binding.name}</div>
</div>
))}
</div>
}
asChild={false}
position='bottom'
>
<RiInformation2Line className='h-3.5 w-3.5' />
</Tooltip>
</span>
</div>
)}
</div>
<ActionButton className='absolute right-5 top-5' onClick={onCancel}>
<RiCloseLine className='h-[18px] w-[18px] shrink-0 text-text-tertiary' />
</ActionButton>
<Form
value={formData}
onChange={handleDataChange}
formSchemas={formSchemas}
className='flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3'
/>
<div className='flex items-center justify-end gap-2 self-stretch p-6 pt-5'>
<Button type='button' variant='secondary' onClick={onCancel}>
{t('dataset.externalAPIForm.cancel')}
</Button>
<Button
type='submit'
variant='primary'
onClick={() => {
if (isEditMode && (datasetBindings?.length ?? 0) > 0)
setShowConfirm(true)
else if (isEditMode && onEdit)
onEdit(formData)
else
handleSave()
}}
disabled={hasEmptyInputs || loading}
>
{t('dataset.externalAPIForm.save')}
</Button>
</div>
<div className='system-xs-regular flex items-center justify-center gap-1 self-stretch rounded-b-2xl border-t-[0.5px]
border-divider-subtle bg-background-soft px-2 py-3 text-text-tertiary'
>
<RiLock2Fill className='h-3 w-3 text-text-quaternary' />
{t('dataset.externalAPIForm.encrypted.front')}
<a
className='text-text-accent'
target='_blank' rel='noopener noreferrer'
href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
>
PKCS1_OAEP
</a>
{t('dataset.externalAPIForm.encrypted.end')}
</div>
</div>
{showConfirm && (datasetBindings?.length ?? 0) > 0 && (
<Confirm
isShow={showConfirm}
type='warning'
title='Warning'
content={`${t('dataset.editExternalAPIConfirmWarningContent.front')} ${datasetBindings?.length} ${t('dataset.editExternalAPIConfirmWarningContent.end')}`}
onCancel={() => setShowConfirm(false)}
onConfirm={handleSave}
/>
)}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default memo(AddExternalAPIModal)

View File

@@ -0,0 +1,93 @@
import React from 'react'
import {
RiAddLine,
RiBookOpenLine,
RiCloseLine,
} from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import ExternalKnowledgeAPICard from '../external-knowledge-api-card'
import cn from '@/utils/classnames'
import { useExternalKnowledgeApi } from '@/context/external-knowledge-api-context'
import ActionButton from '@/app/components/base/action-button'
import Button from '@/app/components/base/button'
import Loading from '@/app/components/base/loading'
import { useModalContext } from '@/context/modal-context'
import { useDocLink } from '@/context/i18n'
type ExternalAPIPanelProps = {
onClose: () => void
}
const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({ onClose }) => {
const { t } = useTranslation()
const docLink = useDocLink()
const { setShowExternalKnowledgeAPIModal } = useModalContext()
const { externalKnowledgeApiList, mutateExternalKnowledgeApis, isLoading } = useExternalKnowledgeApi()
const handleOpenExternalAPIModal = () => {
setShowExternalKnowledgeAPIModal({
payload: { name: '', settings: { endpoint: '', api_key: '' } },
datasetBindings: [],
onSaveCallback: () => {
mutateExternalKnowledgeApis()
},
onCancelCallback: () => {
mutateExternalKnowledgeApis()
},
isEditMode: false,
})
}
return (
<div
tabIndex={-1}
className={cn('absolute bottom-2 right-0 top-14 z-10 flex outline-none')}
>
<div
className={cn(
'relative flex h-full w-[420px] flex-col rounded-l-2xl border border-components-panel-border bg-components-panel-bg-alt',
)}
>
<div className='flex items-start self-stretch p-4 pb-0'>
<div className='flex grow flex-col items-start gap-1'>
<div className='system-xl-semibold self-stretch text-text-primary'>{t('dataset.externalAPIPanelTitle')}</div>
<div className='body-xs-regular self-stretch text-text-tertiary'>{t('dataset.externalAPIPanelDescription')}</div>
<a className='flex cursor-pointer items-center justify-center gap-1 self-stretch'
href={docLink('/guides/knowledge-base/connect-external-knowledge-base')} target='_blank'>
<RiBookOpenLine className='h-3 w-3 text-text-accent' />
<div className='body-xs-regular grow text-text-accent'>{t('dataset.externalAPIPanelDocumentation')}</div>
</a>
</div>
<div className='flex items-center'>
<ActionButton onClick={() => onClose()}>
<RiCloseLine className='h-4 w-4 text-text-tertiary' />
</ActionButton>
</div>
</div>
<div className='flex flex-col items-start justify-center gap-2 self-stretch px-4 py-3'>
<Button
variant={'primary'}
className='flex items-center justify-center gap-0.5 px-3 py-2'
onClick={handleOpenExternalAPIModal}
>
<RiAddLine className='h-4 w-4 text-components-button-primary-text' />
<div className='system-sm-medium text-components-button-primary-text'>{t('dataset.createExternalAPI')}</div>
</Button>
</div>
<div className='flex grow flex-col items-start gap-1 self-stretch px-4 py-0'>
{isLoading
? (
<Loading />
)
: (
externalKnowledgeApiList.map(api => (
<ExternalKnowledgeAPICard key={api.id} api={api} />
))
)}
</div>
</div>
</div>
)
}
export default ExternalAPIPanel

View File

@@ -0,0 +1,151 @@
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiDeleteBinLine,
RiEditLine,
} from '@remixicon/react'
import type { CreateExternalAPIReq } from '../declarations'
import type { ExternalAPIItem } from '@/models/datasets'
import { checkUsageExternalAPI, deleteExternalAPI, fetchExternalAPI, updateExternalAPI } from '@/service/datasets'
import { ApiConnectionMod } from '@/app/components/base/icons/src/vender/solid/development'
import { useExternalKnowledgeApi } from '@/context/external-knowledge-api-context'
import { useModalContext } from '@/context/modal-context'
import ActionButton from '@/app/components/base/action-button'
import Confirm from '@/app/components/base/confirm'
type ExternalKnowledgeAPICardProps = {
api: ExternalAPIItem
}
const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({ api }) => {
const { setShowExternalKnowledgeAPIModal } = useModalContext()
const [showConfirm, setShowConfirm] = useState(false)
const [isHovered, setIsHovered] = useState(false)
const [usageCount, setUsageCount] = useState(0)
const { mutateExternalKnowledgeApis } = useExternalKnowledgeApi()
const { t } = useTranslation()
const handleEditClick = async () => {
try {
const response = await fetchExternalAPI({ apiTemplateId: api.id })
const formValue: CreateExternalAPIReq = {
name: response.name,
settings: {
endpoint: response.settings.endpoint,
api_key: response.settings.api_key,
},
}
setShowExternalKnowledgeAPIModal({
payload: formValue,
onSaveCallback: () => {
mutateExternalKnowledgeApis()
},
onCancelCallback: () => {
mutateExternalKnowledgeApis()
},
isEditMode: true,
datasetBindings: response.dataset_bindings,
onEditCallback: async (updatedData: CreateExternalAPIReq) => {
try {
await updateExternalAPI({
apiTemplateId: api.id,
body: {
...response,
name: updatedData.name,
settings: {
...response.settings,
endpoint: updatedData.settings.endpoint,
api_key: updatedData.settings.api_key,
},
},
})
mutateExternalKnowledgeApis()
}
catch (error) {
console.error('Error updating external knowledge API:', error)
}
},
})
}
catch (error) {
console.error('Error fetching external knowledge API data:', error)
}
}
const handleDeleteClick = async () => {
try {
const usage = await checkUsageExternalAPI({ apiTemplateId: api.id })
if (usage.is_using)
setUsageCount(usage.count)
setShowConfirm(true)
}
catch (error) {
console.error('Error checking external API usage:', error)
}
}
const handleConfirmDelete = async () => {
try {
const response = await deleteExternalAPI({ apiTemplateId: api.id })
if (response && response.result === 'success') {
setShowConfirm(false)
mutateExternalKnowledgeApis()
}
else {
console.error('Failed to delete external API')
}
}
catch (error) {
console.error('Error deleting external knowledge API:', error)
}
}
return (
<>
<div className={`shadows-shadow-xs flex items-start self-stretch rounded-lg border-[0.5px] border-components-panel-border-subtle
bg-components-panel-on-panel-item-bg p-2
pl-3 ${isHovered ? 'border-state-destructive-border bg-state-destructive-hover' : ''}`}
>
<div className='flex grow flex-col items-start justify-center gap-1.5 py-1'>
<div className='flex items-center gap-1 self-stretch text-text-secondary'>
<ApiConnectionMod className='h-4 w-4' />
<div className='system-sm-medium'>{api.name}</div>
</div>
<div className='system-xs-regular self-stretch text-text-tertiary'>{api.settings.endpoint}</div>
</div>
<div className='flex items-start gap-1'>
<ActionButton onClick={handleEditClick}>
<RiEditLine className='h-4 w-4 text-text-tertiary hover:text-text-secondary' />
</ActionButton>
<ActionButton
className='hover:bg-state-destructive-hover'
onClick={handleDeleteClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<RiDeleteBinLine className='h-4 w-4 text-text-tertiary hover:text-text-destructive' />
</ActionButton>
</div>
</div>
{showConfirm && (
<Confirm
isShow={showConfirm}
title={`${t('dataset.deleteExternalAPIConfirmWarningContent.title.front')} ${api.name}${t('dataset.deleteExternalAPIConfirmWarningContent.title.end')}`}
content={
usageCount > 0
? `${t('dataset.deleteExternalAPIConfirmWarningContent.content.front')} ${usageCount} ${t('dataset.deleteExternalAPIConfirmWarningContent.content.end')}`
: t('dataset.deleteExternalAPIConfirmWarningContent.noConnectionContent')
}
type='warning'
onConfirm={handleConfirmDelete}
onCancel={() => setShowConfirm(false)}
/>
)}
</>
)
}
export default ExternalKnowledgeAPICard