Commit 8a50be91 by liimin

去除一些文件

1 parent e948cb6f
Showing 111 changed files with 0 additions and 4953 deletions
This diff could not be displayed because it is too large.
import React from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '../base/app-icon'
import Tooltip from '@/app/components/base/tooltip'
export type IAppBasicProps = {
iconType?: 'app' | 'api' | 'dataset' | 'webapp' | 'notion'
icon?: string
icon_background?: string | null
isExternal?: boolean
name: string
type: string | React.ReactNode
hoverTip?: string
textStyle?: { main?: string; extra?: string }
isExtraInLine?: boolean
mode?: string
}
const ApiSvg = <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.5 3.5C8.5 4.60457 9.39543 5.5 10.5 5.5C11.6046 5.5 12.5 4.60457 12.5 3.5C12.5 2.39543 11.6046 1.5 10.5 1.5C9.39543 1.5 8.5 2.39543 8.5 3.5Z" stroke="#5850EC" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
<path d="M12.5 9C12.5 10.1046 13.3954 11 14.5 11C15.6046 11 16.5 10.1046 16.5 9C16.5 7.89543 15.6046 7 14.5 7C13.3954 7 12.5 7.89543 12.5 9Z" stroke="#5850EC" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
<path d="M8.5 3.5H5.5L3.5 6.5" stroke="#5850EC" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
<path d="M8.5 14.5C8.5 15.6046 9.39543 16.5 10.5 16.5C11.6046 16.5 12.5 15.6046 12.5 14.5C12.5 13.3954 11.6046 12.5 10.5 12.5C9.39543 12.5 8.5 13.3954 8.5 14.5Z" stroke="#5850EC" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
<path d="M8.5 14.5H5.5L3.5 11.5" stroke="#5850EC" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
<path d="M12.5 9H1.5" stroke="#5850EC" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
const DatasetSvg = <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" clipRule="evenodd" d="M0.833497 5.13481C0.833483 4.69553 0.83347 4.31654 0.858973 4.0044C0.88589 3.67495 0.94532 3.34727 1.10598 3.03195C1.34567 2.56155 1.72812 2.17909 2.19852 1.93941C2.51384 1.77875 2.84152 1.71932 3.17097 1.6924C3.48312 1.6669 3.86209 1.66691 4.30137 1.66693L7.62238 1.66684C8.11701 1.66618 8.55199 1.66561 8.95195 1.80356C9.30227 1.92439 9.62134 2.12159 9.88607 2.38088C10.1883 2.67692 10.3823 3.06624 10.603 3.50894L11.3484 5.00008H14.3679C15.0387 5.00007 15.5924 5.00006 16.0434 5.03691C16.5118 5.07518 16.9424 5.15732 17.3468 5.36339C17.974 5.68297 18.4839 6.19291 18.8035 6.82011C19.0096 7.22456 19.0917 7.65515 19.13 8.12356C19.1668 8.57455 19.1668 9.12818 19.1668 9.79898V13.5345C19.1668 14.2053 19.1668 14.7589 19.13 15.2099C19.0917 15.6784 19.0096 16.1089 18.8035 16.5134C18.4839 17.1406 17.974 17.6505 17.3468 17.9701C16.9424 18.1762 16.5118 18.2583 16.0434 18.2966C15.5924 18.3334 15.0387 18.3334 14.3679 18.3334H5.63243C4.96163 18.3334 4.40797 18.3334 3.95698 18.2966C3.48856 18.2583 3.05798 18.1762 2.65353 17.9701C2.02632 17.6505 1.51639 17.1406 1.19681 16.5134C0.990734 16.1089 0.908597 15.6784 0.870326 15.2099C0.833478 14.7589 0.833487 14.2053 0.833497 13.5345V5.13481ZM7.51874 3.33359C8.17742 3.33359 8.30798 3.34447 8.4085 3.37914C8.52527 3.41942 8.63163 3.48515 8.71987 3.57158C8.79584 3.64598 8.86396 3.7579 9.15852 4.34704L9.48505 5.00008L2.50023 5.00008C2.50059 4.61259 2.50314 4.34771 2.5201 4.14012C2.5386 3.91374 2.57 3.82981 2.59099 3.7886C2.67089 3.6318 2.79837 3.50432 2.95517 3.42442C2.99638 3.40343 3.08031 3.37203 3.30669 3.35353C3.54281 3.33424 3.85304 3.33359 4.3335 3.33359H7.51874Z" fill="#444CE7" />
</svg>
const WebappSvg = <svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.375 5.45825L7.99998 8.99992M7.99998 8.99992L1.62498 5.45825M7.99998 8.99992L8 16.1249M14.75 12.0439V5.95603C14.75 5.69904 14.75 5.57055 14.7121 5.45595C14.6786 5.35457 14.6239 5.26151 14.5515 5.18299C14.4697 5.09424 14.3574 5.03184 14.1328 4.90704L8.58277 1.8237C8.37007 1.70553 8.26372 1.64645 8.15109 1.62329C8.05141 1.60278 7.9486 1.60278 7.84891 1.62329C7.73628 1.64645 7.62993 1.70553 7.41723 1.8237L1.86723 4.90704C1.64259 5.03184 1.53026 5.09424 1.44847 5.18299C1.37612 5.26151 1.32136 5.35457 1.28786 5.45595C1.25 5.57055 1.25 5.69904 1.25 5.95603V12.0439C1.25 12.3008 1.25 12.4293 1.28786 12.5439C1.32136 12.6453 1.37612 12.7384 1.44847 12.8169C1.53026 12.9056 1.64259 12.968 1.86723 13.0928L7.41723 16.1762C7.62993 16.2943 7.73628 16.3534 7.84891 16.3766C7.9486 16.3971 8.05141 16.3971 8.15109 16.3766C8.26372 16.3534 8.37007 16.2943 8.58277 16.1762L14.1328 13.0928C14.3574 12.968 14.4697 12.9056 14.5515 12.8169C14.6239 12.7384 14.6786 12.6453 14.7121 12.5439C14.75 12.4293 14.75 12.3008 14.75 12.0439Z" stroke="#155EEF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
const NotionSvg = <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clipPath="url(#clip0_6294_13848)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M4.287 21.9133L1.70748 18.6999C1.08685 17.9267 0.75 16.976 0.75 15.9974V4.36124C0.75 2.89548 1.92269 1.67923 3.43553 1.57594L15.3991 0.759137C16.2682 0.699797 17.1321 0.930818 17.8461 1.41353L22.0494 4.25543C22.8018 4.76414 23.25 5.59574 23.25 6.48319V19.7124C23.25 21.1468 22.0969 22.3345 20.6157 22.4256L7.3375 23.243C6.1555 23.3158 5.01299 22.8178 4.287 21.9133Z" fill="white" />
<path d="M8.43607 10.1842V10.0318C8.43607 9.64564 8.74535 9.32537 9.14397 9.29876L12.0475 9.10491L16.0628 15.0178V9.82823L15.0293 9.69046V9.6181C15.0293 9.22739 15.3456 8.90501 15.7493 8.88433L18.3912 8.74899V9.12918C18.3912 9.30765 18.2585 9.46031 18.0766 9.49108L17.4408 9.59861V18.0029L16.6429 18.2773C15.9764 18.5065 15.2343 18.2611 14.8527 17.6853L10.9545 11.803V17.4173L12.1544 17.647L12.1377 17.7583C12.0853 18.1069 11.7843 18.3705 11.4202 18.3867L8.43607 18.5195C8.39662 18.1447 8.67758 17.8093 9.06518 17.7686L9.45771 17.7273V10.2416L8.43607 10.1842Z" fill="black" />
<path fill-rule="evenodd" clip-rule="evenodd" d="M15.5062 2.22521L3.5426 3.04201C2.82599 3.09094 2.27051 3.66706 2.27051 4.36136V15.9975C2.27051 16.6499 2.49507 17.2837 2.90883 17.7992L5.48835 21.0126C5.90541 21.5322 6.56174 21.8183 7.24076 21.7765L20.519 20.9591C21.1995 20.9172 21.7293 20.3716 21.7293 19.7125V6.48332C21.7293 6.07557 21.5234 5.69348 21.1777 5.45975L16.9743 2.61784C16.546 2.32822 16.0277 2.1896 15.5062 2.22521ZM4.13585 4.54287C3.96946 4.41968 4.04865 4.16303 4.25768 4.14804L15.5866 3.33545C15.9476 3.30956 16.3063 3.40896 16.5982 3.61578L18.8713 5.22622C18.9576 5.28736 18.9171 5.41935 18.8102 5.42516L6.8129 6.07764C6.44983 6.09739 6.09144 5.99073 5.80276 5.77699L4.13585 4.54287ZM6.25018 8.12315C6.25018 7.7334 6.56506 7.41145 6.9677 7.38952L19.6523 6.69871C20.0447 6.67734 20.375 6.97912 20.375 7.35898V18.8141C20.375 19.2031 20.0613 19.5247 19.6594 19.5476L7.05516 20.2648C6.61845 20.2896 6.25018 19.954 6.25018 19.5312V8.12315Z" fill="black" />
</g>
<defs>
<clipPath id="clip0_6294_13848">
<rect width="24" height="24" fill="white" />
</clipPath>
</defs>
</svg>
const ICON_MAP = {
app: <AppIcon className='border !border-[rgba(0,0,0,0.05)]' />,
api: <AppIcon innerIcon={ApiSvg} className='border !border-purple-200 !bg-purple-50' />,
dataset: <AppIcon innerIcon={DatasetSvg} className='!border-[0.5px] !border-indigo-100 !bg-indigo-25' />,
webapp: <AppIcon innerIcon={WebappSvg} className='border !border-primary-200 !bg-primary-100' />,
notion: <AppIcon innerIcon={NotionSvg} className='!border-[0.5px] !border-indigo-100 !bg-white' />,
}
export default function AppBasic({ icon, icon_background, name, isExternal, type, hoverTip, textStyle, isExtraInLine, mode = 'expand', iconType = 'app' }: IAppBasicProps) {
const { t } = useTranslation()
return (
<div className="flex grow items-center">
{icon && icon_background && iconType === 'app' && (
<div className='mr-3 shrink-0'>
<AppIcon icon={icon} background={icon_background} />
</div>
)}
{iconType !== 'app'
&& <div className='mr-3 shrink-0'>
{ICON_MAP[iconType]}
</div>
}
{mode === 'expand' && <div className="group w-full">
<div className={`system-md-semibold flex flex-row items-center text-text-secondary group-hover:text-text-primary ${textStyle?.main ?? ''}`}>
<div className="min-w-0 overflow-hidden text-ellipsis break-normal">
{name}
</div>
{hoverTip
&& <Tooltip
popupContent={
<div className='w-[240px]'>
{hoverTip}
</div>
}
popupClassName='ml-1'
triggerClassName='w-4 h-4 ml-1'
position='top'
/>
}
</div>
{isExtraInLine ? (
<div className="system-2xs-medium-uppercase flex text-text-tertiary">{type}</div>
) : (
<div className='system-2xs-medium-uppercase text-text-tertiary'>{isExternal ? t('dataset.externalTag') : type}</div>
)}
</div>}
</div>
)
}
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '../base/app-icon'
const DatasetSvg = <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" clipRule="evenodd" d="M0.833497 5.13481C0.833483 4.69553 0.83347 4.31654 0.858973 4.0044C0.88589 3.67495 0.94532 3.34727 1.10598 3.03195C1.34567 2.56155 1.72812 2.17909 2.19852 1.93941C2.51384 1.77875 2.84152 1.71932 3.17097 1.6924C3.48312 1.6669 3.86209 1.66691 4.30137 1.66693L7.62238 1.66684C8.11701 1.66618 8.55199 1.66561 8.95195 1.80356C9.30227 1.92439 9.62134 2.12159 9.88607 2.38088C10.1883 2.67692 10.3823 3.06624 10.603 3.50894L11.3484 5.00008H14.3679C15.0387 5.00007 15.5924 5.00006 16.0434 5.03691C16.5118 5.07518 16.9424 5.15732 17.3468 5.36339C17.974 5.68297 18.4839 6.19291 18.8035 6.82011C19.0096 7.22456 19.0917 7.65515 19.13 8.12356C19.1668 8.57455 19.1668 9.12818 19.1668 9.79898V13.5345C19.1668 14.2053 19.1668 14.7589 19.13 15.2099C19.0917 15.6784 19.0096 16.1089 18.8035 16.5134C18.4839 17.1406 17.974 17.6505 17.3468 17.9701C16.9424 18.1762 16.5118 18.2583 16.0434 18.2966C15.5924 18.3334 15.0387 18.3334 14.3679 18.3334H5.63243C4.96163 18.3334 4.40797 18.3334 3.95698 18.2966C3.48856 18.2583 3.05798 18.1762 2.65353 17.9701C2.02632 17.6505 1.51639 17.1406 1.19681 16.5134C0.990734 16.1089 0.908597 15.6784 0.870326 15.2099C0.833478 14.7589 0.833487 14.2053 0.833497 13.5345V5.13481ZM7.51874 3.33359C8.17742 3.33359 8.30798 3.34447 8.4085 3.37914C8.52527 3.41942 8.63163 3.48515 8.71987 3.57158C8.79584 3.64598 8.86396 3.7579 9.15852 4.34704L9.48505 5.00008L2.50023 5.00008C2.50059 4.61259 2.50314 4.34771 2.5201 4.14012C2.5386 3.91374 2.57 3.82981 2.59099 3.7886C2.67089 3.6318 2.79837 3.50432 2.95517 3.42442C2.99638 3.40343 3.08031 3.37203 3.30669 3.35353C3.54281 3.33424 3.85304 3.33359 4.3335 3.33359H7.51874Z" fill="#444CE7" />
</svg>
type Props = {
isExternal?: boolean
name: string
description: string
expand: boolean
extraInfo?: React.ReactNode
}
const DatasetInfo: FC<Props> = ({
name,
description,
isExternal,
expand,
extraInfo,
}) => {
const { t } = useTranslation()
return (
<div className='pl-1 pt-1'>
<div className='mr-3 shrink-0'>
<AppIcon innerIcon={DatasetSvg} className='!border-[0.5px] !border-indigo-100 !bg-indigo-25' />
</div>
{expand && (
<div className='mt-2'>
<div className='system-md-semibold text-text-secondary'>
{name}
</div>
<div className='system-2xs-medium-uppercase mt-1 text-text-tertiary'>{isExternal ? t('dataset.externalTag') : t('dataset.localDocs')}</div>
<div className='system-xs-regular my-3 text-text-tertiary first-letter:capitalize'>{description}</div>
</div>
)}
{extraInfo}
</div>
)
}
export default React.memo(DatasetInfo)
import React, { useEffect } from 'react'
import { useShallow } from 'zustand/react/shallow'
import { RiLayoutRight2Line } from '@remixicon/react'
import { LayoutRight2LineMod } from '../base/icons/src/public/knowledge'
import NavLink from './navLink'
import type { NavIcon } from './navLink'
import AppBasic from './basic'
import AppInfo from './app-info'
import DatasetInfo from './dataset-info'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { useStore as useAppStore } from '@/app/components/app/store'
import cn from '@/utils/classnames'
export type IAppDetailNavProps = {
iconType?: 'app' | 'dataset' | 'notion'
title: string
desc: string
isExternal?: boolean
icon: string
icon_background: string
navigation: Array<{
name: string
href: string
icon: NavIcon
selectedIcon: NavIcon
}>
extraInfo?: (modeState: string) => React.ReactNode
}
const AppDetailNav = ({ title, desc, isExternal, icon, icon_background, navigation, extraInfo, iconType = 'app' }: IAppDetailNavProps) => {
const { appSidebarExpand, setAppSiderbarExpand } = useAppStore(useShallow(state => ({
appSidebarExpand: state.appSidebarExpand,
setAppSiderbarExpand: state.setAppSiderbarExpand,
})))
const media = useBreakpoints()
const isMobile = media === MediaType.mobile
const expand = appSidebarExpand === 'expand'
const handleToggle = (state: string) => {
setAppSiderbarExpand(state === 'expand' ? 'collapse' : 'expand')
}
useEffect(() => {
if (appSidebarExpand) {
localStorage.setItem('app-detail-collapse-or-expand', appSidebarExpand)
setAppSiderbarExpand(appSidebarExpand)
}
}, [appSidebarExpand, setAppSiderbarExpand])
return (
<div
className={`
flex shrink-0 flex-col border-r border-divider-burn bg-background-default-subtle transition-all
${expand ? 'w-[216px]' : 'w-14'}
`}
>
<div
className={`
shrink-0
${expand ? 'p-2' : 'p-1'}
`}
>
{iconType === 'app' && (
<AppInfo expand={expand} />
)}
{iconType === 'dataset' && (
<DatasetInfo
name={title}
description={desc}
isExternal={isExternal}
expand={expand}
extraInfo={extraInfo && extraInfo(appSidebarExpand)}
/>
)}
{!['app', 'dataset'].includes(iconType) && (
<AppBasic
mode={appSidebarExpand}
iconType={iconType}
icon={icon}
icon_background={icon_background}
name={title}
type={desc}
isExternal={isExternal}
/>
)}
</div>
<div className='px-4'>
<div className={cn('mx-auto mt-1 h-[1px] bg-divider-subtle', !expand && 'w-6')} />
</div>
<nav
className={`
grow space-y-1
${expand ? 'p-4' : 'px-2.5 py-4'}
`}
>
{navigation.map((item, index) => {
return (
<NavLink key={index} mode={appSidebarExpand} iconMap={{ selected: item.selectedIcon, normal: item.icon }} name={item.name} href={item.href} />
)
})}
</nav>
{
!isMobile && (
<div
className={`
shrink-0 py-3
${expand ? 'px-6' : 'px-4'}
`}
>
<div
className='flex h-6 w-6 cursor-pointer items-center justify-center text-gray-500'
onClick={() => handleToggle(appSidebarExpand)}
>
{
expand
? <RiLayoutRight2Line className='h-5 w-5 text-components-menu-item-text' />
: <LayoutRight2LineMod className='h-5 w-5 text-components-menu-item-text' />
}
</div>
</div>
)
}
</div>
)
}
export default React.memo(AppDetailNav)
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
import Link from 'next/link'
import classNames from '@/utils/classnames'
import type { RemixiconComponentType } from '@remixicon/react'
export type NavIcon = React.ComponentType<
React.PropsWithoutRef<React.ComponentProps<'svg'>> & {
title?: string | undefined
titleId?: string | undefined
}> | RemixiconComponentType
export type NavLinkProps = {
name: string
href: string
iconMap: {
selected: NavIcon
normal: NavIcon
}
mode?: string
}
export default function NavLink({
name,
href,
iconMap,
mode = 'expand',
}: NavLinkProps) {
const segment = useSelectedLayoutSegment()
const formattedSegment = (() => {
let res = segment?.toLowerCase()
// logs and annotations use the same nav
if (res === 'annotations')
res = 'logs'
return res
})()
const isActive = href.toLowerCase().split('/')?.pop() === formattedSegment
const NavIcon = isActive ? iconMap.selected : iconMap.normal
return (
<Link
key={name}
href={href}
className={classNames(
isActive ? 'bg-state-accent-active text-text-accent font-semibold' : 'text-components-menu-item-text hover:bg-state-base-hover hover:text-components-menu-item-text-hover',
'group flex items-center h-9 rounded-md py-2 text-sm font-normal',
mode === 'expand' ? 'px-3' : 'px-2.5',
)}
title={mode === 'collapse' ? name : ''}
>
<NavIcon
className={classNames(
'h-4 w-4 flex-shrink-0',
mode === 'expand' ? 'mr-2' : 'mr-0',
)}
aria-hidden="true"
/>
{mode === 'expand' && name}
</Link>
)
}
.sidebar {
border-right: 1px solid #F3F4F6;
}
.completionPic {
background-image: url('./completion.png')
}
.expertPic {
background-image: url('./expert.png')
}
\ No newline at end of file
'use client'
import type { FC, SVGProps } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
const ThreeDotsIcon = ({ className }: SVGProps<SVGElement>) => {
return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
<path d="M5 6.5V5M8.93934 7.56066L10 6.5M10.0103 11.5H11.5103" stroke="#374151" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
}
const EmptyElement: FC = () => {
const { t } = useTranslation()
return (
<div className='flex h-full items-center justify-center'>
<div className='box-border h-fit w-[560px] rounded-2xl bg-background-section-burn px-5 py-4'>
<span className='system-md-semibold text-text-secondary'>{t('appAnnotation.noData.title')}<ThreeDotsIcon className='relative -left-1.5 -top-3 inline' /></span>
<div className='system-sm-regular mt-2 text-text-tertiary'>
{t('appAnnotation.noData.description')}
</div>
</div>
</div>
)
}
export default React.memo(EmptyElement)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import useSWR from 'swr'
import Input from '@/app/components/base/input'
import { fetchAnnotationsCount } from '@/service/log'
export type QueryParam = {
keyword?: string
}
type IFilterProps = {
appId: string
queryParams: QueryParam
setQueryParams: (v: QueryParam) => void
children: React.JSX.Element
}
const Filter: FC<IFilterProps> = ({
appId,
queryParams,
setQueryParams,
children,
}) => {
// TODO: change fetch list api
const { data } = useSWR({ url: `/apps/${appId}/annotations/count` }, fetchAnnotationsCount)
const { t } = useTranslation()
if (!data)
return null
return (
<div className='mb-2 flex flex-row flex-wrap items-center justify-between gap-2'>
<Input
wrapperClassName='w-[200px]'
showLeftIcon
showClearIcon
value={queryParams.keyword}
placeholder={t('common.operation.search')!}
onChange={(e) => {
setQueryParams({ ...queryParams, keyword: e.target.value })
}}
onClear={() => setQueryParams({ ...queryParams, keyword: '' })}
/>
{children}
</div>
)
}
export default React.memo(Filter)
'use client'
import type { FC } from 'react'
import React, { Fragment, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiAddLine,
RiMoreFill,
} from '@remixicon/react'
import { useContext } from 'use-context-selector'
import {
useCSVDownloader,
} from 'react-papaparse'
import { Menu, MenuButton, MenuItems, Transition } from '@headlessui/react'
import Button from '../../../base/button'
import AddAnnotationModal from '../add-annotation-modal'
import type { AnnotationItemBasic } from '../type'
import BatchAddModal from '../batch-add-annotation-modal'
import cn from '@/utils/classnames'
import CustomPopover from '@/app/components/base/popover'
import { FileDownload02, FilePlus02 } from '@/app/components/base/icons/src/vender/line/files'
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
import I18n from '@/context/i18n'
import { fetchExportAnnotationList } from '@/service/annotation'
import { LanguagesSupported } from '@/i18n/language'
const CSV_HEADER_QA_EN = ['Question', 'Answer']
const CSV_HEADER_QA_CN = ['问题', '答案']
type Props = {
appId: string
onAdd: (payload: AnnotationItemBasic) => void
onAdded: () => void
controlUpdateList: number
}
const HeaderOptions: FC<Props> = ({
appId,
onAdd,
onAdded,
controlUpdateList,
}) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const { CSVDownloader, Type } = useCSVDownloader()
const [list, setList] = useState<AnnotationItemBasic[]>([])
const annotationUnavailable = list.length === 0
const listTransformer = (list: AnnotationItemBasic[]) => list.map(
(item: AnnotationItemBasic) => {
const dataString = `{"messages": [{"role": "system", "content": ""}, {"role": "user", "content": ${JSON.stringify(item.question)}}, {"role": "assistant", "content": ${JSON.stringify(item.answer)}}]}`
return dataString
},
)
const JSONLOutput = () => {
const a = document.createElement('a')
const content = listTransformer(list).join('\n')
const file = new Blob([content], { type: 'application/jsonl' })
a.href = URL.createObjectURL(file)
a.download = `annotations-${locale}.jsonl`
a.click()
}
const fetchList = async () => {
const { data }: any = await fetchExportAnnotationList(appId)
setList(data as AnnotationItemBasic[])
}
useEffect(() => {
fetchList()
}, [])
useEffect(() => {
if (controlUpdateList)
fetchList()
}, [controlUpdateList])
const [showBulkImportModal, setShowBulkImportModal] = useState(false)
const Operations = () => {
return (
<div className="w-full py-1">
<button className='mx-1 flex h-9 w-[calc(100%_-_8px)] cursor-pointer items-center space-x-2 rounded-lg px-3 py-2 hover:bg-components-panel-on-panel-item-bg-hover disabled:opacity-50' onClick={() => {
setShowBulkImportModal(true)
}}>
<FilePlus02 className='h-4 w-4 text-text-tertiary' />
<span className='system-sm-regular grow text-left text-text-secondary'>{t('appAnnotation.table.header.bulkImport')}</span>
</button>
<Menu as="div" className="relative h-full w-full">
<MenuButton className='mx-1 flex h-9 w-[calc(100%_-_8px)] cursor-pointer items-center space-x-2 rounded-lg px-3 py-2 hover:bg-components-panel-on-panel-item-bg-hover disabled:opacity-50'>
<FileDownload02 className='h-4 w-4 text-text-tertiary' />
<span className='system-sm-regular grow text-left text-text-secondary'>{t('appAnnotation.table.header.bulkExport')}</span>
<ChevronRight className='h-[14px] w-[14px] shrink-0 text-text-tertiary' />
</MenuButton>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<MenuItems
className={cn(
'absolute left-1 top-[1px] z-10 min-w-[100px] origin-top-right -translate-x-full rounded-xl border-[0.5px] border-components-panel-on-panel-item-bg bg-components-panel-bg py-1 shadow-xs',
)}
>
<CSVDownloader
type={Type.Link}
filename={`annotations-${locale}`}
bom={true}
data={[
locale !== LanguagesSupported[1] ? CSV_HEADER_QA_EN : CSV_HEADER_QA_CN,
...list.map(item => [item.question, item.answer]),
]}
>
<button disabled={annotationUnavailable} className='mx-1 flex h-9 w-[calc(100%_-_8px)] cursor-pointer items-center space-x-2 rounded-lg px-3 py-2 hover:bg-components-panel-on-panel-item-bg-hover disabled:opacity-50'>
<span className='system-sm-regular grow text-left text-text-secondary'>CSV</span>
</button>
</CSVDownloader>
<button disabled={annotationUnavailable} className={cn('mx-1 flex h-9 w-[calc(100%_-_8px)] cursor-pointer items-center space-x-2 rounded-lg px-3 py-2 hover:bg-components-panel-on-panel-item-bg-hover disabled:opacity-50', '!border-0')} onClick={JSONLOutput}>
<span className='system-sm-regular grow text-left text-text-secondary'>JSONL</span>
</button>
</MenuItems>
</Transition>
</Menu>
</div>
)
}
const [showAddModal, setShowAddModal] = React.useState(false)
return (
<div className='flex space-x-2'>
<Button variant='primary' onClick={() => setShowAddModal(true)}>
<RiAddLine className='mr-0.5 h-4 w-4' />
<div>{t('appAnnotation.table.header.addAnnotation')}</div>
</Button>
<CustomPopover
htmlContent={<Operations />}
position="br"
trigger="click"
btnElement={
<Button variant='secondary' className='w-8 p-0'>
<RiMoreFill className='h-4 w-4' />
</Button>
}
btnClassName='p-0 border-0'
className={'!z-20 h-fit !w-[155px]'}
popupClassName='!w-full !overflow-visible'
manualClose
/>
{showAddModal && (
<AddAnnotationModal
isShow={showAddModal}
onHide={() => setShowAddModal(false)}
onAdd={onAdd}
/>
)}
{
showBulkImportModal && (
<BatchAddModal
appId={appId}
isShow={showBulkImportModal}
onCancel={() => setShowBulkImportModal(false)}
onAdded={onAdded}
/>
)
}
</div>
)
}
export default React.memo(HeaderOptions)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { RiDeleteBinLine, RiEditLine } from '@remixicon/react'
import type { AnnotationItem } from './type'
import RemoveAnnotationConfirmModal from './remove-annotation-confirm-modal'
import ActionButton from '@/app/components/base/action-button'
import useTimestamp from '@/hooks/use-timestamp'
import cn from '@/utils/classnames'
type Props = {
list: AnnotationItem[]
onRemove: (id: string) => void
onView: (item: AnnotationItem) => void
}
const List: FC<Props> = ({
list,
onView,
onRemove,
}) => {
const { t } = useTranslation()
const { formatTime } = useTimestamp()
const [currId, setCurrId] = React.useState<string | null>(null)
const [showConfirmDelete, setShowConfirmDelete] = React.useState(false)
return (
<div className='overflow-x-auto'>
<table className={cn('mt-2 w-full min-w-[440px] border-collapse border-0')}>
<thead className='system-xs-medium-uppercase text-text-tertiary'>
<tr>
<td className='w-5 whitespace-nowrap rounded-l-lg bg-background-section-burn pl-2 pr-1'>{t('appAnnotation.table.header.question')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.table.header.answer')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.table.header.createdAt')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.table.header.hits')}</td>
<td className='w-[96px] whitespace-nowrap rounded-r-lg bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.table.header.actions')}</td>
</tr>
</thead>
<tbody className="system-sm-regular text-text-secondary">
{list.map(item => (
<tr
key={item.id}
className='cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover'
onClick={
() => {
onView(item)
}
}
>
<td
className='max-w-[250px] overflow-hidden text-ellipsis whitespace-nowrap p-3 pr-2'
title={item.question}
>{item.question}</td>
<td
className='max-w-[250px] overflow-hidden text-ellipsis whitespace-nowrap p-3 pr-2'
title={item.answer}
>{item.answer}</td>
<td className='p-3 pr-2'>{formatTime(item.created_at, t('appLog.dateTimeFormat') as string)}</td>
<td className='p-3 pr-2'>{item.hit_count}</td>
<td className='w-[96px] p-3 pr-2' onClick={e => e.stopPropagation()}>
{/* Actions */}
<div className='flex space-x-1 text-text-tertiary'>
<ActionButton onClick={() => onView(item)}>
<RiEditLine className='h-4 w-4' />
</ActionButton>
<ActionButton
onClick={() => {
setCurrId(item.id)
setShowConfirmDelete(true)
}}
>
<RiDeleteBinLine className='h-4 w-4' />
</ActionButton>
</div>
</td>
</tr>
))}
</tbody>
</table>
<RemoveAnnotationConfirmModal
isShow={showConfirmDelete}
onHide={() => setShowConfirmDelete(false)}
onRemove={() => {
onRemove(currId as string)
setShowConfirmDelete(false)
}}
/>
</div>
)
}
export default React.memo(List)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import Confirm from '@/app/components/base/confirm'
type Props = {
isShow: boolean
onHide: () => void
onRemove: () => void
}
const RemoveAnnotationConfirmModal: FC<Props> = ({
isShow,
onHide,
onRemove,
}) => {
const { t } = useTranslation()
return (
<Confirm
isShow={isShow}
onCancel={onHide}
onConfirm={onRemove}
title={t('appDebug.feature.annotation.removeConfirm')}
/>
)
}
export default React.memo(RemoveAnnotationConfirmModal)
export type AnnotationItemBasic = {
message_id?: string
question: string
answer: string
}
export type AnnotationItem = {
id: string
question: string
answer: string
created_at: number
hit_count: number
}
export type HitHistoryItem = {
id: string
question: string
match: string
response: string
source: string
score: number
created_at: number
}
export type EmbeddingModelConfig = {
embedding_provider_name: string
embedding_model_name: string
}
export enum AnnotationEnableStatus {
enable = 'enable',
disable = 'disable',
}
export enum JobStatus {
waiting = 'waiting',
processing = 'processing',
completed = 'completed',
}
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { ClockFastForward } from '@/app/components/base/icons/src/vender/line/time'
const HitHistoryNoData: FC = () => {
const { t } = useTranslation()
return (
<div className='mx-auto mt-20 w-[480px] space-y-2 rounded-2xl bg-background-section-burn p-5'>
<div className='inline-block rounded-lg border border-divider-subtle p-3'>
<ClockFastForward className='h-5 w-5 text-text-tertiary' />
</div>
<div className='system-sm-regular text-text-tertiary'>{t('appAnnotation.viewModal.noHitHistory')}</div>
</div>
)
}
export default React.memo(HitHistoryNoData)
'use client'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import EditItem, { EditItemType } from '../edit-annotation-modal/edit-item'
import type { AnnotationItem, HitHistoryItem } from '../type'
import HitHistoryNoData from './hit-history-no-data'
import Badge from '@/app/components/base/badge'
import Drawer from '@/app/components/base/drawer-plus'
import Pagination from '@/app/components/base/pagination'
import { MessageCheckRemove } from '@/app/components/base/icons/src/vender/line/communication'
import Confirm from '@/app/components/base/confirm'
import TabSlider from '@/app/components/base/tab-slider-plain'
import { fetchHitHistoryList } from '@/service/annotation'
import { APP_PAGE_LIMIT } from '@/config'
import useTimestamp from '@/hooks/use-timestamp'
import cn from '@/utils/classnames'
type Props = {
appId: string
isShow: boolean
onHide: () => void
item: AnnotationItem
onSave: (editedQuery: string, editedAnswer: string) => void
onRemove: () => void
}
enum TabType {
annotation = 'annotation',
hitHistory = 'hitHistory',
}
const ViewAnnotationModal: FC<Props> = ({
appId,
isShow,
onHide,
item,
onSave,
onRemove,
}) => {
const { id, question, answer, created_at: createdAt } = item
const [newQuestion, setNewQuery] = useState(question)
const [newAnswer, setNewAnswer] = useState(answer)
const { t } = useTranslation()
const { formatTime } = useTimestamp()
const [currPage, setCurrPage] = React.useState<number>(0)
const [total, setTotal] = useState(0)
const [hitHistoryList, setHitHistoryList] = useState<HitHistoryItem[]>([])
const fetchHitHistory = async (page = 1) => {
try {
const { data, total }: any = await fetchHitHistoryList(appId, id, {
page,
limit: 10,
})
setHitHistoryList(data as HitHistoryItem[])
setTotal(total)
}
catch (e) {
}
}
useEffect(() => {
fetchHitHistory(currPage + 1)
}, [currPage])
const tabs = [
{ value: TabType.annotation, text: t('appAnnotation.viewModal.annotatedResponse') },
{
value: TabType.hitHistory,
text: (
hitHistoryList.length > 0
? (
<div className='flex items-center space-x-1'>
<div>{t('appAnnotation.viewModal.hitHistory')}</div>
<Badge
text={`${total} ${t(`appAnnotation.viewModal.hit${hitHistoryList.length > 1 ? 's' : ''}`)}`}
/>
</div>
)
: t('appAnnotation.viewModal.hitHistory')
),
},
]
const [activeTab, setActiveTab] = useState(TabType.annotation)
const handleSave = (type: EditItemType, editedContent: string) => {
if (type === EditItemType.Query) {
setNewQuery(editedContent)
onSave(editedContent, newAnswer)
}
else {
setNewAnswer(editedContent)
onSave(newQuestion, editedContent)
}
}
const [showModal, setShowModal] = useState(false)
const annotationTab = (
<>
<EditItem
type={EditItemType.Query}
content={question}
onSave={editedContent => handleSave(EditItemType.Query, editedContent)}
/>
<EditItem
type={EditItemType.Answer}
content={answer}
onSave={editedContent => handleSave(EditItemType.Answer, editedContent)}
/>
</>
)
const hitHistoryTab = total === 0
? (<HitHistoryNoData />)
: (
<div>
<table className={cn('w-full min-w-[440px] border-collapse border-0')} >
<thead className="system-xs-medium-uppercase text-text-tertiary">
<tr>
<td className='w-5 whitespace-nowrap rounded-l-lg bg-background-section-burn pl-2 pr-1'>{t('appAnnotation.hitHistoryTable.query')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.hitHistoryTable.match')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.hitHistoryTable.response')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.hitHistoryTable.source')}</td>
<td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.hitHistoryTable.score')}</td>
<td className='w-[160px] whitespace-nowrap rounded-r-lg bg-background-section-burn py-1.5 pl-3'>{t('appAnnotation.hitHistoryTable.time')}</td>
</tr>
</thead>
<tbody className="system-sm-regular text-text-secondary">
{hitHistoryList.map(item => (
<tr
key={item.id}
className={'cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover'}
>
<td
className='max-w-[250px] overflow-hidden text-ellipsis whitespace-nowrap p-3 pr-2'
title={item.question}
>{item.question}</td>
<td
className='max-w-[250px] overflow-hidden text-ellipsis whitespace-nowrap p-3 pr-2'
title={item.match}
>{item.match}</td>
<td
className='max-w-[250px] overflow-hidden text-ellipsis whitespace-nowrap p-3 pr-2'
title={item.response}
>{item.response}</td>
<td className='p-3 pr-2'>{item.source}</td>
<td className='p-3 pr-2'>{item.score ? item.score.toFixed(2) : '-'}</td>
<td className='p-3 pr-2'>{formatTime(item.created_at, t('appLog.dateTimeFormat') as string)}</td>
</tr>
))}
</tbody>
</table>
{(total && total > APP_PAGE_LIMIT)
? <Pagination
className='px-0'
current={currPage}
onChange={setCurrPage}
total={total}
/>
: null}
</div>
)
return (
<div>
<Drawer
isShow={isShow}
onHide={onHide}
maxWidthClassName='!max-w-[800px]'
title={
<TabSlider
className='relative top-[9px] shrink-0'
value={activeTab}
onChange={v => setActiveTab(v as TabType)}
options={tabs}
noBorderBottom
itemClassName='!pb-3.5'
/>
}
body={(
<div>
<div className='space-y-6 p-6 pb-4'>
{activeTab === TabType.annotation ? annotationTab : hitHistoryTab}
</div>
<Confirm
isShow={showModal}
onCancel={() => setShowModal(false)}
onConfirm={async () => {
await onRemove()
setShowModal(false)
onHide()
}}
title={t('appDebug.feature.annotation.removeConfirm')}
/>
</div>
)}
foot={id
? (
<div className='system-sm-medium flex h-16 items-center justify-between rounded-bl-xl rounded-br-xl border-t border-divider-subtle bg-background-section-burn px-4 text-text-tertiary'>
<div
className='flex cursor-pointer items-center space-x-2 pl-3'
onClick={() => setShowModal(true)}
>
<MessageCheckRemove />
<div>{t('appAnnotation.editModal.removeThisCache')}</div>
</div>
<div>{t('appAnnotation.editModal.createdAt')}&nbsp;{formatTime(createdAt, t('appLog.dateTimeFormat') as string)}</div>
</div>
)
: undefined}
/>
</div>
)
}
export default React.memo(ViewAnnotationModal)
import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import produce from 'immer'
import type { AppPublisherProps } from '@/app/components/app/app-publisher'
import Confirm from '@/app/components/base/confirm'
import AppPublisher from '@/app/components/app/app-publisher'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import type { ModelAndParameter } from '@/app/components/app/configuration/debug/types'
import type { FileUpload } from '@/app/components/base/features/types'
import { Resolution } from '@/types/app'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
type Props = Omit<AppPublisherProps, 'onPublish'> & {
onPublish?: (modelAndParameter?: ModelAndParameter, features?: any) => Promise<any> | any
publishedConfig?: any
resetAppConfig?: () => void
}
const FeaturesWrappedAppPublisher = (props: Props) => {
const { t } = useTranslation()
const features = useFeatures(s => s.features)
const featuresStore = useFeaturesStore()
const [restoreConfirmOpen, setRestoreConfirmOpen] = useState(false)
const handleConfirm = useCallback(() => {
props.resetAppConfig?.()
const {
features,
setFeatures,
} = featuresStore!.getState()
const newFeatures = produce(features, (draft) => {
draft.moreLikeThis = props.publishedConfig.modelConfig.more_like_this || { enabled: false }
draft.opening = {
enabled: !!props.publishedConfig.modelConfig.opening_statement,
opening_statement: props.publishedConfig.modelConfig.opening_statement || '',
suggested_questions: props.publishedConfig.modelConfig.suggested_questions || [],
}
draft.moderation = props.publishedConfig.modelConfig.sensitive_word_avoidance || { enabled: false }
draft.speech2text = props.publishedConfig.modelConfig.speech_to_text || { enabled: false }
draft.text2speech = props.publishedConfig.modelConfig.text_to_speech || { enabled: false }
draft.suggested = props.publishedConfig.modelConfig.suggested_questions_after_answer || { enabled: false }
draft.citation = props.publishedConfig.modelConfig.retriever_resource || { enabled: false }
draft.annotationReply = props.publishedConfig.modelConfig.annotation_reply || { enabled: false }
draft.file = {
image: {
detail: props.publishedConfig.modelConfig.file_upload?.image?.detail || Resolution.high,
enabled: !!props.publishedConfig.modelConfig.file_upload?.image?.enabled,
number_limits: props.publishedConfig.modelConfig.file_upload?.image?.number_limits || 3,
transfer_methods: props.publishedConfig.modelConfig.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
},
enabled: !!(props.publishedConfig.modelConfig.file_upload?.enabled || props.publishedConfig.modelConfig.file_upload?.image?.enabled),
allowed_file_types: props.publishedConfig.modelConfig.file_upload?.allowed_file_types || [SupportUploadFileTypes.image],
allowed_file_extensions: props.publishedConfig.modelConfig.file_upload?.allowed_file_extensions || FILE_EXTS[SupportUploadFileTypes.image].map(ext => `.${ext}`),
allowed_file_upload_methods: props.publishedConfig.modelConfig.file_upload?.allowed_file_upload_methods || props.publishedConfig.modelConfig.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
number_limits: props.publishedConfig.modelConfig.file_upload?.number_limits || props.publishedConfig.modelConfig.file_upload?.image?.number_limits || 3,
} as FileUpload
})
setFeatures(newFeatures)
setRestoreConfirmOpen(false)
}, [featuresStore, props])
const handlePublish = useCallback((modelAndParameter?: ModelAndParameter) => {
return props.onPublish?.(modelAndParameter, features)
}, [features, props])
return (
<>
<AppPublisher {...{
...props,
onPublish: handlePublish,
onRestore: () => setRestoreConfirmOpen(true),
}}/>
{restoreConfirmOpen && (
<Confirm
title={t('appDebug.resetConfig.title')}
content={t('appDebug.resetConfig.message')}
isShow={restoreConfirmOpen}
onConfirm={handleConfirm}
onCancel={() => setRestoreConfirmOpen(false)}
/>
)}
</>
)
}
export default FeaturesWrappedAppPublisher
import type { FC } from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiArrowDownSLine } from '@remixicon/react'
import type { ModelAndParameter } from '../configuration/debug/types'
import ModelIcon from '../../header/account-setting/model-provider-page/model-icon'
import Button from '@/app/components/base/button'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { useProviderContext } from '@/context/provider-context'
import type { Model, ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
type PublishWithMultipleModelProps = {
multipleModelConfigs: ModelAndParameter[]
// textGenerationModelList?: Model[]
onSelect: (v: ModelAndParameter) => void
}
const PublishWithMultipleModel: FC<PublishWithMultipleModelProps> = ({
multipleModelConfigs,
// textGenerationModelList = [],
onSelect,
}) => {
const { t } = useTranslation()
const language = useLanguage()
const { textGenerationModelList } = useProviderContext()
const [open, setOpen] = useState(false)
const validModelConfigs: (ModelAndParameter & { modelItem: ModelItem; providerItem: Model })[] = []
multipleModelConfigs.forEach((item) => {
const provider = textGenerationModelList.find(model => model.provider === item.provider)
if (provider) {
const model = provider.models.find(model => model.model === item.model)
if (model) {
validModelConfigs.push({
id: item.id,
model: item.model,
provider: item.provider,
modelItem: model,
providerItem: provider,
parameters: item.parameters,
})
}
}
})
const handleToggle = () => {
if (validModelConfigs.length)
setOpen(v => !v)
}
const handleSelect = (item: ModelAndParameter) => {
onSelect(item)
setOpen(false)
}
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-end'
>
<PortalToFollowElemTrigger className='w-full' onClick={handleToggle}>
<Button
variant='primary'
disabled={!validModelConfigs.length}
className='mt-3 w-full'
>
{t('appDebug.operation.applyConfig')}
<RiArrowDownSLine className='ml-0.5 h-3 w-3' />
</Button>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-50 mt-1 w-[288px]'>
<div className='rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg p-1 shadow-lg'>
<div className='flex h-[22px] items-center px-3 text-xs font-medium text-text-tertiary'>
{t('appDebug.publishAs')}
</div>
{
validModelConfigs.map((item, index) => (
<div
key={item.id}
className='flex h-8 cursor-pointer items-center rounded-lg px-3 text-sm text-text-tertiary hover:bg-state-base-hover'
onClick={() => handleSelect(item)}
>
<span className='min-w-[18px] italic'>#{index + 1}</span>
<ModelIcon modelName={item.model} provider={item.providerItem} className='ml-2' />
<div
className='ml-1 truncate text-text-secondary'
title={item.modelItem.label[language]}
>
{item.modelItem.label[language]}
</div>
</div>
))
}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default PublishWithMultipleModel
import type { HTMLProps, PropsWithChildren } from 'react'
import { RiArrowRightUpLine } from '@remixicon/react'
import classNames from '@/utils/classnames'
export type SuggestedActionProps = PropsWithChildren<HTMLProps<HTMLAnchorElement> & {
icon?: React.ReactNode
link?: string
disabled?: boolean
}>
const SuggestedAction = ({ icon, link, disabled, children, className, ...props }: SuggestedActionProps) => (
<a
href={disabled ? undefined : link}
target='_blank'
rel='noreferrer'
className={classNames(
'flex justify-start items-center gap-2 py-2 px-2.5 bg-background-section-burn rounded-lg transition-colors [&:not(:first-child)]:mt-1',
disabled ? 'shadow-xs opacity-30 cursor-not-allowed' : 'text-text-secondary hover:bg-state-accent-hover hover:text-text-accent cursor-pointer',
className,
)}
{...props}
>
<div className='relative h-4 w-4'>{icon}</div>
<div className='system-sm-medium shrink grow basis-0'>{children}</div>
<RiArrowRightUpLine className='h-3.5 w-3.5' />
</a>
)
export default SuggestedAction
import React, { type FC, useCallback, useState } from 'react'
import Modal from '@/app/components/base/modal'
import type { VersionHistory } from '@/types/workflow'
import { useTranslation } from 'react-i18next'
import { RiCloseLine } from '@remixicon/react'
import Input from '../../base/input'
import Textarea from '../../base/textarea'
import Button from '../../base/button'
import Toast from '@/app/components/base/toast'
type VersionInfoModalProps = {
isOpen: boolean
versionInfo?: VersionHistory
onClose: () => void
onPublish: (params: { title: string; releaseNotes: string; id?: string }) => void
}
const TITLE_MAX_LENGTH = 15
const RELEASE_NOTES_MAX_LENGTH = 100
const VersionInfoModal: FC<VersionInfoModalProps> = ({
isOpen,
versionInfo,
onClose,
onPublish,
}) => {
const { t } = useTranslation()
const [title, setTitle] = useState(versionInfo?.marked_name || '')
const [releaseNotes, setReleaseNotes] = useState(versionInfo?.marked_comment || '')
const [titleError, setTitleError] = useState(false)
const [releaseNotesError, setReleaseNotesError] = useState(false)
const handlePublish = () => {
if (title.length > TITLE_MAX_LENGTH) {
setTitleError(true)
Toast.notify({
type: 'error',
message: t('workflow.versionHistory.editField.titleLengthLimit', { limit: TITLE_MAX_LENGTH }),
})
return
}
else {
titleError && setTitleError(false)
}
if (releaseNotes.length > RELEASE_NOTES_MAX_LENGTH) {
setReleaseNotesError(true)
Toast.notify({
type: 'error',
message: t('workflow.versionHistory.editField.releaseNotesLengthLimit', { limit: RELEASE_NOTES_MAX_LENGTH }),
})
return
}
else {
releaseNotesError && setReleaseNotesError(false)
}
onPublish({ title, releaseNotes, id: versionInfo?.id })
onClose()
}
const handleTitleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setTitle(e.target.value)
}, [])
const handleDescriptionChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setReleaseNotes(e.target.value)
}, [])
return <Modal className='p-0' isShow={isOpen} onClose={onClose}>
<div className='relative w-full p-6 pb-4 pr-14'>
<div className='title-2xl-semi-bold text-text-primary first-letter:capitalize'>
{versionInfo?.marked_name ? t('workflow.versionHistory.editVersionInfo') : t('workflow.versionHistory.nameThisVersion')}
</div>
<div className='absolute right-5 top-5 flex h-8 w-8 cursor-pointer items-center justify-center p-1.5' onClick={onClose}>
<RiCloseLine className='h-[18px] w-[18px] text-text-tertiary' />
</div>
</div>
<div className='flex flex-col gap-y-4 px-6 py-3'>
<div className='flex flex-col gap-y-1'>
<div className='system-sm-semibold flex h-6 items-center text-text-secondary'>
{t('workflow.versionHistory.editField.title')}
</div>
<Input
value={title}
placeholder={`${t('workflow.versionHistory.nameThisVersion')}${t('workflow.panel.optional')}`}
onChange={handleTitleChange}
destructive={titleError}
/>
</div>
<div className='flex flex-col gap-y-1'>
<div className='system-sm-semibold flex h-6 items-center text-text-secondary'>
{t('workflow.versionHistory.editField.releaseNotes')}
</div>
<Textarea
value={releaseNotes}
placeholder={`${t('workflow.versionHistory.releaseNotesPlaceholder')}${t('workflow.panel.optional')}`}
onChange={handleDescriptionChange}
destructive={releaseNotesError}
/>
</div>
</div>
<div className='flex justify-end p-6 pt-5'>
<div className='flex items-center gap-x-3'>
<Button onClick={onClose}>{t('common.operation.cancel')}</Button>
<Button variant='primary' onClick={handlePublish}>{t('workflow.common.publish')}</Button>
</div>
</div>
</Modal>
}
export default VersionInfoModal
'use client'
import type { FC } from 'react'
import React from 'react'
const MoreLikeThisIcon: FC = () => {
return (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" clipRule="evenodd" d="M5.83914 0.666748H10.1609C10.6975 0.666741 11.1404 0.666734 11.5012 0.696212C11.8759 0.726829 12.2204 0.792538 12.544 0.957399C13.0457 1.21306 13.4537 1.62101 13.7093 2.12277C13.8742 2.44633 13.9399 2.7908 13.9705 3.16553C14 3.52633 14 3.96923 14 4.50587V7.41171C14 7.62908 14 7.73776 13.9652 7.80784C13.9303 7.87806 13.8939 7.91566 13.8249 7.95288C13.756 7.99003 13.6262 7.99438 13.3665 8.00307C12.8879 8.01909 12.4204 8.14633 11.997 8.36429C10.9478 7.82388 9.62021 7.82912 8.53296 8.73228C7.15064 9.88056 6.92784 11.8645 8.0466 13.2641C8.36602 13.6637 8.91519 14.1949 9.40533 14.6492C9.49781 14.7349 9.54405 14.7777 9.5632 14.8041C9.70784 15.003 9.5994 15.2795 9.35808 15.3271C9.32614 15.3334 9.26453 15.3334 9.14129 15.3334H5.83912C5.30248 15.3334 4.85958 15.3334 4.49878 15.304C4.12405 15.2733 3.77958 15.2076 3.45603 15.0428C2.95426 14.7871 2.54631 14.3792 2.29065 13.8774C2.12579 13.5538 2.06008 13.2094 2.02946 12.8346C1.99999 12.4738 1.99999 12.0309 2 11.4943V4.50587C1.99999 3.96924 1.99999 3.52632 2.02946 3.16553C2.06008 2.7908 2.12579 2.44633 2.29065 2.12277C2.54631 1.62101 2.95426 1.21306 3.45603 0.957399C3.77958 0.792538 4.12405 0.726829 4.49878 0.696212C4.85957 0.666734 5.3025 0.666741 5.83914 0.666748ZM4.66667 5.33342C4.29848 5.33342 4 5.63189 4 6.00008C4 6.36827 4.29848 6.66675 4.66667 6.66675H8.66667C9.03486 6.66675 9.33333 6.36827 9.33333 6.00008C9.33333 5.63189 9.03486 5.33342 8.66667 5.33342H4.66667ZM4 8.66675C4 8.29856 4.29848 8.00008 4.66667 8.00008H6C6.36819 8.00008 6.66667 8.29856 6.66667 8.66675C6.66667 9.03494 6.36819 9.33342 6 9.33342H4.66667C4.29848 9.33342 4 9.03494 4 8.66675ZM4.66667 2.66675C4.29848 2.66675 4 2.96523 4 3.33342C4 3.7016 4.29848 4.00008 4.66667 4.00008H10.6667C11.0349 4.00008 11.3333 3.7016 11.3333 3.33342C11.3333 2.96523 11.0349 2.66675 10.6667 2.66675H4.66667Z" fill="#DD2590" />
<path d="M11.9977 10.0256C11.3313 9.26808 10.2199 9.06432 9.3849 9.75796C8.54988 10.4516 8.43232 11.6113 9.08807 12.4317C9.58479 13.0531 10.9986 14.3025 11.655 14.8719C11.7744 14.9754 11.8341 15.0272 11.9037 15.0477C11.9642 15.0654 12.0312 15.0654 12.0917 15.0477C12.1613 15.0272 12.221 14.9754 12.3404 14.8719C12.9968 14.3025 14.4106 13.0531 14.9074 12.4317C15.5631 11.6113 15.4599 10.4443 14.6105 9.75796C13.7612 9.07161 12.6642 9.26808 11.9977 10.0256Z" fill="#DD2590" />
</svg>
)
}
export default React.memo(MoreLikeThisIcon)
'use client'
import type { FC } from 'react'
import React from 'react'
const SuggestedQuestionsAfterAnswerIcon: FC = () => {
return (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" clipRule="evenodd" d="M10.8275 1.33325H5.17245C4.63581 1.33324 4.19289 1.33324 3.8321 1.36272C3.45737 1.39333 3.1129 1.45904 2.78934 1.6239C2.28758 1.87956 1.87963 2.28751 1.62397 2.78928C1.45911 3.11284 1.3934 3.4573 1.36278 3.83204C1.3333 4.19283 1.33331 4.63574 1.33332 5.17239L1.33328 9.42497C1.333 9.95523 1.33278 10.349 1.42418 10.6901C1.67076 11.6103 2.38955 12.3291 3.3098 12.5757C3.51478 12.6306 3.73878 12.6525 3.99998 12.6611L3.99998 13.5806C3.99995 13.7374 3.99992 13.8973 4.01182 14.0283C4.0232 14.1536 4.05333 14.3901 4.21844 14.5969C4.40843 14.8349 4.69652 14.9734 5.00106 14.973C5.26572 14.9728 5.46921 14.8486 5.57416 14.7792C5.6839 14.7066 5.80872 14.6067 5.93117 14.5087L7.53992 13.2217C7.88564 12.9451 7.98829 12.8671 8.09494 12.8126C8.20192 12.7579 8.3158 12.718 8.43349 12.6938C8.55081 12.6697 8.67974 12.6666 9.12248 12.6666H10.8275C11.3642 12.6666 11.8071 12.6666 12.1679 12.6371C12.5426 12.6065 12.8871 12.5408 13.2106 12.3759C13.7124 12.1203 14.1203 11.7123 14.376 11.2106C14.5409 10.887 14.6066 10.5425 14.6372 10.1678C14.6667 9.80701 14.6667 9.36411 14.6667 8.82747V5.17237C14.6667 4.63573 14.6667 4.19283 14.6372 3.83204C14.6066 3.4573 14.5409 3.11284 14.376 2.78928C14.1203 2.28751 13.7124 1.87956 13.2106 1.6239C12.8871 1.45904 12.5426 1.39333 12.1679 1.36272C11.8071 1.33324 11.3642 1.33324 10.8275 1.33325ZM8.99504 4.99992C8.99504 4.44763 9.44275 3.99992 9.99504 3.99992C10.5473 3.99992 10.995 4.44763 10.995 4.99992C10.995 5.5522 10.5473 5.99992 9.99504 5.99992C9.44275 5.99992 8.99504 5.5522 8.99504 4.99992ZM4.92837 7.79996C5.222 7.57974 5.63816 7.63837 5.85961 7.93051C5.90071 7.98295 5.94593 8.03229 5.99199 8.08035C6.09019 8.18282 6.23775 8.32184 6.42882 8.4608C6.81353 8.74059 7.3454 8.99996 7.99504 8.99996C8.64469 8.99996 9.17655 8.74059 9.56126 8.4608C9.75233 8.32184 9.89989 8.18282 9.99809 8.08035C10.0441 8.0323 10.0894 7.98294 10.1305 7.93051C10.3519 7.63837 10.7681 7.57974 11.0617 7.79996C11.3563 8.02087 11.416 8.43874 11.195 8.73329C11.1967 8.73112 11.1928 8.7361 11.186 8.74466C11.1697 8.7651 11.1372 8.80597 11.1261 8.81916C11.087 8.86575 11.0317 8.92884 10.9607 9.00289C10.8194 9.15043 10.6128 9.34474 10.3455 9.53912C9.81353 9.92599 9.01206 10.3333 7.99504 10.3333C6.97802 10.3333 6.17655 9.92599 5.64459 9.53912C5.37733 9.34474 5.17072 9.15043 5.02934 9.00289C4.95837 8.92884 4.90305 8.86575 4.86395 8.81916C4.84438 8.79585 4.82881 8.77659 4.81731 8.76207C4.58702 8.46455 4.61798 8.03275 4.92837 7.79996ZM5.99504 3.99992C5.44275 3.99992 4.99504 4.44763 4.99504 4.99992C4.99504 5.5522 5.44275 5.99992 5.99504 5.99992C6.54732 5.99992 6.99504 5.5522 6.99504 4.99992C6.99504 4.44763 6.54732 3.99992 5.99504 3.99992Z" fill="#06AED4" />
</svg>
)
}
export default React.memo(SuggestedQuestionsAfterAnswerIcon)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import WarningMask from '.'
import Button from '@/app/components/base/button'
export type IFormattingChangedProps = {
onConfirm: () => void
}
const FormattingChanged: FC<IFormattingChangedProps> = ({
onConfirm,
}) => {
const { t } = useTranslation()
return (
<WarningMask
title={t('appDebug.feature.dataSet.queryVariable.unableToQueryDataSet')}
description={t('appDebug.feature.dataSet.queryVariable.unableToQueryDataSetTip')}
footer={
<div className='flex space-x-2'>
<Button variant='primary' className='flex !w-[96px] justify-start' onClick={onConfirm}>
<span className='text-[13px] font-medium'>{t('appDebug.feature.dataSet.queryVariable.ok')}</span>
</Button>
</div>
}
/>
)
}
export default React.memo(FormattingChanged)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import WarningMask from '.'
import Button from '@/app/components/base/button'
export type IFormattingChangedProps = {
onConfirm: () => void
onCancel: () => void
}
const icon = (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.33337 6.66667C1.33337 6.66667 2.67003 4.84548 3.75593 3.75883C4.84183 2.67218 6.34244 2 8.00004 2C11.3137 2 14 4.68629 14 8C14 11.3137 11.3137 14 8.00004 14C5.26465 14 2.95678 12.1695 2.23455 9.66667M1.33337 6.66667V2.66667M1.33337 6.66667H5.33337" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)
const FormattingChanged: FC<IFormattingChangedProps> = ({
onConfirm,
onCancel,
}) => {
const { t } = useTranslation()
return (
<WarningMask
title={t('appDebug.formattingChangedTitle')}
description={t('appDebug.formattingChangedText')}
footer={
<div className='flex space-x-2'>
<Button variant='primary' className='flex space-x-2' onClick={onConfirm}>
{icon}
<span>{t('common.operation.refresh')}</span>
</Button>
<Button onClick={onCancel}>{t('common.operation.cancel') as string}</Button>
</div>
}
/>
)
}
export default React.memo(FormattingChanged)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import WarningMask from '.'
import Button from '@/app/components/base/button'
export type IHasNotSetAPIProps = {
isTrailFinished: boolean
onSetting: () => void
}
const icon = (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 6.00001L14 2.00001M14 2.00001H9.99999M14 2.00001L8 8M6.66667 2H5.2C4.0799 2 3.51984 2 3.09202 2.21799C2.71569 2.40973 2.40973 2.71569 2.21799 3.09202C2 3.51984 2 4.07989 2 5.2V10.8C2 11.9201 2 12.4802 2.21799 12.908C2.40973 13.2843 2.71569 13.5903 3.09202 13.782C3.51984 14 4.07989 14 5.2 14H10.8C11.9201 14 12.4802 14 12.908 13.782C13.2843 13.5903 13.5903 13.2843 13.782 12.908C14 12.4802 14 11.9201 14 10.8V9.33333" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)
const HasNotSetAPI: FC<IHasNotSetAPIProps> = ({
isTrailFinished,
onSetting,
}) => {
const { t } = useTranslation()
return (
<WarningMask
title={isTrailFinished ? t('appDebug.notSetAPIKey.trailFinished') : t('appDebug.notSetAPIKey.title')}
description={t('appDebug.notSetAPIKey.description')}
footer={
<Button variant='primary' className='flex space-x-2' onClick={onSetting}>
<span>{t('appDebug.notSetAPIKey.settingBtn')}</span>
{icon}
</Button>}
/>
)
}
export default React.memo(HasNotSetAPI)
'use client'
import type { FC } from 'react'
import React from 'react'
import s from './style.module.css'
export type IWarningMaskProps = {
title: string
description: string
footer: React.ReactNode
}
const warningIcon = (
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.99996 13.3334V10.0001M9.99996 6.66675H10.0083M18.3333 10.0001C18.3333 14.6025 14.6023 18.3334 9.99996 18.3334C5.39759 18.3334 1.66663 14.6025 1.66663 10.0001C1.66663 5.39771 5.39759 1.66675 9.99996 1.66675C14.6023 1.66675 18.3333 5.39771 18.3333 10.0001Z" stroke="#F79009" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)
const WarningMask: FC<IWarningMaskProps> = ({
title,
description,
footer,
}) => {
return (
<div className={`${s.mask} absolute inset-0 z-10 pt-16`}
>
<div className='mx-auto px-10'>
<div className={`${s.icon} flex h-11 w-11 items-center justify-center rounded-xl bg-white`}>{warningIcon}</div>
<div className='mt-4 text-[24px] font-semibold leading-normal text-gray-800'>
{title}
</div>
<div className='mt-3 text-base text-gray-500'>
{description}
</div>
<div className='mt-6'>
{footer}
</div>
</div>
</div>
)
}
export default React.memo(WarningMask)
.mask {
background-color: rgba(239, 244, 255, 0.9);
backdrop-filter: blur(2px);
}
.icon {
box-shadow: 0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03);
}
\ No newline at end of file
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Modal from '@/app/components/base/modal'
import type { ConversationHistoriesRole } from '@/models/debug'
import Button from '@/app/components/base/button'
type Props = {
isShow: boolean
saveLoading: boolean
data: ConversationHistoriesRole
onClose: () => void
onSave: (data: any) => void
}
const EditModal: FC<Props> = ({
isShow,
saveLoading,
data,
onClose,
onSave,
}) => {
const { t } = useTranslation()
const [tempData, setTempData] = useState(data)
return (
<Modal
title={t('appDebug.feature.conversationHistory.editModal.title')}
isShow={isShow}
onClose={onClose}
>
<div className={'mt-6 text-sm font-medium leading-[21px] text-text-primary'}>{t('appDebug.feature.conversationHistory.editModal.userPrefix')}</div>
<input className={'mt-2 box-border h-10 w-full rounded-lg bg-components-input-bg-normal px-3 text-sm leading-10'}
value={tempData.user_prefix}
onChange={e => setTempData({
...tempData,
user_prefix: e.target.value,
})}
/>
<div className={'mt-6 text-sm font-medium leading-[21px] text-text-primary'}>{t('appDebug.feature.conversationHistory.editModal.assistantPrefix')}</div>
<input className={'mt-2 box-border h-10 w-full rounded-lg bg-components-input-bg-normal px-3 text-sm leading-10'}
value={tempData.assistant_prefix}
onChange={e => setTempData({
...tempData,
assistant_prefix: e.target.value,
})}
placeholder={t('common.chat.conversationNamePlaceholder') || ''}
/>
<div className='mt-10 flex justify-end'>
<Button className='mr-2 shrink-0' onClick={onClose}>{t('common.operation.cancel')}</Button>
<Button variant='primary' className='shrink-0' onClick={() => onSave(tempData)} loading={saveLoading}>{t('common.operation.save')}</Button>
</div>
</Modal>
)
}
export default React.memo(EditModal)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useContext } from 'use-context-selector'
import { useTranslation } from 'react-i18next'
import OperationBtn from '@/app/components/app/configuration/base/operation-btn'
import Panel from '@/app/components/app/configuration/base/feature-panel'
import { MessageClockCircle } from '@/app/components/base/icons/src/vender/solid/general'
import I18n from '@/context/i18n'
import { LanguagesSupported } from '@/i18n/language'
type Props = {
showWarning: boolean
onShowEditModal: () => void
}
const HistoryPanel: FC<Props> = ({
showWarning,
onShowEditModal,
}) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
return (
<Panel
className='mt-2'
title={
<div className='flex items-center gap-2'>
<div>{t('appDebug.feature.conversationHistory.title')}</div>
</div>
}
headerIcon={
<div className='rounded-md p-1 shadow-xs'>
<MessageClockCircle className='h-4 w-4 text-[#DD2590]' />
</div>}
headerRight={
<div className='flex items-center'>
<div className='text-xs text-text-tertiary'>{t('appDebug.feature.conversationHistory.description')}</div>
<div className='ml-3 h-[14px] w-[1px] bg-divider-regular'></div>
<OperationBtn type="edit" onClick={onShowEditModal} />
</div>
}
noBodySpacing
>
{showWarning && (
<div className='flex justify-between rounded-b-xl bg-background-section-burn px-3 py-2 text-xs text-text-secondary'>
<div>{t('appDebug.feature.conversationHistory.tip')}
<a href={`${locale === LanguagesSupported[1]
? 'https://docs.dify.ai/v/zh-hans/guides/application-design/prompt-engineering'
: 'https://docs.dify.ai/features/prompt-engineering'}`}
target='_blank' rel='noopener noreferrer'
className='text-[#155EEF]'>{t('appDebug.feature.conversationHistory.learnMore')}
</a>
</div>
</div>
)}
</Panel>
)
}
export default React.memo(HistoryPanel)
'use client'
import type { FC } from 'react'
import React, { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import produce from 'immer'
import { useContext } from 'use-context-selector'
import ParamConfig from './param-config'
import { Vision } from '@/app/components/base/icons/src/vender/features'
import Tooltip from '@/app/components/base/tooltip'
// import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
import ConfigContext from '@/context/debug-configuration'
// import { Resolution } from '@/types/app'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import Switch from '@/app/components/base/switch'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
const ConfigVision: FC = () => {
const { t } = useTranslation()
const { isShowVisionConfig, isAllowVideoUpload } = useContext(ConfigContext)
const file = useFeatures(s => s.features.file)
const featuresStore = useFeaturesStore()
const isImageEnabled = file?.allowed_file_types?.includes(SupportUploadFileTypes.image) ?? false
const handleChange = useCallback((value: boolean) => {
const {
features,
setFeatures,
} = featuresStore!.getState()
const newFeatures = produce(features, (draft) => {
if (value) {
draft.file!.allowed_file_types = Array.from(new Set([
...(draft.file?.allowed_file_types || []),
SupportUploadFileTypes.image,
...(isAllowVideoUpload ? [SupportUploadFileTypes.video] : []),
]))
}
else {
draft.file!.allowed_file_types = draft.file!.allowed_file_types?.filter(
type => type !== SupportUploadFileTypes.image && (isAllowVideoUpload ? type !== SupportUploadFileTypes.video : true),
)
}
if (draft.file) {
draft.file.enabled = (draft.file.allowed_file_types?.length ?? 0) > 0
draft.file.image = {
...(draft.file.image || {}),
enabled: value,
}
}
})
setFeatures(newFeatures)
}, [featuresStore, isAllowVideoUpload])
if (!isShowVisionConfig)
return null
return (
<div className='mt-2 flex items-center gap-2 rounded-xl border-l-[0.5px] border-t-[0.5px] border-effects-highlight bg-background-section-burn p-2'>
<div className='shrink-0 p-1'>
<div className='rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-indigo-indigo-600 p-1 shadow-xs'>
<Vision className='h-4 w-4 text-text-primary-on-surface' />
</div>
</div>
<div className='flex grow items-center'>
<div className='system-sm-semibold mr-1 text-text-secondary'>{t('appDebug.vision.name')}</div>
<Tooltip
popupContent={
<div className='w-[180px]' >
{t('appDebug.vision.description')}
</div>
}
/>
</div>
<div className='flex shrink-0 items-center'>
{/* <div className='mr-2 flex items-center gap-0.5'>
<div className='text-text-tertiary system-xs-medium-uppercase'>{t('appDebug.vision.visionSettings.resolution')}</div>
<Tooltip
popupContent={
<div className='w-[180px]' >
{t('appDebug.vision.visionSettings.resolutionTooltip').split('\n').map(item => (
<div key={item}>{item}</div>
))}
</div>
}
/>
</div> */}
{/* <div className='flex items-center gap-1'>
<OptionCard
title={t('appDebug.vision.visionSettings.high')}
selected={file?.image?.detail === Resolution.high}
onSelect={() => handleChange(Resolution.high)}
/>
<OptionCard
title={t('appDebug.vision.visionSettings.low')}
selected={file?.image?.detail === Resolution.low}
onSelect={() => handleChange(Resolution.low)}
/>
</div> */}
<ParamConfig />
<div className='ml-1 mr-3 h-3.5 w-[1px] bg-divider-regular'></div>
<Switch
defaultValue={isImageEnabled}
onChange={handleChange}
size='md'
/>
</div>
</div>
)
}
export default React.memo(ConfigVision)
'use client'
import type { FC } from 'react'
import React, { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import produce from 'immer'
import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
import { Resolution, TransferMethod } from '@/types/app'
import ParamItem from '@/app/components/base/param-item'
import Tooltip from '@/app/components/base/tooltip'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import type { FileUpload } from '@/app/components/base/features/types'
const MIN = 1
const MAX = 6
const ParamConfigContent: FC = () => {
const { t } = useTranslation()
const file = useFeatures(s => s.features.file)
const featuresStore = useFeaturesStore()
const handleChange = useCallback((data: FileUpload) => {
const {
features,
setFeatures,
} = featuresStore!.getState()
const newFeatures = produce(features, (draft) => {
draft.file = {
...draft.file,
allowed_file_upload_methods: data.allowed_file_upload_methods,
number_limits: data.number_limits,
image: {
enabled: data.enabled,
detail: data.image?.detail,
transfer_methods: data.allowed_file_upload_methods,
number_limits: data.number_limits,
},
}
})
setFeatures(newFeatures)
}, [featuresStore])
return (
<div>
<div className='text-base font-semibold leading-6 text-text-primary'>{t('appDebug.vision.visionSettings.title')}</div>
<div className='space-y-6 pt-3'>
<div>
<div className='mb-2 flex items-center space-x-1'>
<div className='text-[13px] font-semibold leading-[18px] text-text-secondary'>{t('appDebug.vision.visionSettings.resolution')}</div>
<Tooltip
popupContent={
<div className='w-[180px]' >
{t('appDebug.vision.visionSettings.resolutionTooltip').split('\n').map(item => (
<div key={item}>{item}</div>
))}
</div>
}
/>
</div>
<div className='flex items-center gap-1'>
<OptionCard
className='grow'
title={t('appDebug.vision.visionSettings.high')}
selected={file?.image?.detail === Resolution.high}
onSelect={() => handleChange({
...file,
image: { detail: Resolution.high },
})}
/>
<OptionCard
className='grow'
title={t('appDebug.vision.visionSettings.low')}
selected={file?.image?.detail === Resolution.low}
onSelect={() => handleChange({
...file,
image: { detail: Resolution.low },
})}
/>
</div>
</div>
<div>
<div className='mb-2 text-[13px] font-semibold leading-[18px] text-text-secondary'>{t('appDebug.vision.visionSettings.uploadMethod')}</div>
<div className='flex items-center gap-1'>
<OptionCard
className='grow'
title={t('appDebug.vision.visionSettings.both')}
selected={!!file?.allowed_file_upload_methods?.includes(TransferMethod.local_file) && !!file?.allowed_file_upload_methods?.includes(TransferMethod.remote_url)}
onSelect={() => handleChange({
...file,
allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
})}
/>
<OptionCard
className='grow'
title={t('appDebug.vision.visionSettings.localUpload')}
selected={!!file?.allowed_file_upload_methods?.includes(TransferMethod.local_file) && file?.allowed_file_upload_methods?.length === 1}
onSelect={() => handleChange({
...file,
allowed_file_upload_methods: [TransferMethod.local_file],
})}
/>
<OptionCard
className='grow'
title={t('appDebug.vision.visionSettings.url')}
selected={!!file?.allowed_file_upload_methods?.includes(TransferMethod.remote_url) && file?.allowed_file_upload_methods?.length === 1}
onSelect={() => handleChange({
...file,
allowed_file_upload_methods: [TransferMethod.remote_url],
})}
/>
</div>
</div>
<div>
<ParamItem
id='upload_limit'
className=''
name={t('appDebug.vision.visionSettings.uploadLimit')}
noTooltip
{...{
default: 2,
step: 1,
min: MIN,
max: MAX,
}}
value={file?.number_limits || 3}
enable={true}
onChange={(_key: string, value: number) => {
if (!value)
return
handleChange({
...file,
number_limits: value,
})
}}
/>
</div>
</div>
</div>
)
}
export default React.memo(ParamConfigContent)
'use client'
import type { FC } from 'react'
import { memo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiSettings2Line } from '@remixicon/react'
import ParamConfigContent from './param-config-content'
import Button from '@/app/components/base/button'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import cn from '@/utils/classnames'
const ParamsConfig: FC = () => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-end'
offset={{
mainAxis: 4,
}}
>
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
<Button variant='ghost' size='small' className={cn('')}>
<RiSettings2Line className='h-3.5 w-3.5' />
<div className='ml-1'>{t('appDebug.voice.settings')}</div>
</Button>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent style={{ zIndex: 50 }}>
<div className='w-80 space-y-3 rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg p-4 shadow-lg sm:w-[412px]'>
<ParamConfigContent />
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default memo(ParamsConfig)
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiSettings2Line } from '@remixicon/react'
import AgentSetting from './agent/agent-setting'
import Button from '@/app/components/base/button'
import type { AgentConfig } from '@/models/debug'
type Props = {
isFunctionCall: boolean
isChatModel: boolean
agentConfig?: AgentConfig
onAgentSettingChange: (payload: AgentConfig) => void
}
const AgentSettingButton: FC<Props> = ({
onAgentSettingChange,
isFunctionCall,
isChatModel,
agentConfig,
}) => {
const { t } = useTranslation()
const [isShowAgentSetting, setIsShowAgentSetting] = useState(false)
return (
<>
<Button onClick={() => setIsShowAgentSetting(true)} className='mr-2 shrink-0'>
<RiSettings2Line className='mr-1 h-4 w-4 text-text-tertiary' />
{t('appDebug.agent.setting.name')}
</Button>
{isShowAgentSetting && (
<AgentSetting
isFunctionCall={isFunctionCall}
payload={agentConfig as AgentConfig}
isChatModel={isChatModel}
onSave={(payloadNew) => {
onAgentSettingChange(payloadNew)
setIsShowAgentSetting(false)
}}
onCancel={() => setIsShowAgentSetting(false)}
/>
)}
</>
)
}
export default React.memo(AgentSettingButton)
'use client'
import type { FC } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiCloseLine } from '@remixicon/react'
import { useClickAway } from 'ahooks'
import ItemPanel from './item-panel'
import Button from '@/app/components/base/button'
import { CuteRobot } from '@/app/components/base/icons/src/vender/solid/communication'
import { Unblur } from '@/app/components/base/icons/src/vender/solid/education'
import Slider from '@/app/components/base/slider'
import type { AgentConfig } from '@/models/debug'
import { DEFAULT_AGENT_PROMPT, MAX_ITERATIONS_NUM } from '@/config'
type Props = {
isChatModel: boolean
payload: AgentConfig
isFunctionCall: boolean
onCancel: () => void
onSave: (payload: any) => void
}
const maxIterationsMin = 1
const AgentSetting: FC<Props> = ({
isChatModel,
payload,
isFunctionCall,
onCancel,
onSave,
}) => {
const { t } = useTranslation()
const [tempPayload, setTempPayload] = useState(payload)
const ref = useRef(null)
const [mounted, setMounted] = useState(false)
useClickAway(() => {
if (mounted)
onCancel()
}, ref)
useEffect(() => {
setMounted(true)
}, [])
const handleSave = () => {
onSave(tempPayload)
}
return (
<div className='fixed inset-0 z-[100] flex justify-end overflow-hidden p-2'
style={{
backgroundColor: 'rgba(16, 24, 40, 0.20)',
}}
>
<div
ref={ref}
className='flex h-full w-[640px] flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl'
>
<div className='flex h-14 shrink-0 items-center justify-between border-b border-divider-regular pl-6 pr-5'>
<div className='flex flex-col text-base font-semibold text-text-primary'>
<div className='leading-6'>{t('appDebug.agent.setting.name')}</div>
</div>
<div className='flex items-center'>
<div
onClick={onCancel}
className='flex h-6 w-6 cursor-pointer items-center justify-center'
>
<RiCloseLine className='h-4 w-4 text-text-tertiary' />
</div>
</div>
</div>
{/* Body */}
<div className='grow overflow-y-auto border-b p-6 pb-[68px] pt-5' style={{
borderBottom: 'rgba(0, 0, 0, 0.05)',
}}>
{/* Agent Mode */}
<ItemPanel
className='mb-4'
icon={
<CuteRobot className='h-4 w-4 text-indigo-600' />
}
name={t('appDebug.agent.agentMode')}
description={t('appDebug.agent.agentModeDes')}
>
<div className='text-[13px] font-medium leading-[18px] text-text-primary'>{isFunctionCall ? t('appDebug.agent.agentModeType.functionCall') : t('appDebug.agent.agentModeType.ReACT')}</div>
</ItemPanel>
<ItemPanel
className='mb-4'
icon={
<Unblur className='h-4 w-4 text-[#FB6514]' />
}
name={t('appDebug.agent.setting.maximumIterations.name')}
description={t('appDebug.agent.setting.maximumIterations.description')}
>
<div className='flex items-center'>
<Slider
className='mr-3 w-[156px]'
min={maxIterationsMin}
max={MAX_ITERATIONS_NUM}
value={tempPayload.max_iteration}
onChange={(value) => {
setTempPayload({
...tempPayload,
max_iteration: value,
})
}}
/>
<input
type="number"
min={maxIterationsMin}
max={MAX_ITERATIONS_NUM} step={1}
className="block h-7 w-11 rounded-lg border-0 bg-components-input-bg-normal px-1.5 pl-1 leading-7 text-text-primary placeholder:text-text-tertiary focus:ring-1 focus:ring-inset focus:ring-primary-600"
value={tempPayload.max_iteration}
onChange={(e) => {
let value = Number.parseInt(e.target.value, 10)
if (value < maxIterationsMin)
value = maxIterationsMin
if (value > MAX_ITERATIONS_NUM)
value = MAX_ITERATIONS_NUM
setTempPayload({
...tempPayload,
max_iteration: value,
})
}} />
</div>
</ItemPanel>
{!isFunctionCall && (
<div className='rounded-xl bg-background-section-burn py-2 shadow-xs'>
<div className='flex h-8 items-center px-4 text-sm font-semibold leading-6 text-text-secondary'>{t('tools.builtInPromptTitle')}</div>
<div className='h-[396px] overflow-y-auto whitespace-pre-line px-4 text-sm font-normal leading-5 text-text-secondary'>
{isChatModel ? DEFAULT_AGENT_PROMPT.chat : DEFAULT_AGENT_PROMPT.completion}
</div>
<div className='px-4'>
<div className='inline-flex h-5 items-center rounded-md bg-components-input-bg-normal px-1 text-xs font-medium leading-[18px] text-text-tertiary'>{(isChatModel ? DEFAULT_AGENT_PROMPT.chat : DEFAULT_AGENT_PROMPT.completion).length}</div>
</div>
</div>
)}
</div>
<div
className='sticky bottom-0 z-[5] flex w-full justify-end border-t border-divider-regular bg-background-section-burn px-6 py-4'
>
<Button
onClick={onCancel}
className='mr-2'
>
{t('common.operation.cancel')}
</Button>
<Button
variant='primary'
onClick={handleSave}
>
{t('common.operation.save')}
</Button>
</div>
</div>
</div>
)
}
export default React.memo(AgentSetting)
'use client'
import type { FC } from 'react'
import React from 'react'
import cn from '@/utils/classnames'
import Tooltip from '@/app/components/base/tooltip'
type Props = {
className?: string
icon: React.JSX.Element
name: string
description: string
children: React.JSX.Element
}
const ItemPanel: FC<Props> = ({
className,
icon,
name,
description,
children,
}) => {
return (
<div className={cn(className, 'flex h-12 items-center justify-between rounded-lg bg-background-section-burn px-3')}>
<div className='flex items-center'>
{icon}
<div className='ml-3 mr-1 text-sm font-semibold leading-6 text-text-secondary'>{name}</div>
<Tooltip
popupContent={
<div className='w-[180px]'>
{description}
</div>
}
>
</Tooltip>
</div>
<div>
{children}
</div>
</div>
)
}
export default React.memo(ItemPanel)
'use client'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import {
RiArrowLeftLine,
RiCloseLine,
} from '@remixicon/react'
import Drawer from '@/app/components/base/drawer'
import Loading from '@/app/components/base/loading'
import ActionButton from '@/app/components/base/action-button'
import Icon from '@/app/components/plugins/card/base/card-icon'
import OrgInfo from '@/app/components/plugins/card/base/org-info'
import Description from '@/app/components/plugins/card/base/description'
import TabSlider from '@/app/components/base/tab-slider-plain'
import Button from '@/app/components/base/button'
import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'
import { addDefaultValue, toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import type { Collection, Tool } from '@/app/components/tools/types'
import { CollectionType } from '@/app/components/tools/types'
import { fetchBuiltInToolList, fetchCustomToolList, fetchModelToolList, fetchWorkflowToolList } from '@/service/tools'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import cn from '@/utils/classnames'
type Props = {
showBackButton?: boolean
collection: Collection
isBuiltIn?: boolean
isModel?: boolean
toolName: string
setting?: Record<string, any>
readonly?: boolean
onHide: () => void
onSave?: (value: Record<string, any>) => void
}
const SettingBuiltInTool: FC<Props> = ({
showBackButton = false,
collection,
isBuiltIn = true,
isModel = true,
toolName,
setting = {},
readonly,
onHide,
onSave,
}) => {
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const { t } = useTranslation()
const [isLoading, setIsLoading] = useState(true)
const [tools, setTools] = useState<Tool[]>([])
const currTool = tools.find(tool => tool.name === toolName)
const formSchemas = currTool ? toolParametersToFormSchemas(currTool.parameters) : []
const infoSchemas = formSchemas.filter((item: any) => item.form === 'llm')
const settingSchemas = formSchemas.filter((item: any) => item.form !== 'llm')
const hasSetting = settingSchemas.length > 0
const [tempSetting, setTempSetting] = useState(setting)
const [currType, setCurrType] = useState('info')
const isInfoActive = currType === 'info'
useEffect(() => {
if (!collection)
return
(async () => {
setIsLoading(true)
try {
const list = await new Promise<Tool[]>((resolve) => {
(async function () {
if (isModel)
resolve(await fetchModelToolList(collection.name))
else if (isBuiltIn)
resolve(await fetchBuiltInToolList(collection.name))
else if (collection.type === CollectionType.workflow)
resolve(await fetchWorkflowToolList(collection.id))
else
resolve(await fetchCustomToolList(collection.name))
}())
})
setTools(list)
const currTool = list.find(tool => tool.name === toolName)
if (currTool) {
const formSchemas = toolParametersToFormSchemas(currTool.parameters)
setTempSetting(addDefaultValue(setting, formSchemas))
}
}
catch (e) { }
setIsLoading(false)
})()
}, [collection?.name, collection?.id, collection?.type])
useEffect(() => {
setCurrType((!readonly && hasSetting) ? 'setting' : 'info')
}, [hasSetting])
const isValid = (() => {
let valid = true
settingSchemas.forEach((item: any) => {
if (item.required && !tempSetting[item.name])
valid = false
})
return valid
})()
const getType = (type: string) => {
if (type === 'number-input')
return t('tools.setBuiltInTools.number')
if (type === 'text-input')
return t('tools.setBuiltInTools.string')
if (type === 'file')
return t('tools.setBuiltInTools.file')
return type
}
const infoUI = (
<div className=''>
{infoSchemas.length > 0 && (
<div className='space-y-1 py-2'>
{infoSchemas.map((item: any, index) => (
<div key={index} className='py-1'>
<div className='flex items-center gap-2'>
<div className='code-sm-semibold text-text-secondary'>{item.label[language]}</div>
<div className='system-xs-regular text-text-tertiary'>
{getType(item.type)}
</div>
{item.required && (
<div className='system-xs-medium text-text-warning-secondary'>{t('tools.setBuiltInTools.required')}</div>
)}
</div>
{item.human_description && (
<div className='system-xs-regular mt-0.5 text-text-tertiary'>
{item.human_description?.[language]}
</div>
)}
</div>
))}
</div>
)}
</div>
)
const settingUI = (
<Form
value={tempSetting}
onChange={setTempSetting}
formSchemas={settingSchemas as any}
isEditMode={false}
showOnVariableMap={{}}
validating={false}
readonly={readonly}
/>
)
return (
<Drawer
isOpen
clickOutsideNotOpen={false}
onClose={onHide}
footer={null}
mask={false}
positionCenter={false}
panelClassname={cn('mb-2 mr-2 mt-[64px] !w-[420px] !max-w-[420px] justify-start rounded-2xl border-[0.5px] border-components-panel-border !bg-components-panel-bg !p-0 shadow-xl')}
>
<>
{isLoading && <Loading type='app' />}
{!isLoading && (
<>
{/* header */}
<div className='relative border-b border-divider-subtle p-4 pb-3'>
<div className='absolute right-3 top-3'>
<ActionButton onClick={onHide}>
<RiCloseLine className='h-4 w-4' />
</ActionButton>
</div>
{showBackButton && (
<div
className='system-xs-semibold-uppercase mb-2 flex cursor-pointer items-center gap-1 text-text-accent-secondary'
onClick={onHide}
>
<RiArrowLeftLine className='h-4 w-4' />
BACK
</div>
)}
<div className='flex items-center gap-1'>
<Icon size='tiny' className='h-6 w-6' src={collection.icon} />
<OrgInfo
packageNameClassName='w-auto'
orgName={collection.author}
packageName={collection.name.split('/').pop() || ''}
/>
</div>
<div className='system-md-semibold mt-1 text-text-primary'>{currTool?.label[language]}</div>
{!!currTool?.description[language] && (
<Description className='mt-3' text={currTool.description[language]} descriptionLineRows={2}></Description>
)}
</div>
{/* form */}
<div className='h-full'>
<div className='flex h-full flex-col'>
{(hasSetting && !readonly) ? (
<TabSlider
className='mt-1 shrink-0 px-4'
itemClassName='py-3'
noBorderBottom
value={currType}
onChange={(value) => {
setCurrType(value)
}}
options={[
{ value: 'info', text: t('tools.setBuiltInTools.parameters')! },
{ value: 'setting', text: t('tools.setBuiltInTools.setting')! },
]}
/>
) : (
<div className='system-sm-semibold-uppercase p-4 pb-1 text-text-primary'>{t('tools.setBuiltInTools.parameters')}</div>
)}
<div className='h-0 grow overflow-y-auto px-4'>
{isInfoActive ? infoUI : settingUI}
</div>
{!readonly && !isInfoActive && (
<div className='mt-2 flex shrink-0 justify-end space-x-2 rounded-b-[10px] border-t border-divider-regular bg-components-panel-bg px-6 py-4'>
<Button className='flex h-8 items-center !px-3 !text-[13px] font-medium ' onClick={onHide}>{t('common.operation.cancel')}</Button>
<Button className='flex h-8 items-center !px-3 !text-[13px] font-medium' variant='primary' disabled={!isValid} onClick={() => onSave?.(addDefaultValue(tempSetting, formSchemas))}>{t('common.operation.save')}</Button>
</div>
)}
</div>
</div>
</>
)}
</>
</Drawer>
)
}
export default React.memo(SettingBuiltInTool)
'use client'
import type { FC } from 'react'
import React from 'react'
import copy from 'copy-to-clipboard'
import { useContext } from 'use-context-selector'
import { useTranslation } from 'react-i18next'
import cn from '@/utils/classnames'
import {
Clipboard,
ClipboardCheck,
} from '@/app/components/base/icons/src/vender/line/files'
import PromptEditor from '@/app/components/base/prompt-editor'
import type { ExternalDataTool } from '@/models/common'
import ConfigContext from '@/context/debug-configuration'
import { useModalContext } from '@/context/modal-context'
import { useToastContext } from '@/app/components/base/toast'
import s from '@/app/components/app/configuration/config-prompt/style.module.css'
import { noop } from 'lodash-es'
type Props = {
className?: string
type: 'first-prompt' | 'next-iteration'
value: string
onChange: (value: string) => void
}
const Editor: FC<Props> = ({
className,
type,
value,
onChange,
}) => {
const { t } = useTranslation()
const { notify } = useToastContext()
const [isCopied, setIsCopied] = React.useState(false)
const {
modelConfig,
hasSetBlockStatus,
dataSets,
showSelectDataSet,
externalDataToolsConfig,
setExternalDataToolsConfig,
} = useContext(ConfigContext)
const promptVariables = modelConfig.configs.prompt_variables
const { setShowExternalDataToolModal } = useModalContext()
const isFirstPrompt = type === 'first-prompt'
const editorHeight = isFirstPrompt ? 'h-[336px]' : 'h-[52px]'
const handleOpenExternalDataToolModal = () => {
setShowExternalDataToolModal({
payload: {},
onSaveCallback: (newExternalDataTool: ExternalDataTool) => {
setExternalDataToolsConfig([...externalDataToolsConfig, newExternalDataTool])
},
onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {
for (let i = 0; i < promptVariables.length; i++) {
if (promptVariables[i].key === newExternalDataTool.variable) {
notify({ type: 'error', message: t('appDebug.varKeyError.keyAlreadyExists', { key: promptVariables[i].key }) })
return false
}
}
for (let i = 0; i < externalDataToolsConfig.length; i++) {
if (externalDataToolsConfig[i].variable === newExternalDataTool.variable) {
notify({ type: 'error', message: t('appDebug.varKeyError.keyAlreadyExists', { key: externalDataToolsConfig[i].variable }) })
return false
}
}
return true
},
})
}
return (
<div className={cn(className, s.gradientBorder, 'relative')}>
<div className='rounded-xl bg-white'>
<div className={cn(s.boxHeader, 'flex h-11 items-center justify-between rounded-tl-xl rounded-tr-xl bg-white pb-1 pl-4 pr-3 pt-2 hover:shadow-xs')}>
<div className='text-sm font-semibold uppercase text-indigo-800'>{t(`appDebug.agent.${isFirstPrompt ? 'firstPrompt' : 'nextIteration'}`)}</div>
<div className={cn(s.optionWrap, 'items-center space-x-1')}>
{!isCopied
? (
<Clipboard className='h-6 w-6 cursor-pointer p-1 text-gray-500' onClick={() => {
copy(value)
setIsCopied(true)
}} />
)
: (
<ClipboardCheck className='h-6 w-6 p-1 text-gray-500' />
)}
</div>
</div>
<div className={cn(editorHeight, ' min-h-[102px] overflow-y-auto px-4 text-sm text-gray-700')}>
<PromptEditor
className={editorHeight}
value={value}
contextBlock={{
show: true,
selectable: !hasSetBlockStatus.context,
datasets: dataSets.map(item => ({
id: item.id,
name: item.name,
type: item.data_source_type,
})),
onAddContext: showSelectDataSet,
}}
variableBlock={{
show: true,
variables: modelConfig.configs.prompt_variables.map(item => ({
name: item.name,
value: item.key,
})),
}}
externalToolBlock={{
show: true,
externalTools: externalDataToolsConfig.map(item => ({
name: item.label!,
variableName: item.variable!,
icon: item.icon,
icon_background: item.icon_background,
})),
onAddExternalTool: handleOpenExternalDataToolModal,
}}
historyBlock={{
show: false,
selectable: false,
history: {
user: '',
assistant: '',
},
onEditRole: noop,
}}
queryBlock={{
show: false,
selectable: false,
}}
onChange={onChange}
onBlur={noop}
/>
</div>
<div className='flex pb-2 pl-4'>
<div className="h-[18px] rounded-md bg-gray-100 px-1 text-xs leading-[18px] text-gray-500">{value.length}</div>
</div>
</div>
</div>
)
}
export default React.memo(Editor)
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiArrowDownSLine } from '@remixicon/react'
import AgentSetting from '../agent/agent-setting'
import cn from '@/utils/classnames'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { BubbleText } from '@/app/components/base/icons/src/vender/solid/education'
import Radio from '@/app/components/base/radio/ui'
import { CuteRobot } from '@/app/components/base/icons/src/vender/solid/communication'
import { Settings04 } from '@/app/components/base/icons/src/vender/line/general'
import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'
import type { AgentConfig } from '@/models/debug'
type Props = {
value: string
disabled: boolean
onChange: (value: string) => void
isFunctionCall: boolean
isChatModel: boolean
agentConfig?: AgentConfig
onAgentSettingChange: (payload: AgentConfig) => void
}
type ItemProps = {
text: string
disabled: boolean
value: string
isChecked: boolean
description: string
Icon: any
onClick: (value: string) => void
}
const SelectItem: FC<ItemProps> = ({ text, value, Icon, isChecked, description, onClick, disabled }) => {
return (
<div
className={cn(disabled ? 'opacity-50' : 'cursor-pointer', isChecked ? 'border-[2px] border-indigo-600 shadow-sm' : 'border border-gray-100', 'mb-2 rounded-xl bg-gray-25 p-3 pr-4 hover:bg-gray-50')}
onClick={() => !disabled && onClick(value)}
>
<div className='flex items-center justify-between'>
<div className='flex items-center '>
<div className='mr-3 rounded-lg bg-indigo-50 p-1'>
<Icon className='h-4 w-4 text-indigo-600' />
</div>
<div className='text-sm font-medium leading-5 text-gray-900'>{text}</div>
</div>
<Radio isChecked={isChecked} />
</div>
<div className='ml-9 text-xs font-normal leading-[18px] text-gray-500'>{description}</div>
</div>
)
}
const AssistantTypePicker: FC<Props> = ({
value,
disabled,
onChange,
onAgentSettingChange,
isFunctionCall,
isChatModel,
agentConfig,
}) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const handleChange = (chosenValue: string) => {
if (value === chosenValue)
return
onChange(chosenValue)
if (chosenValue !== 'agent')
setOpen(false)
}
const isAgent = value === 'agent'
const [isShowAgentSetting, setIsShowAgentSetting] = useState(false)
const agentConfigUI = (
<>
<div className='my-4 h-[1px] bg-gray-100'></div>
<div
className={cn(isAgent ? 'group cursor-pointer hover:bg-primary-50' : 'opacity-30', 'rounded-xl bg-gray-50 p-3 pr-4 ')}
onClick={() => {
if (isAgent) {
setOpen(false)
setIsShowAgentSetting(true)
}
}}
>
<div className='flex items-center justify-between'>
<div className='flex items-center '>
<div className='mr-3 rounded-lg bg-gray-200 p-1 group-hover:bg-white'>
<Settings04 className='h-4 w-4 text-gray-600 group-hover:text-[#155EEF]' />
</div>
<div className='text-sm font-medium leading-5 text-gray-900 group-hover:text-[#155EEF]'>{t('appDebug.agent.setting.name')}</div>
</div>
<ArrowUpRight className='h-4 w-4 text-gray-500 group-hover:text-[#155EEF]' />
</div>
<div className='ml-9 text-xs font-normal leading-[18px] text-gray-500'>{t('appDebug.agent.setting.description')}</div>
</div>
</>
)
return (
<>
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-end'
offset={{
mainAxis: 8,
crossAxis: -2,
}}
>
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
<div className={cn(open && 'bg-gray-50', 'flex h-8 cursor-pointer select-none items-center space-x-1 rounded-lg border border-black/5 px-3 text-indigo-600')}>
{isAgent ? <BubbleText className='h-3 w-3' /> : <CuteRobot className='h-3 w-3' />}
<div className='text-xs font-medium'>{t(`appDebug.assistantType.${isAgent ? 'agentAssistant' : 'chatAssistant'}.name`)}</div>
<RiArrowDownSLine className='h-3 w-3' />
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent style={{ zIndex: 1000 }}>
<div className='relative left-0.5 w-[480px] rounded-xl border border-black/8 bg-white p-6 shadow-lg'>
<div className='mb-2 text-sm font-semibold leading-5 text-gray-900'>{t('appDebug.assistantType.name')}</div>
<SelectItem
Icon={BubbleText}
value='chat'
disabled={disabled}
text={t('appDebug.assistantType.chatAssistant.name')}
description={t('appDebug.assistantType.chatAssistant.description')}
isChecked={!isAgent}
onClick={handleChange}
/>
<SelectItem
Icon={CuteRobot}
value='agent'
disabled={disabled}
text={t('appDebug.assistantType.agentAssistant.name')}
description={t('appDebug.assistantType.agentAssistant.description')}
isChecked={isAgent}
onClick={handleChange}
/>
{!disabled && agentConfigUI}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
{isShowAgentSetting && (
<AgentSetting
isFunctionCall={isFunctionCall}
payload={agentConfig as AgentConfig}
isChatModel={isChatModel}
onSave={(payloadNew) => {
onAgentSettingChange(payloadNew)
setIsShowAgentSetting(false)
}}
onCancel={() => setIsShowAgentSetting(false)}
/>
)}
</>
)
}
export default React.memo(AssistantTypePicker)
'use client'
import type { FC } from 'react'
import React, { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import produce from 'immer'
import { useContext } from 'use-context-selector'
import { Document } from '@/app/components/base/icons/src/vender/features'
import Tooltip from '@/app/components/base/tooltip'
import ConfigContext from '@/context/debug-configuration'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import Switch from '@/app/components/base/switch'
const ConfigDocument: FC = () => {
const { t } = useTranslation()
const file = useFeatures(s => s.features.file)
const featuresStore = useFeaturesStore()
const { isShowDocumentConfig } = useContext(ConfigContext)
const isDocumentEnabled = file?.allowed_file_types?.includes(SupportUploadFileTypes.document) ?? false
const handleChange = useCallback((value: boolean) => {
const {
features,
setFeatures,
} = featuresStore!.getState()
const newFeatures = produce(features, (draft) => {
if (value) {
draft.file!.allowed_file_types = Array.from(new Set([
...(draft.file?.allowed_file_types || []),
SupportUploadFileTypes.document,
]))
}
else {
draft.file!.allowed_file_types = draft.file!.allowed_file_types?.filter(
type => type !== SupportUploadFileTypes.document,
)
}
if (draft.file)
draft.file.enabled = (draft.file.allowed_file_types?.length ?? 0) > 0
})
setFeatures(newFeatures)
}, [featuresStore])
if (!isShowDocumentConfig)
return null
return (
<div className='mt-2 flex items-center gap-2 rounded-xl border-l-[0.5px] border-t-[0.5px] bg-background-section-burn p-2'>
<div className='shrink-0 p-1'>
<div className='rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-indigo-indigo-600 p-1 shadow-xs'>
<Document className='h-4 w-4 text-text-primary-on-surface' />
</div>
</div>
<div className='flex grow items-center'>
<div className='system-sm-semibold mr-1 text-text-secondary'>{t('appDebug.feature.documentUpload.title')}</div>
<Tooltip
popupContent={
<div className='w-[180px]' >
{t('appDebug.feature.documentUpload.description')}
</div>
}
/>
</div>
<div className='flex shrink-0 items-center'>
<div className='ml-1 mr-3 h-3.5 w-[1px] bg-divider-subtle'></div>
<Switch
defaultValue={isDocumentEnabled}
onChange={handleChange}
size='md'
/>
</div>
</div>
)
}
export default React.memo(ConfigDocument)
import React, { useEffect } from 'react'
function useFeature({
introduction,
setIntroduction,
moreLikeThis,
setMoreLikeThis,
suggestedQuestionsAfterAnswer,
setSuggestedQuestionsAfterAnswer,
speechToText,
setSpeechToText,
textToSpeech,
setTextToSpeech,
citation,
setCitation,
annotation,
setAnnotation,
moderation,
setModeration,
}: {
introduction: string
setIntroduction: (introduction: string) => void
moreLikeThis: boolean
setMoreLikeThis: (moreLikeThis: boolean) => void
suggestedQuestionsAfterAnswer: boolean
setSuggestedQuestionsAfterAnswer: (suggestedQuestionsAfterAnswer: boolean) => void
speechToText: boolean
setSpeechToText: (speechToText: boolean) => void
textToSpeech: boolean
setTextToSpeech: (textToSpeech: boolean) => void
citation: boolean
setCitation: (citation: boolean) => void
annotation: boolean
setAnnotation: (annotation: boolean) => void
moderation: boolean
setModeration: (moderation: boolean) => void
}) {
const [tempShowOpeningStatement, setTempShowOpeningStatement] = React.useState(!!introduction)
useEffect(() => {
// wait to api data back
if (introduction)
setTempShowOpeningStatement(true)
}, [introduction])
// const [tempMoreLikeThis, setTempMoreLikeThis] = React.useState(moreLikeThis)
// useEffect(() => {
// setTempMoreLikeThis(moreLikeThis)
// }, [moreLikeThis])
const featureConfig = {
openingStatement: tempShowOpeningStatement,
moreLikeThis,
suggestedQuestionsAfterAnswer,
speechToText,
textToSpeech,
citation,
annotation,
moderation,
}
const handleFeatureChange = (key: string, value: boolean) => {
switch (key) {
case 'openingStatement':
if (!value)
setIntroduction('')
setTempShowOpeningStatement(value)
break
case 'moreLikeThis':
setMoreLikeThis(value)
break
case 'suggestedQuestionsAfterAnswer':
setSuggestedQuestionsAfterAnswer(value)
break
case 'speechToText':
setSpeechToText(value)
break
case 'textToSpeech':
setTextToSpeech(value)
break
case 'citation':
setCitation(value)
break
case 'annotation':
setAnnotation(value)
break
case 'moderation':
setModeration(value)
}
}
return {
featureConfig,
handleFeatureChange,
}
}
export default useFeature
'use client'
import type { FC } from 'react'
import React from 'react'
import { useContext } from 'use-context-selector'
import produce from 'immer'
import { useFormattingChangedDispatcher } from '../debug/hooks'
import DatasetConfig from '../dataset-config'
import HistoryPanel from '../config-prompt/conversation-history/history-panel'
import ConfigVision from '../config-vision'
import ConfigDocument from './config-document'
import AgentTools from './agent/agent-tools'
import ConfigContext from '@/context/debug-configuration'
import ConfigPrompt from '@/app/components/app/configuration/config-prompt'
import ConfigVar from '@/app/components/app/configuration/config-var'
import type { ModelConfig, PromptVariable } from '@/models/debug'
import type { AppType } from '@/types/app'
import { ModelModeType } from '@/types/app'
const Config: FC = () => {
const {
mode,
isAdvancedMode,
modelModeType,
isAgent,
hasSetBlockStatus,
showHistoryModal,
modelConfig,
setModelConfig,
setPrevPromptConfig,
} = useContext(ConfigContext)
const isChatApp = ['advanced-chat', 'agent-chat', 'chat'].includes(mode)
const formattingChangedDispatcher = useFormattingChangedDispatcher()
const promptTemplate = modelConfig.configs.prompt_template
const promptVariables = modelConfig.configs.prompt_variables
// simple mode
const handlePromptChange = (newTemplate: string, newVariables: PromptVariable[]) => {
const newModelConfig = produce(modelConfig, (draft: ModelConfig) => {
draft.configs.prompt_template = newTemplate
draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...newVariables]
})
if (modelConfig.configs.prompt_template !== newTemplate)
formattingChangedDispatcher()
setPrevPromptConfig(modelConfig.configs)
setModelConfig(newModelConfig)
}
const handlePromptVariablesNameChange = (newVariables: PromptVariable[]) => {
setPrevPromptConfig(modelConfig.configs)
const newModelConfig = produce(modelConfig, (draft: ModelConfig) => {
draft.configs.prompt_variables = newVariables
})
setModelConfig(newModelConfig)
}
return (
<>
<div
className="relative h-0 grow overflow-y-auto px-6 pb-[50px]"
>
{/* Template */}
<ConfigPrompt
mode={mode as AppType}
promptTemplate={promptTemplate}
promptVariables={promptVariables}
onChange={handlePromptChange}
/>
{/* Variables */}
<ConfigVar
promptVariables={promptVariables}
onPromptVariablesChange={handlePromptVariablesNameChange}
/>
{/* Dataset */}
<DatasetConfig />
{/* Tools */}
{isAgent && (
<AgentTools />
)}
<ConfigVision />
<ConfigDocument />
{/* Chat History */}
{isAdvancedMode && isChatApp && modelModeType === ModelModeType.completion && (
<HistoryPanel
showWarning={!hasSetBlockStatus.history}
onShowEditModal={showHistoryModal}
/>
)}
</div>
</>
)
}
export default React.memo(Config)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import s from './style.module.css'
import Button from '@/app/components/base/button'
export type IContrlBtnGroupProps = {
onSave: () => void
onReset: () => void
}
const ContrlBtnGroup: FC<IContrlBtnGroupProps> = ({ onSave, onReset }) => {
const { t } = useTranslation()
return (
<div className="fixed bottom-0 left-[224px] h-[64px] w-[519px]">
<div className={`${s.ctrlBtn} flex h-full items-center gap-2 bg-white pl-4`}>
<Button variant='primary' onClick={onSave}>{t('appDebug.operation.applyConfig')}</Button>
<Button onClick={onReset}>{t('appDebug.operation.resetConfig')}</Button>
</div>
</div>
)
}
export default React.memo(ContrlBtnGroup)
.ctrlBtn {
left: -16px;
right: -16px;
bottom: -16px;
border-top: 1px solid #F3F4F6;
}
\ No newline at end of file
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import TypeIcon from '../type-icon'
import RemoveIcon from '../../base/icons/remove-icon'
import s from './style.module.css'
import cn from '@/utils/classnames'
import type { DataSet } from '@/models/datasets'
import { formatNumber } from '@/utils/format'
import Tooltip from '@/app/components/base/tooltip'
export type ICardItemProps = {
className?: string
config: DataSet
onRemove: (id: string) => void
readonly?: boolean
}
const CardItem: FC<ICardItemProps> = ({
className,
config,
onRemove,
readonly,
}) => {
const { t } = useTranslation()
return (
<div
className={
cn(className, s.card,
'relative flex cursor-pointer items-center rounded-xl border border-gray-200 bg-white px-3 py-2.5')
}>
<div className='flex items-center space-x-2'>
<div className={cn(!config.embedding_available && 'opacity-50')}>
<TypeIcon type="upload_file" />
</div>
<div>
<div className='mr-1 flex w-[160px] items-center'>
<div className={cn('overflow-hidden text-ellipsis whitespace-nowrap text-[13px] font-medium leading-[18px] text-gray-800', !config.embedding_available && 'opacity-50')}>{config.name}</div>
{!config.embedding_available && (
<Tooltip
popupContent={t('dataset.unavailableTip')}
>
<span className='inline-flex shrink-0 whitespace-nowrap rounded-md border border-gray-200 px-1 text-xs font-normal leading-[18px] text-gray-500'>{t('dataset.unavailable')}</span>
</Tooltip>
)}
</div>
<div className={cn('flex max-w-[150px] text-xs text-gray-500', !config.embedding_available && 'opacity-50')}>
{formatNumber(config.word_count)} {t('appDebug.feature.dataSet.words')} · {formatNumber(config.document_count)} {t('appDebug.feature.dataSet.textBlocks')}
</div>
</div>
</div>
{!readonly && <RemoveIcon className={`${s.deleteBtn} absolute right-1 top-1/2 translate-y-[-50%]`} onClick={() => onRemove(config.id)} />}
</div>
)
}
export default React.memo(CardItem)
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import {
RiDeleteBinLine,
RiEditLine,
} from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import SettingsModal from '../settings-modal'
import type { DataSet } from '@/models/datasets'
import { DataSourceType } from '@/models/datasets'
import FileIcon from '@/app/components/base/file-icon'
import { Folder } from '@/app/components/base/icons/src/vender/solid/files'
import { Globe06 } from '@/app/components/base/icons/src/vender/solid/mapsAndTravel'
import Drawer from '@/app/components/base/drawer'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import Badge from '@/app/components/base/badge'
import { useKnowledge } from '@/hooks/use-knowledge'
import cn from '@/utils/classnames'
type ItemProps = {
className?: string
config: DataSet
onRemove: (id: string) => void
readonly?: boolean
onSave: (newDataset: DataSet) => void
editable?: boolean
}
const Item: FC<ItemProps> = ({
config,
onSave,
onRemove,
editable = true,
}) => {
const media = useBreakpoints()
const isMobile = media === MediaType.mobile
const [showSettingsModal, setShowSettingsModal] = useState(false)
const { formatIndexingTechniqueAndMethod } = useKnowledge()
const { t } = useTranslation()
const handleSave = (newDataset: DataSet) => {
onSave(newDataset)
setShowSettingsModal(false)
}
const [isDeleting, setIsDeleting] = useState(false)
return (
<div className={cn('group relative mb-1 flex w-full items-center rounded-lg border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg py-2 pl-2.5 pr-3 shadow-xs last-of-type:mb-0 hover:bg-components-panel-on-panel-item-bg-hover hover:shadow-sm', isDeleting && 'border-state-destructive-border hover:bg-state-destructive-hover')}>
{
config.data_source_type === DataSourceType.FILE && (
<div className='mr-2 flex h-6 w-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-[#E0EAFF] bg-[#F5F8FF]'>
<Folder className='h-4 w-4 text-[#444CE7]' />
</div>
)
}
{
config.data_source_type === DataSourceType.NOTION && (
<div className='mr-2 flex h-6 w-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-[#EAECF5]'>
<FileIcon type='notion' className='h-4 w-4' />
</div>
)
}
{
config.data_source_type === DataSourceType.WEB && (
<div className='mr-2 flex h-6 w-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-blue-100 bg-[#F5FAFF]'>
<Globe06 className='h-4 w-4 text-blue-600' />
</div>
)
}
<div className='grow'>
<div className='flex h-[18px] items-center'>
<div className='grow truncate text-[13px] font-medium text-text-secondary' title={config.name}>{config.name}</div>
{config.provider === 'external'
? <Badge text={t('dataset.externalTag') as string} />
: <Badge
text={formatIndexingTechniqueAndMethod(config.indexing_technique, config.retrieval_model_dict?.search_method)}
/>}
</div>
</div >
<div className='absolute bottom-0 right-0 top-0 hidden w-[124px] items-center justify-end rounded-lg bg-gradient-to-r from-white/50 to-white to-50% pr-2 group-hover:flex'>
{
editable && <div
className='mr-1 flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-black/5'
onClick={() => setShowSettingsModal(true)}
>
<RiEditLine className='h-4 w-4 text-text-tertiary' />
</div>
}
<div
className='flex h-6 w-6 cursor-pointer items-center justify-center text-text-tertiary hover:text-text-destructive'
onClick={() => onRemove(config.id)}
onMouseOver={() => setIsDeleting(true)}
onMouseLeave={() => setIsDeleting(false)}
>
<RiDeleteBinLine className='h-4 w-4' />
</div>
</div>
<Drawer isOpen={showSettingsModal} onClose={() => setShowSettingsModal(false)} footer={null} mask={isMobile} panelClassname='mt-16 mx-2 sm:mr-2 mb-3 !p-0 !max-w-[640px] rounded-xl'>
<SettingsModal
currentDataset={config}
onCancel={() => setShowSettingsModal(false)}
onSave={handleSave}
/>
</Drawer>
</div >
)
}
export default Item
.card {
box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
width: 100%;
}
.card:hover {
box-shadow: 0px 4px 8px -2px rgba(16, 24, 40, 0.1), 0px 2px 4px -2px rgba(16, 24, 40, 0.06);
}
.btnWrap {
padding-left: 64px;
visibility: hidden;
background: linear-gradient(270deg, #FFF 49.99%, rgba(255, 255, 255, 0.00) 98.1%);
}
.card:hover .btnWrap {
visibility: visible;
}
.settingBtn:hover {
background-color: rgba(0, 0, 0, 0.05);
}
\ No newline at end of file
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import type { Props } from './var-picker'
import VarPicker from './var-picker'
import cn from '@/utils/classnames'
import { BracketsX } from '@/app/components/base/icons/src/vender/line/development'
import Tooltip from '@/app/components/base/tooltip'
const ContextVar: FC<Props> = (props) => {
const { t } = useTranslation()
const { value, options } = props
const currItem = options.find(item => item.value === value)
const notSetVar = !currItem
return (
<div className={cn(notSetVar ? 'rounded-bl-xl rounded-br-xl border-[#FEF0C7] bg-[#FEF0C7]' : 'border-components-panel-border-subtle', 'flex h-12 items-center justify-between border-t px-3 ')}>
<div className='flex shrink-0 items-center space-x-1'>
<div className='p-1'>
<BracketsX className='h-4 w-4 text-text-accent' />
</div>
<div className='mr-1 text-sm font-medium text-text-secondary'>{t('appDebug.feature.dataSet.queryVariable.title')}</div>
<Tooltip
popupContent={
<div className='w-[180px]'>
{t('appDebug.feature.dataSet.queryVariable.tip')}
</div>
}
/>
</div>
<VarPicker {...props} />
</div>
)
}
export default React.memo(ContextVar)
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ChevronDownIcon } from '@heroicons/react/24/outline'
import cn from '@/utils/classnames'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import type { IInputTypeIconProps } from '@/app/components/app/configuration/config-var/input-type-icon'
import IconTypeIcon from '@/app/components/app/configuration/config-var/input-type-icon'
type Option = { name: string; value: string; type: string }
export type Props = {
triggerClassName?: string
className?: string
value: string | undefined
options: Option[]
onChange: (value: string) => void
notSelectedVarTip?: string | null
}
const VarItem: FC<{ item: Option }> = ({ item }) => (
<div className='flex h-[18px] items-center space-x-1 rounded bg-[#EFF8FF] px-1'>
<IconTypeIcon type={item.type as IInputTypeIconProps['type']} className='text-[#1570EF]' />
<div className='flex text-xs font-medium text-[#1570EF]'>
<span className='opacity-60'>{'{{'}</span>
<span className='max-w-[150px] truncate'>{item.value}</span>
<span className='opacity-60'>{'}}'}</span>
</div>
</div>
)
const VarPicker: FC<Props> = ({
triggerClassName,
className,
value,
options,
onChange,
notSelectedVarTip,
}) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const currItem = options.find(item => item.value === value)
const notSetVar = !currItem
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-end'
offset={{
mainAxis: 8,
}}
>
<PortalToFollowElemTrigger className={cn(triggerClassName)} onClick={() => setOpen(v => !v)}>
<div className={cn(
className,
notSetVar ? 'border-[#FEDF89] bg-[#FFFCF5] text-[#DC6803]' : ' border-components-button-secondary-border text-text-accent hover:bg-components-button-secondary-bg',
open ? 'bg-components-button-secondary-bg' : 'bg-transparent',
`
flex h-8 cursor-pointer items-center justify-center space-x-1 rounded-lg border px-2 text-[13px]
font-medium shadow-xs
`)}>
<div>
{value
? (
<VarItem item={currItem as Option} />
)
: (<div>
{notSelectedVarTip || t('appDebug.feature.dataSet.queryVariable.choosePlaceholder')}
</div>)}
</div>
<ChevronDownIcon className={cn(open && 'rotate-180 text-text-tertiary', 'h-3.5 w-3.5')} />
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent style={{ zIndex: 1000 }}>
{options.length > 0
? (<div className='max-h-[50vh] w-[240px] overflow-y-auto rounded-lg border border-components-panel-border bg-components-panel-bg p-1 shadow-lg'>
{options.map(({ name, value, type }, index) => (
<div
key={index}
className='flex cursor-pointer rounded-lg px-3 py-1 hover:bg-state-base-hover'
onClick={() => {
onChange(value)
setOpen(false)
}}
>
<VarItem item={{ name, value, type }} />
</div>
))}
</div>)
: (
<div className='w-[240px] rounded-lg border border-components-panel-border bg-components-panel-bg p-6 shadow-lg'>
<div className='mb-1 text-sm font-medium text-text-secondary'>{t('appDebug.feature.dataSet.queryVariable.noVar')}</div>
<div className='text-xs leading-normal text-text-tertiary'>{t('appDebug.feature.dataSet.queryVariable.noVarTip')}</div>
</div>
)}
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default React.memo(VarPicker)
import React from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import ConfigContext from '@/context/debug-configuration'
import Input from '@/app/components/base/input'
import Select from '@/app/components/base/select'
import Textarea from '@/app/components/base/textarea'
import { DEFAULT_VALUE_MAX_LEN } from '@/config'
import type { Inputs } from '@/models/debug'
import cn from '@/utils/classnames'
type Props = {
inputs: Inputs
}
const ChatUserInput = ({
inputs,
}: Props) => {
const { t } = useTranslation()
const { modelConfig, setInputs } = useContext(ConfigContext)
const promptVariables = modelConfig.configs.prompt_variables.filter(({ key, name }) => {
return key && key?.trim() && name && name?.trim()
})
const promptVariableObj = (() => {
const obj: Record<string, boolean> = {}
promptVariables.forEach((input) => {
obj[input.key] = true
})
return obj
})()
const handleInputValueChange = (key: string, value: string) => {
if (!(key in promptVariableObj))
return
const newInputs = { ...inputs }
promptVariables.forEach((input) => {
if (input.key === key)
newInputs[key] = value
})
setInputs(newInputs)
}
if (!promptVariables.length)
return null
return (
<div className={cn('z-[1] rounded-xl border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg shadow-xs')}>
<div className='px-4 pb-4 pt-3'>
{promptVariables.map(({ key, name, type, options, max_length, required }, index) => (
<div
key={key}
className='mb-4 last-of-type:mb-0'
>
<div>
<div className='system-sm-semibold mb-1 flex h-6 items-center gap-1 text-text-secondary'>
<div className='truncate'>{name || key}</div>
{!required && <span className='system-xs-regular text-text-tertiary'>{t('workflow.panel.optional')}</span>}
</div>
<div className='grow'>
{type === 'string' && (
<Input
value={inputs[key] ? `${inputs[key]}` : ''}
onChange={(e) => { handleInputValueChange(key, e.target.value) }}
placeholder={name}
autoFocus={index === 0}
maxLength={max_length || DEFAULT_VALUE_MAX_LEN}
/>
)}
{type === 'paragraph' && (
<Textarea
className='h-[120px] grow'
placeholder={name}
value={inputs[key] ? `${inputs[key]}` : ''}
onChange={(e) => { handleInputValueChange(key, e.target.value) }}
/>
)}
{type === 'select' && (
<Select
className='w-full'
defaultValue={inputs[key] as string}
onSelect={(i) => { handleInputValueChange(key, i.value as string) }}
items={(options || []).map(i => ({ name: i, value: i }))}
allowSearch={false}
/>
)}
{type === 'number' && (
<Input
type='number'
value={inputs[key] ? `${inputs[key]}` : ''}
onChange={(e) => { handleInputValueChange(key, e.target.value) }}
placeholder={name}
autoFocus={index === 0}
maxLength={max_length || DEFAULT_VALUE_MAX_LEN}
/>
)}
</div>
</div>
</div>
))}
</div>
</div>
)
}
export default ChatUserInput
import type { FC } from 'react'
import {
memo,
useCallback,
useMemo,
} from 'react'
import type { ModelAndParameter } from '../types'
import {
APP_CHAT_WITH_MULTIPLE_MODEL,
APP_CHAT_WITH_MULTIPLE_MODEL_RESTART,
} from '../types'
import {
useConfigFromDebugContext,
useFormattingChangedSubscription,
} from '../hooks'
import Chat from '@/app/components/base/chat/chat'
import { useChat } from '@/app/components/base/chat/chat/hooks'
import { useDebugConfigurationContext } from '@/context/debug-configuration'
import type { ChatConfig, OnSend } from '@/app/components/base/chat/types'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { useProviderContext } from '@/context/provider-context'
import {
fetchConversationMessages,
fetchSuggestedQuestions,
stopChatMessageResponding,
} from '@/service/debug'
import Avatar from '@/app/components/base/avatar'
import { useAppContext } from '@/context/app-context'
import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useFeatures } from '@/app/components/base/features/hooks'
import type { InputForm } from '@/app/components/base/chat/chat/type'
import { getLastAnswer } from '@/app/components/base/chat/utils'
import { canFindTool } from '@/utils'
type ChatItemProps = {
modelAndParameter: ModelAndParameter
}
const ChatItem: FC<ChatItemProps> = ({
modelAndParameter,
}) => {
const { userProfile } = useAppContext()
const {
modelConfig,
appId,
inputs,
collectionList,
} = useDebugConfigurationContext()
const { textGenerationModelList } = useProviderContext()
const features = useFeatures(s => s.features)
const configTemplate = useConfigFromDebugContext()
const config = useMemo(() => {
return {
...configTemplate,
more_like_this: features.moreLikeThis,
opening_statement: features.opening?.enabled ? (features.opening?.opening_statement || '') : '',
suggested_questions: features.opening?.enabled ? (features.opening?.suggested_questions || []) : [],
sensitive_word_avoidance: features.moderation,
speech_to_text: features.speech2text,
text_to_speech: features.text2speech,
file_upload: features.file,
suggested_questions_after_answer: features.suggested,
retriever_resource: features.citation,
annotation_reply: features.annotationReply,
} as ChatConfig
}, [configTemplate, features])
const inputsForm = useMemo(() => {
return modelConfig.configs.prompt_variables.filter(item => item.type !== 'api').map(item => ({ ...item, label: item.name, variable: item.key })) as InputForm[]
}, [modelConfig.configs.prompt_variables])
const {
chatList,
isResponding,
handleSend,
suggestedQuestions,
handleRestart,
} = useChat(
config,
{
inputs,
inputsForm,
},
[],
taskId => stopChatMessageResponding(appId, taskId),
)
useFormattingChangedSubscription(chatList)
const doSend: OnSend = useCallback((message, files) => {
const currentProvider = textGenerationModelList.find(item => item.provider === modelAndParameter.provider)
const currentModel = currentProvider?.models.find(model => model.model === modelAndParameter.model)
const supportVision = currentModel?.features?.includes(ModelFeatureEnum.vision)
const configData = {
...config,
model: {
provider: modelAndParameter.provider,
name: modelAndParameter.model,
mode: currentModel?.model_properties.mode,
completion_params: modelAndParameter.parameters,
},
}
const data: any = {
query: message,
inputs,
model_config: configData,
parent_message_id: getLastAnswer(chatList)?.id || null,
}
if ((config.file_upload as any).enabled && files?.length && supportVision)
data.files = files
handleSend(
`apps/${appId}/chat-messages`,
data,
{
onGetConversationMessages: (conversationId, getAbortController) => fetchConversationMessages(appId, conversationId, getAbortController),
onGetSuggestedQuestions: (responseItemId, getAbortController) => fetchSuggestedQuestions(appId, responseItemId, getAbortController),
},
)
}, [appId, chatList, config, handleSend, inputs, modelAndParameter.model, modelAndParameter.parameters, modelAndParameter.provider, textGenerationModelList])
const { eventEmitter } = useEventEmitterContextContext()
eventEmitter?.useSubscription((v: any) => {
if (v.type === APP_CHAT_WITH_MULTIPLE_MODEL)
doSend(v.payload.message, v.payload.files)
if (v.type === APP_CHAT_WITH_MULTIPLE_MODEL_RESTART)
handleRestart()
})
const allToolIcons = useMemo(() => {
const icons: Record<string, any> = {}
modelConfig.agentConfig.tools?.forEach((item: any) => {
icons[item.tool_name] = collectionList.find((collection: any) => canFindTool(collection.id, item.provider_id))?.icon
})
return icons
}, [collectionList, modelConfig.agentConfig.tools])
if (!chatList.length)
return null
return (
<Chat
config={config}
chatList={chatList}
isResponding={isResponding}
noChatInput
noStopResponding
chatContainerClassName='p-4'
chatFooterClassName='p-4 pb-0'
suggestedQuestions={suggestedQuestions}
onSend={doSend}
showPromptLog
questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size={40} />}
allToolIcons={allToolIcons}
hideLogModal
noSpacing
/>
)
}
export default memo(ChatItem)
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ModelAndParameter } from '../types'
import { noop } from 'lodash-es'
export type DebugWithMultipleModelContextType = {
multipleModelConfigs: ModelAndParameter[]
onMultipleModelConfigsChange: (multiple: boolean, modelConfigs: ModelAndParameter[]) => void
onDebugWithMultipleModelChange: (singleModelConfig: ModelAndParameter) => void
checkCanSend?: () => boolean
}
const DebugWithMultipleModelContext = createContext<DebugWithMultipleModelContextType>({
multipleModelConfigs: [],
onMultipleModelConfigsChange: noop,
onDebugWithMultipleModelChange: noop,
})
export const useDebugWithMultipleModelContext = () => useContext(DebugWithMultipleModelContext)
type DebugWithMultipleModelContextProviderProps = {
children: React.ReactNode
} & DebugWithMultipleModelContextType
export const DebugWithMultipleModelContextProvider = ({
children,
onMultipleModelConfigsChange,
multipleModelConfigs,
onDebugWithMultipleModelChange,
checkCanSend,
}: DebugWithMultipleModelContextProviderProps) => {
return (
<DebugWithMultipleModelContext.Provider value={{
onMultipleModelConfigsChange,
multipleModelConfigs,
onDebugWithMultipleModelChange,
checkCanSend,
}}>
{children}
</DebugWithMultipleModelContext.Provider>
)
}
export default DebugWithMultipleModelContext
import type { CSSProperties, FC } from 'react'
import { useTranslation } from 'react-i18next'
import { memo } from 'react'
import type { ModelAndParameter } from '../types'
import ModelParameterTrigger from './model-parameter-trigger'
import ChatItem from './chat-item'
import TextGenerationItem from './text-generation-item'
import { useDebugWithMultipleModelContext } from './context'
import { useDebugConfigurationContext } from '@/context/debug-configuration'
import Dropdown from '@/app/components/base/dropdown'
import type { Item } from '@/app/components/base/dropdown'
import { useProviderContext } from '@/context/provider-context'
import { ModelStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
type DebugItemProps = {
modelAndParameter: ModelAndParameter
className?: string
style?: CSSProperties
}
const DebugItem: FC<DebugItemProps> = ({
modelAndParameter,
className,
style,
}) => {
const { t } = useTranslation()
const { mode } = useDebugConfigurationContext()
const {
multipleModelConfigs,
onMultipleModelConfigsChange,
onDebugWithMultipleModelChange,
} = useDebugWithMultipleModelContext()
const { textGenerationModelList } = useProviderContext()
const index = multipleModelConfigs.findIndex(v => v.id === modelAndParameter.id)
const currentProvider = textGenerationModelList.find(item => item.provider === modelAndParameter.provider)
const currentModel = currentProvider?.models.find(item => item.model === modelAndParameter.model)
const handleSelect = (item: Item) => {
if (item.value === 'duplicate') {
if (multipleModelConfigs.length >= 4)
return
onMultipleModelConfigsChange(
true,
[
...multipleModelConfigs.slice(0, index + 1),
{
...modelAndParameter,
id: `${Date.now()}`,
},
...multipleModelConfigs.slice(index + 1),
],
)
}
if (item.value === 'debug-as-single-model')
onDebugWithMultipleModelChange(modelAndParameter)
if (item.value === 'remove') {
onMultipleModelConfigsChange(
true,
multipleModelConfigs.filter(item => item.id !== modelAndParameter.id),
)
}
}
return (
<div
className={`flex min-w-[320px] flex-col rounded-xl bg-background-section-burn ${className}`}
style={style}
>
<div className='flex h-10 shrink-0 items-center justify-between border-b-[0.5px] border-divider-regular px-3'>
<div className='flex h-5 w-6 items-center justify-center font-medium italic text-text-tertiary'>
#{index + 1}
</div>
<ModelParameterTrigger
modelAndParameter={modelAndParameter}
/>
<Dropdown
onSelect={handleSelect}
items={[
...(
multipleModelConfigs.length <= 3
? [
{
value: 'duplicate',
text: t('appDebug.duplicateModel'),
},
]
: []
),
...(
(modelAndParameter.provider && modelAndParameter.model)
? [
{
value: 'debug-as-single-model',
text: t('appDebug.debugAsSingleModel'),
},
]
: []
),
]}
secondItems={
multipleModelConfigs.length > 2
? [
{
value: 'remove',
text: t('common.operation.remove') as string,
},
]
: undefined
}
/>
</div>
<div style={{ height: 'calc(100% - 40px)' }}>
{
(mode === 'chat' || mode === 'agent-chat') && currentProvider && currentModel && currentModel.status === ModelStatusEnum.active && (
<ChatItem modelAndParameter={modelAndParameter} />
)
}
{
mode === 'completion' && currentProvider && currentModel && currentModel.status === ModelStatusEnum.active && (
<TextGenerationItem modelAndParameter={modelAndParameter}/>
)
}
</div>
</div>
)
}
export default memo(DebugItem)
import type { FC } from 'react'
import {
memo,
useCallback,
useMemo,
} from 'react'
import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../types'
import DebugItem from './debug-item'
import {
DebugWithMultipleModelContextProvider,
useDebugWithMultipleModelContext,
} from './context'
import type { DebugWithMultipleModelContextType } from './context'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import ChatInputArea from '@/app/components/base/chat/chat/chat-input-area'
import { useDebugConfigurationContext } from '@/context/debug-configuration'
import { useFeatures } from '@/app/components/base/features/hooks'
import { useStore as useAppStore } from '@/app/components/app/store'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { InputForm } from '@/app/components/base/chat/chat/type'
const DebugWithMultipleModel = () => {
const {
mode,
inputs,
modelConfig,
} = useDebugConfigurationContext()
const speech2text = useFeatures(s => s.features.speech2text)
const file = useFeatures(s => s.features.file)
const {
multipleModelConfigs,
checkCanSend,
} = useDebugWithMultipleModelContext()
const { eventEmitter } = useEventEmitterContextContext()
const isChatMode = mode === 'chat' || mode === 'agent-chat'
const handleSend = useCallback((message: string, files?: FileEntity[]) => {
if (checkCanSend && !checkCanSend())
return
eventEmitter?.emit({
type: APP_CHAT_WITH_MULTIPLE_MODEL,
payload: {
message,
files,
},
} as any)
}, [eventEmitter, checkCanSend])
const twoLine = multipleModelConfigs.length === 2
const threeLine = multipleModelConfigs.length === 3
const fourLine = multipleModelConfigs.length === 4
const size = useMemo(() => {
let width = ''
let height = ''
if (twoLine) {
width = 'calc(50% - 4px - 24px)'
height = '100%'
}
if (threeLine) {
width = 'calc(33.3% - 5.33px - 16px)'
height = '100%'
}
if (fourLine) {
width = 'calc(50% - 4px - 24px)'
height = 'calc(50% - 4px)'
}
return {
width,
height,
}
}, [twoLine, threeLine, fourLine])
const position = useCallback((idx: number) => {
let translateX = '0'
let translateY = '0'
if (twoLine && idx === 1)
translateX = 'calc(100% + 8px)'
if (threeLine && idx === 1)
translateX = 'calc(100% + 8px)'
if (threeLine && idx === 2)
translateX = 'calc(200% + 16px)'
if (fourLine && idx === 1)
translateX = 'calc(100% + 8px)'
if (fourLine && idx === 2)
translateY = 'calc(100% + 8px)'
if (fourLine && idx === 3) {
translateX = 'calc(100% + 8px)'
translateY = 'calc(100% + 8px)'
}
return {
translateX,
translateY,
}
}, [twoLine, threeLine, fourLine])
const setShowAppConfigureFeaturesModal = useAppStore(s => s.setShowAppConfigureFeaturesModal)
const inputsForm = modelConfig.configs.prompt_variables.filter(item => item.type !== 'api').map(item => ({ ...item, label: item.name, variable: item.key })) as InputForm[]
return (
<div className='flex h-full flex-col'>
<div
className={`
relative mb-3 grow overflow-auto px-6
`}
style={{ height: isChatMode ? 'calc(100% - 60px)' : '100%' }}
>
{
multipleModelConfigs.map((modelConfig, index) => (
<DebugItem
key={modelConfig.id}
modelAndParameter={modelConfig}
className={`
absolute left-6 top-0 min-h-[200px]
${twoLine && index === 0 && 'mr-2'}
${threeLine && (index === 0 || index === 1) && 'mr-2'}
${fourLine && (index === 0 || index === 2) && 'mr-2'}
${fourLine && (index === 0 || index === 1) && 'mb-2'}
`}
style={{
width: size.width,
height: size.height,
transform: `translateX(${position(index).translateX}) translateY(${position(index).translateY})`,
}}
/>
))
}
</div>
{isChatMode && (
<div className='shrink-0 px-6 pb-0'>
<ChatInputArea
showFeatureBar
showFileUpload={false}
onFeatureBarClick={setShowAppConfigureFeaturesModal}
onSend={handleSend}
speechToTextConfig={speech2text as any}
visionConfig={file}
inputs={inputs}
inputsForm={inputsForm}
/>
</div>
)}
</div>
)
}
const DebugWithMultipleModelMemoed = memo(DebugWithMultipleModel)
const DebugWithMultipleModelWrapper: FC<DebugWithMultipleModelContextType> = ({
onMultipleModelConfigsChange,
multipleModelConfigs,
onDebugWithMultipleModelChange,
checkCanSend,
}) => {
return (
<DebugWithMultipleModelContextProvider
onMultipleModelConfigsChange={onMultipleModelConfigsChange}
multipleModelConfigs={multipleModelConfigs}
onDebugWithMultipleModelChange={onDebugWithMultipleModelChange}
checkCanSend={checkCanSend}
>
<DebugWithMultipleModelMemoed />
</DebugWithMultipleModelContextProvider>
)
}
export default memo(DebugWithMultipleModelWrapper)
import type { FC } from 'react'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import { RiArrowDownSLine } from '@remixicon/react'
import type { ModelAndParameter } from '../types'
import { useDebugWithMultipleModelContext } from './context'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import ModelIcon from '@/app/components/header/account-setting/model-provider-page/model-icon'
import ModelName from '@/app/components/header/account-setting/model-provider-page/model-name'
import {
MODEL_STATUS_TEXT,
ModelStatusEnum,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useDebugConfigurationContext } from '@/context/debug-configuration'
import { CubeOutline } from '@/app/components/base/icons/src/vender/line/shapes'
import Tooltip from '@/app/components/base/tooltip'
import { AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
type ModelParameterTriggerProps = {
modelAndParameter: ModelAndParameter
}
const ModelParameterTrigger: FC<ModelParameterTriggerProps> = ({
modelAndParameter,
}) => {
const { t } = useTranslation()
const {
mode,
isAdvancedMode,
} = useDebugConfigurationContext()
const {
multipleModelConfigs,
onMultipleModelConfigsChange,
onDebugWithMultipleModelChange,
} = useDebugWithMultipleModelContext()
const language = useLanguage()
const index = multipleModelConfigs.findIndex(v => v.id === modelAndParameter.id)
const handleSelectModel = ({ modelId, provider }: { modelId: string; provider: string }) => {
const newModelConfigs = [...multipleModelConfigs]
newModelConfigs[index] = {
...newModelConfigs[index],
model: modelId,
provider,
}
onMultipleModelConfigsChange(true, newModelConfigs)
}
const handleParamsChange = (params: any) => {
const newModelConfigs = [...multipleModelConfigs]
newModelConfigs[index] = {
...newModelConfigs[index],
parameters: params,
}
onMultipleModelConfigsChange(true, newModelConfigs)
}
return (
<ModelParameterModal
mode={mode}
isAdvancedMode={isAdvancedMode}
provider={modelAndParameter.provider}
modelId={modelAndParameter.model}
completionParams={modelAndParameter.parameters}
onCompletionParamsChange={handleParamsChange}
setModel={handleSelectModel}
debugWithMultipleModel
onDebugWithMultipleModelChange={() => onDebugWithMultipleModelChange(modelAndParameter)}
renderTrigger={({
open,
currentProvider,
currentModel,
}) => (
<div
className={`
flex h-8 max-w-[200px] cursor-pointer items-center rounded-lg px-2
${open && 'bg-state-base-hover'}
${currentModel && currentModel.status !== ModelStatusEnum.active && '!bg-[#FFFAEB]'}
`}
>
{
currentProvider && (
<ModelIcon
className='mr-1 !h-4 !w-4'
provider={currentProvider}
modelName={currentModel?.model}
/>
)
}
{
!currentProvider && (
<div className='mr-1 flex h-4 w-4 items-center justify-center rounded'>
<CubeOutline className='h-4 w-4 text-text-accent' />
</div>
)
}
{
currentModel && (
<ModelName
className='mr-0.5 text-text-secondary'
modelItem={currentModel}
/>
)
}
{
!currentModel && (
<div className='mr-0.5 truncate text-[13px] font-medium text-text-accent'>
{t('common.modelProvider.selectModel')}
</div>
)
}
<RiArrowDownSLine className={`h-3 w-3 ${(currentModel && currentProvider) ? 'text-text-tertiary' : 'text-text-accent'}`} />
{
currentModel && currentModel.status !== ModelStatusEnum.active && (
<Tooltip popupContent={MODEL_STATUS_TEXT[currentModel.status][language]}>
<AlertTriangle className='h-4 w-4 text-[#F79009]' />
</Tooltip>
)
}
</div>
)}
/>
)
}
export default memo(ModelParameterTrigger)
import type { FC } from 'react'
import { memo } from 'react'
import type { ModelAndParameter } from '../types'
import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../types'
import type {
OnSend,
TextGenerationConfig,
} from '@/app/components/base/text-generation/types'
import { useTextGeneration } from '@/app/components/base/text-generation/hooks'
import TextGeneration from '@/app/components/app/text-generate/item'
import { useDebugConfigurationContext } from '@/context/debug-configuration'
import { promptVariablesToUserInputsForm } from '@/utils/model-config'
import { TransferMethod } from '@/app/components/base/chat/types'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { useProviderContext } from '@/context/provider-context'
import { useFeatures } from '@/app/components/base/features/hooks'
import { noop } from 'lodash-es'
type TextGenerationItemProps = {
modelAndParameter: ModelAndParameter
}
const TextGenerationItem: FC<TextGenerationItemProps> = ({
modelAndParameter,
}) => {
const {
isAdvancedMode,
modelConfig,
appId,
inputs,
promptMode,
speechToTextConfig,
introduction,
suggestedQuestionsAfterAnswerConfig,
citationConfig,
externalDataToolsConfig,
chatPromptConfig,
completionPromptConfig,
dataSets,
datasetConfigs,
} = useDebugConfigurationContext()
const { textGenerationModelList } = useProviderContext()
const features = useFeatures(s => s.features)
const postDatasets = dataSets.map(({ id }) => ({
dataset: {
enabled: true,
id,
},
}))
const contextVar = modelConfig.configs.prompt_variables.find(item => item.is_context_var)?.key
const config: TextGenerationConfig = {
pre_prompt: !isAdvancedMode ? modelConfig.configs.prompt_template : '',
prompt_type: promptMode,
chat_prompt_config: isAdvancedMode ? chatPromptConfig : {},
completion_prompt_config: isAdvancedMode ? completionPromptConfig : {},
user_input_form: promptVariablesToUserInputsForm(modelConfig.configs.prompt_variables),
dataset_query_variable: contextVar || '',
// features
more_like_this: features.moreLikeThis as any,
sensitive_word_avoidance: features.moderation as any,
text_to_speech: features.text2speech as any,
file_upload: features.file as any,
opening_statement: introduction,
speech_to_text: speechToTextConfig,
suggested_questions_after_answer: suggestedQuestionsAfterAnswerConfig,
retriever_resource: citationConfig,
external_data_tools: externalDataToolsConfig,
agent_mode: {
enabled: false,
tools: [],
},
dataset_configs: {
...datasetConfigs,
datasets: {
datasets: [...postDatasets],
} as any,
},
}
const {
completion,
handleSend,
isResponding,
messageId,
} = useTextGeneration()
const doSend: OnSend = (message, files) => {
const currentProvider = textGenerationModelList.find(item => item.provider === modelAndParameter.provider)
const currentModel = currentProvider?.models.find(model => model.model === modelAndParameter.model)
const configData = {
...config,
model: {
provider: modelAndParameter.provider,
name: modelAndParameter.model,
mode: currentModel?.model_properties.mode,
completion_params: modelAndParameter.parameters,
},
}
const data: any = {
inputs,
model_config: configData,
}
if ((config.file_upload as any).enabled && files && files?.length > 0) {
data.files = files.map((item) => {
if (item.transfer_method === TransferMethod.local_file) {
return {
...item,
url: '',
}
}
return item
})
}
handleSend(
`apps/${appId}/completion-messages`,
data,
)
}
const { eventEmitter } = useEventEmitterContextContext()
eventEmitter?.useSubscription((v: any) => {
if (v.type === APP_CHAT_WITH_MULTIPLE_MODEL)
doSend(v.payload.message, v.payload.files)
})
return (
<TextGeneration
className='flex h-full flex-col overflow-y-auto border-none'
content={completion}
isLoading={!completion && isResponding}
isResponding={isResponding}
isInstalledApp={false}
siteInfo={null}
messageId={messageId}
isError={false}
onRetry={noop}
inSidePanel
/>
)
}
export default memo(TextGenerationItem)
import { memo, useCallback, useImperativeHandle, useMemo } from "react";
import {
useConfigFromDebugContext,
useFormattingChangedSubscription,
} from "../hooks";
import Chat from "@/app/components/base/chat/chat";
import { useChat } from "@/app/components/base/chat/chat/hooks";
import { useDebugConfigurationContext } from "@/context/debug-configuration";
import type {
ChatConfig,
ChatItem,
ChatItemInTree,
OnSend,
} from "@/app/components/base/chat/types";
import { useProviderContext } from "@/context/provider-context";
import {
fetchConversationMessages,
fetchSuggestedQuestions,
stopChatMessageResponding,
} from "@/service/debug";
import Avatar from "@/app/components/base/avatar";
import { useAppContext } from "@/context/app-context";
import { ModelFeatureEnum } from "@/app/components/header/account-setting/model-provider-page/declarations";
import { useStore as useAppStore } from "@/app/components/app/store";
import { useFeatures } from "@/app/components/base/features/hooks";
import {
getLastAnswer,
isValidGeneratedAnswer,
} from "@/app/components/base/chat/utils";
import type { InputForm } from "@/app/components/base/chat/chat/type";
import { canFindTool } from "@/utils";
type DebugWithSingleModelProps = {
checkCanSend?: () => boolean;
};
export type DebugWithSingleModelRefType = {
handleRestart: () => void;
};
const DebugWithSingleModel = ({
ref,
checkCanSend,
}: DebugWithSingleModelProps & {
ref: React.RefObject<DebugWithSingleModelRefType>;
}) => {
const { userProfile } = useAppContext();
const {
modelConfig,
appId,
inputs,
collectionList,
completionParams,
// isShowVisionConfig,
} = useDebugConfigurationContext();
const { textGenerationModelList } = useProviderContext();
const features = useFeatures((s) => s.features);
const configTemplate = useConfigFromDebugContext();
const config = useMemo(() => {
return {
...configTemplate,
more_like_this: features.moreLikeThis,
opening_statement: features.opening?.enabled
? features.opening?.opening_statement || ""
: "",
suggested_questions: features.opening?.enabled
? features.opening?.suggested_questions || []
: [],
sensitive_word_avoidance: features.moderation,
speech_to_text: features.speech2text,
text_to_speech: features.text2speech,
file_upload: features.file,
suggested_questions_after_answer: features.suggested,
retriever_resource: features.citation,
annotation_reply: features.annotationReply,
} as ChatConfig;
}, [configTemplate, features]);
const inputsForm = useMemo(() => {
return modelConfig.configs.prompt_variables
.filter((item) => item.type !== "api")
.map((item) => ({
...item,
label: item.name,
variable: item.key,
})) as InputForm[];
}, [modelConfig.configs.prompt_variables]);
const {
chatList,
setTargetMessageId,
isResponding,
handleSend,
suggestedQuestions,
handleStop,
handleRestart,
handleAnnotationAdded,
handleAnnotationEdited,
handleAnnotationRemoved,
} = useChat(
config,
{
inputs,
inputsForm,
},
[],
(taskId) => stopChatMessageResponding(appId, taskId)
);
useFormattingChangedSubscription(chatList);
const doSend: OnSend = useCallback(
(
message,
files,
isRegenerate = false,
parentAnswer: ChatItem | null = null
) => {
if (checkCanSend && !checkCanSend()) return;
const currentProvider = textGenerationModelList.find(
(item) => item.provider === modelConfig.provider
);
const currentModel = currentProvider?.models.find(
(model) => model.model === modelConfig.model_id
);
const supportVision = currentModel?.features?.includes(
ModelFeatureEnum.vision
);
const configData = {
...config,
model: {
provider: modelConfig.provider,
name: modelConfig.model_id,
mode: modelConfig.mode,
completion_params: completionParams,
},
};
const data: any = {
query: message,
inputs,
model_config: configData,
parent_message_id:
(isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) ||
null,
};
if (
(config.file_upload as any)?.enabled &&
files?.length &&
supportVision
)
data.files = files;
handleSend(`apps/${appId}/chat-messages`, data, {
onGetConversationMessages: (conversationId, getAbortController) =>
fetchConversationMessages(appId, conversationId, getAbortController),
onGetSuggestedQuestions: (responseItemId, getAbortController) =>
fetchSuggestedQuestions(appId, responseItemId, getAbortController),
});
},
[
appId,
chatList,
checkCanSend,
completionParams,
config,
handleSend,
inputs,
modelConfig.mode,
modelConfig.model_id,
modelConfig.provider,
textGenerationModelList,
]
);
const doRegenerate = useCallback(
(chatItem: ChatItemInTree) => {
const question = chatList.find(
(item) => item.id === chatItem.parentMessageId
)!;
const parentAnswer = chatList.find(
(item) => item.id === question.parentMessageId
);
// doSend(question.content, question.message_files, true, isValidGeneratedAnswer(parentAnswer) ? parentAnswer : null)
},
[chatList, doSend]
);
const allToolIcons = useMemo(() => {
const icons: Record<string, any> = {};
modelConfig.agentConfig.tools?.forEach((item: any) => {
icons[item.tool_name] = collectionList.find((collection: any) =>
canFindTool(collection.id, item.provider_id)
)?.icon;
});
return icons;
}, [collectionList, modelConfig.agentConfig.tools]);
useImperativeHandle(
ref,
() => {
return {
handleRestart,
};
},
[handleRestart]
);
const setShowAppConfigureFeaturesModal = useAppStore(
(s) => s.setShowAppConfigureFeaturesModal
);
return (
<Chat
config={config}
chatList={chatList}
isResponding={isResponding}
chatContainerClassName="px-3 pt-6"
chatFooterClassName="px-3 pt-10 pb-0"
showFeatureBar
showFileUpload={false}
onFeatureBarClick={setShowAppConfigureFeaturesModal}
suggestedQuestions={suggestedQuestions}
onSend={doSend}
inputs={inputs}
inputsForm={inputsForm}
onRegenerate={doRegenerate}
switchSibling={(siblingMessageId) => setTargetMessageId(siblingMessageId)}
onStopResponding={handleStop}
showPromptLog
questionIcon={
<Avatar
avatar={userProfile.avatar_url}
name={userProfile.name}
size={40}
/>
}
allToolIcons={allToolIcons}
onAnnotationEdited={handleAnnotationEdited}
onAnnotationAdded={handleAnnotationAdded}
onAnnotationRemoved={handleAnnotationRemoved}
noSpacing
/>
);
};
DebugWithSingleModel.displayName = "DebugWithSingleModel";
export default memo(DebugWithSingleModel);
import {
useCallback,
useRef,
useState,
} from 'react'
import type {
DebugWithSingleOrMultipleModelConfigs,
ModelAndParameter,
} from './types'
import { ORCHESTRATE_CHANGED } from './types'
import type {
ChatConfig,
ChatItem,
} from '@/app/components/base/chat/types'
import {
AgentStrategy,
} from '@/types/app'
import { promptVariablesToUserInputsForm } from '@/utils/model-config'
import { useDebugConfigurationContext } from '@/context/debug-configuration'
import { useEventEmitterContextContext } from '@/context/event-emitter'
export const useDebugWithSingleOrMultipleModel = (appId: string) => {
const localeDebugWithSingleOrMultipleModelConfigs = localStorage.getItem('app-debug-with-single-or-multiple-models')
const debugWithSingleOrMultipleModelConfigs = useRef<DebugWithSingleOrMultipleModelConfigs>({})
if (localeDebugWithSingleOrMultipleModelConfigs) {
try {
debugWithSingleOrMultipleModelConfigs.current = JSON.parse(localeDebugWithSingleOrMultipleModelConfigs) || {}
}
catch (e) {
console.error(e)
}
}
const [
debugWithMultipleModel,
setDebugWithMultipleModel,
] = useState(debugWithSingleOrMultipleModelConfigs.current[appId]?.multiple || false)
const [
multipleModelConfigs,
setMultipleModelConfigs,
] = useState(debugWithSingleOrMultipleModelConfigs.current[appId]?.configs || [])
const handleMultipleModelConfigsChange = useCallback((
multiple: boolean,
modelConfigs: ModelAndParameter[],
) => {
const value = {
multiple,
configs: modelConfigs,
}
debugWithSingleOrMultipleModelConfigs.current[appId] = value
localStorage.setItem('app-debug-with-single-or-multiple-models', JSON.stringify(debugWithSingleOrMultipleModelConfigs.current))
setDebugWithMultipleModel(value.multiple)
setMultipleModelConfigs(value.configs)
}, [appId])
return {
debugWithMultipleModel,
multipleModelConfigs,
handleMultipleModelConfigsChange,
}
}
export const useConfigFromDebugContext = () => {
const {
isAdvancedMode,
modelConfig,
appId,
promptMode,
speechToTextConfig,
introduction,
suggestedQuestions: openingSuggestedQuestions,
suggestedQuestionsAfterAnswerConfig,
citationConfig,
moderationConfig,
chatPromptConfig,
completionPromptConfig,
dataSets,
datasetConfigs,
visionConfig,
annotationConfig,
textToSpeechConfig,
isFunctionCall,
} = useDebugConfigurationContext()
const postDatasets = dataSets.map(({ id }) => ({
dataset: {
enabled: true,
id,
},
}))
const contextVar = modelConfig.configs.prompt_variables.find(item => item.is_context_var)?.key
const config: ChatConfig = {
pre_prompt: !isAdvancedMode ? modelConfig.configs.prompt_template : '',
prompt_type: promptMode,
chat_prompt_config: isAdvancedMode ? chatPromptConfig : {},
completion_prompt_config: isAdvancedMode ? completionPromptConfig : {},
user_input_form: promptVariablesToUserInputsForm(modelConfig.configs.prompt_variables),
dataset_query_variable: contextVar || '',
opening_statement: introduction,
more_like_this: {
enabled: false,
},
suggested_questions: openingSuggestedQuestions,
suggested_questions_after_answer: suggestedQuestionsAfterAnswerConfig,
text_to_speech: textToSpeechConfig,
speech_to_text: speechToTextConfig,
retriever_resource: citationConfig,
sensitive_word_avoidance: moderationConfig,
agent_mode: {
...modelConfig.agentConfig,
strategy: isFunctionCall ? AgentStrategy.functionCall : AgentStrategy.react,
},
dataset_configs: {
...datasetConfigs,
datasets: {
datasets: [...postDatasets],
} as any,
},
file_upload: {
image: visionConfig,
},
annotation_reply: annotationConfig,
supportAnnotation: true,
appId,
supportCitationHitInfo: true,
}
return config
}
export const useFormattingChangedDispatcher = () => {
const { eventEmitter } = useEventEmitterContextContext()
const dispatcher = useCallback(() => {
eventEmitter?.emit({
type: ORCHESTRATE_CHANGED,
} as any)
}, [eventEmitter])
return dispatcher
}
export const useFormattingChangedSubscription = (chatList: ChatItem[]) => {
const {
formattingChanged,
setFormattingChanged,
} = useDebugConfigurationContext()
const { eventEmitter } = useEventEmitterContextContext()
eventEmitter?.useSubscription((v: any) => {
if (v.type === ORCHESTRATE_CHANGED) {
if (chatList.some(item => item.isAnswer) && !formattingChanged)
setFormattingChanged(true)
}
})
}
export type ModelAndParameter = {
id: string
model: string
provider: string
parameters: Record<string, any>
}
export type MultipleAndConfigs = {
multiple: boolean
configs: ModelAndParameter[]
}
export type DebugWithSingleOrMultipleModelConfigs = {
[k: string]: MultipleAndConfigs
}
export const APP_CHAT_WITH_MULTIPLE_MODEL = 'APP_CHAT_WITH_MULTIPLE_MODEL'
export const APP_CHAT_WITH_MULTIPLE_MODEL_RESTART = 'APP_CHAT_WITH_MULTIPLE_MODEL_RESTART'
export const ORCHESTRATE_CHANGED = 'ORCHESTRATE_CHANGED'
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import GroupName from '../../base/group-name'
import TextToSpeech from '../chat-group/text-to-speech'
import MoreLikeThis from './more-like-this'
/*
* Include
* 1. More like this
*/
type ExperienceGroupProps = {
isShowTextToSpeech: boolean
isShowMoreLike: boolean
}
const ExperienceEnhanceGroup: FC<ExperienceGroupProps> = ({
isShowTextToSpeech,
isShowMoreLike,
}) => {
const { t } = useTranslation()
return (
<div className='mt-7'>
<GroupName name={t('appDebug.feature.groupExperience.title')}/>
<div className='space-y-3'>
{
isShowMoreLike && (
<MoreLikeThis/>
)
}
{
isShowTextToSpeech && (
<TextToSpeech/>
)
}
</div>
</div>
)
}
export default React.memo(ExperienceEnhanceGroup)
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { XMarkIcon } from '@heroicons/react/24/outline'
import { useLocalStorageState } from 'ahooks'
import MoreLikeThisIcon from '../../../base/icons/more-like-this-icon'
import Panel from '@/app/components/app/configuration/base/feature-panel'
const GENERATE_NUM = 1
const warningIcon = (
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" clipRule="evenodd" d="M6.40616 0.834307C6.14751 0.719294 5.85222 0.719294 5.59356 0.834307C5.3938 0.923133 5.26403 1.07959 5.17373 1.20708C5.08495 1.33242 4.9899 1.49664 4.88536 1.67723L0.751783 8.81705C0.646828 8.9983 0.551451 9.16302 0.486781 9.3028C0.421056 9.44487 0.349754 9.63584 0.372478 9.85381C0.401884 10.1359 0.549654 10.3922 0.779012 10.5589C0.956259 10.6878 1.15726 10.7218 1.31314 10.7361C1.46651 10.7501 1.65684 10.7501 1.86628 10.7501H10.1334C10.3429 10.7501 10.5332 10.7501 10.6866 10.7361C10.8425 10.7218 11.0435 10.6878 11.2207 10.5589C11.4501 10.3922 11.5978 10.1359 11.6272 9.85381C11.65 9.63584 11.5787 9.44487 11.5129 9.3028C11.4483 9.16303 11.3529 8.99833 11.248 8.81709L7.11436 1.67722C7.00983 1.49663 6.91477 1.33242 6.82599 1.20708C6.73569 1.07959 6.60593 0.923133 6.40616 0.834307ZM6.49988 4.50012C6.49988 4.22398 6.27602 4.00012 5.99988 4.00012C5.72374 4.00012 5.49988 4.22398 5.49988 4.50012V6.50012C5.49988 6.77626 5.72374 7.00012 5.99988 7.00012C6.27602 7.00012 6.49988 6.77626 6.49988 6.50012V4.50012ZM5.99988 8.00012C5.72374 8.00012 5.49988 8.22398 5.49988 8.50012C5.49988 8.77626 5.72374 9.00012 5.99988 9.00012H6.00488C6.28102 9.00012 6.50488 8.77626 6.50488 8.50012C6.50488 8.22398 6.28102 8.00012 6.00488 8.00012H5.99988Z" fill="#F79009" />
</svg>
)
const MoreLikeThis: FC = () => {
const { t } = useTranslation()
const [isHideTip, setIsHideTip] = useLocalStorageState('isHideMoreLikeThisTip', {
defaultValue: false,
})
const headerRight = (
<div className='text-xs text-gray-500'>{t('appDebug.feature.moreLikeThis.generateNumTip')} {GENERATE_NUM}</div>
)
return (
<Panel
className='mt-4'
title={t('appDebug.feature.moreLikeThis.title')}
headerIcon={<MoreLikeThisIcon />}
headerRight={headerRight}
noBodySpacing
>
{!isHideTip && (
<div className='flex h-9 items-center justify-between rounded-b-xl bg-[#FFFAEB] px-3 text-xs text-gray-700'>
<div className='flex items-center space-x-2'>
<div>{warningIcon}</div>
<div>{t('appDebug.feature.moreLikeThis.tip')}</div>
</div>
<div className='flex h-4 w-4 cursor-pointer items-center justify-center' onClick={() => setIsHideTip(true)}>
<XMarkIcon className="h-3 w-3" />
</div>
</div>
)}
</Panel>
)
}
export default React.memo(MoreLikeThis)
import { useState } from 'react'
import { clone } from 'lodash-es'
import produce from 'immer'
import type { ChatPromptConfig, CompletionPromptConfig, ConversationHistoriesRole, PromptItem } from '@/models/debug'
import { PromptMode } from '@/models/debug'
import { ModelModeType } from '@/types/app'
import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
import { PRE_PROMPT_PLACEHOLDER_TEXT, checkHasContextBlock, checkHasHistoryBlock, checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'
import { fetchPromptTemplate } from '@/service/debug'
import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
type Param = {
appMode: string
modelModeType: ModelModeType
modelName: string
promptMode: PromptMode
prePrompt: string
onUserChangedPrompt: () => void
hasSetDataSet: boolean
completionParams: FormValue
setCompletionParams: (params: FormValue) => void
setStop: (stop: string[]) => void
}
const useAdvancedPromptConfig = ({
appMode,
modelModeType,
modelName,
promptMode,
prePrompt,
onUserChangedPrompt,
hasSetDataSet,
completionParams,
setCompletionParams,
setStop,
}: Param) => {
const isAdvancedPrompt = promptMode === PromptMode.advanced
const [chatPromptConfig, setChatPromptConfig] = useState<ChatPromptConfig>(clone(DEFAULT_CHAT_PROMPT_CONFIG))
const [completionPromptConfig, setCompletionPromptConfig] = useState<CompletionPromptConfig>(clone(DEFAULT_COMPLETION_PROMPT_CONFIG))
const currentAdvancedPrompt = (() => {
if (!isAdvancedPrompt)
return []
return (modelModeType === ModelModeType.chat) ? chatPromptConfig.prompt : completionPromptConfig.prompt
})()
const setCurrentAdvancedPrompt = (prompt: PromptItem | PromptItem[], isUserChanged?: boolean) => {
if (!isAdvancedPrompt)
return
if (modelModeType === ModelModeType.chat) {
setChatPromptConfig({
...chatPromptConfig,
prompt: prompt as PromptItem[],
})
}
else {
setCompletionPromptConfig({
...completionPromptConfig,
prompt: prompt as PromptItem,
})
}
if (isUserChanged)
onUserChangedPrompt()
}
const setConversationHistoriesRole = (conversationHistoriesRole: ConversationHistoriesRole) => {
setCompletionPromptConfig({
...completionPromptConfig,
conversation_histories_role: conversationHistoriesRole,
})
}
const hasSetBlockStatus = (() => {
if (!isAdvancedPrompt) {
return {
context: checkHasContextBlock(prePrompt),
history: false,
query: false,
}
}
if (modelModeType === ModelModeType.chat) {
return {
context: !!chatPromptConfig.prompt.find(p => checkHasContextBlock(p.text)),
history: false,
query: !!chatPromptConfig.prompt.find(p => checkHasQueryBlock(p.text)),
}
}
else {
const prompt = completionPromptConfig.prompt?.text
return {
context: checkHasContextBlock(prompt),
history: checkHasHistoryBlock(prompt),
query: checkHasQueryBlock(prompt),
}
}
})()
/* prompt: simple to advanced process, or chat model to completion model
* 1. migrate prompt
* 2. change promptMode to advanced
*/
const migrateToDefaultPrompt = async (isMigrateToCompetition?: boolean, toModelModeType?: ModelModeType) => {
const mode = modelModeType
const toReplacePrePrompt = prePrompt || ''
if (!isAdvancedPrompt) {
const { chat_prompt_config, completion_prompt_config, stop } = await fetchPromptTemplate({
appMode,
mode,
modelName,
hasSetDataSet,
})
if (modelModeType === ModelModeType.chat) {
const newPromptConfig = produce(chat_prompt_config, (draft) => {
draft.prompt = draft.prompt.map((p) => {
return {
...p,
text: p.text.replace(PRE_PROMPT_PLACEHOLDER_TEXT, toReplacePrePrompt),
}
})
})
setChatPromptConfig(newPromptConfig)
}
else {
const newPromptConfig = produce(completion_prompt_config, (draft) => {
draft.prompt.text = draft.prompt.text.replace(PRE_PROMPT_PLACEHOLDER_TEXT, toReplacePrePrompt)
})
setCompletionPromptConfig(newPromptConfig)
setCompletionParams({
...completionParams,
stop,
})
}
return
}
if (isMigrateToCompetition) {
const { completion_prompt_config, chat_prompt_config, stop } = await fetchPromptTemplate({
appMode,
mode: toModelModeType as ModelModeType,
modelName,
hasSetDataSet,
})
if (toModelModeType === ModelModeType.completion) {
const newPromptConfig = produce(completion_prompt_config, (draft) => {
if (!completionPromptConfig.prompt?.text)
draft.prompt.text = draft.prompt.text.replace(PRE_PROMPT_PLACEHOLDER_TEXT, toReplacePrePrompt)
else
draft.prompt.text = completionPromptConfig.prompt?.text.replace(PRE_PROMPT_PLACEHOLDER_TEXT, toReplacePrePrompt)
if (['advanced-chat', 'agent-chat', 'chat'].includes(appMode) && completionPromptConfig.conversation_histories_role.assistant_prefix && completionPromptConfig.conversation_histories_role.user_prefix)
draft.conversation_histories_role = completionPromptConfig.conversation_histories_role
})
setCompletionPromptConfig(newPromptConfig)
if (!completionParams.stop || completionParams.stop.length === 0) {
setCompletionParams({
...completionParams,
stop,
})
}
setStop(stop) // switch mode's params is async. It may override the stop value.
}
else {
const newPromptConfig = produce(chat_prompt_config, (draft) => {
draft.prompt = draft.prompt.map((p) => {
return {
...p,
text: p.text.replace(PRE_PROMPT_PLACEHOLDER_TEXT, toReplacePrePrompt),
}
})
})
setChatPromptConfig(newPromptConfig)
}
}
}
return {
chatPromptConfig,
setChatPromptConfig,
completionPromptConfig,
setCompletionPromptConfig,
currentAdvancedPrompt,
setCurrentAdvancedPrompt,
hasSetBlockStatus,
setConversationHistoriesRole,
migrateToDefaultPrompt,
}
}
export default useAdvancedPromptConfig
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!