Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

7.1 KB
Raw Blame
import type { OnFeaturesChange } from '@/app/components/base/features/types'
import type { AnnotationReplyConfig } from '@/models/debug'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiEqualizer2Line, RiExternalLinkLine } from '@remixicon/react'
import { produce } from 'immer'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import ConfigParamModal from '@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal'
import useAnnotationConfig from '@/app/components/base/features/new-feature-panel/annotation-reply/use-annotation-config'
import FeatureCard from '@/app/components/base/features/new-feature-panel/feature-card'
import AnnotationFullModal from '@/app/components/billing/annotation-full/modal'
import { toast } from '@/app/notifications'
import { ANNOTATION_DEFAULT } from '@/config'
import Link from '@/next/link'
import { usePathname } from '@/next/navigation'
import { getErrorMessage } from '@/utils/error-message'

type Props = Readonly<{
  disabled?: boolean
  onChange?: OnFeaturesChange
}>

const AnnotationReply = ({ disabled, onChange }: Props) => {
  const { t } = useTranslation(['appDebug', 'common', 'modelProvider'])
  const pathname = usePathname()
  const matched = /\/app\/([^/]+)/.exec(pathname)
  const appId = matched?.length && matched[1] ? matched[1] : ''
  const featuresStore = useFeaturesStore()
  const annotationReply = useFeatures((s) => s.features.annotationReply)
  const [isDisabling, setIsDisabling] = useState(false)

  const updateAnnotationReply = useCallback(
    (newConfig: AnnotationReplyConfig) => {
      const { features, setFeatures } = featuresStore!.getState()
      const newFeatures = produce(features, (draft) => {
        draft.annotationReply = newConfig
      })
      setFeatures(newFeatures)
      onChange?.()
    },
    [featuresStore, onChange],
  )

  const {
    isAnnotationQuotaUnavailable,
    handleEnableAnnotation,
    handleDisableAnnotation,
    isShowAnnotationConfigInit,
    setIsShowAnnotationConfigInit,
    isShowAnnotationFullModal,
    setIsShowAnnotationFullModal,
  } = useAnnotationConfig({
    appId,
    annotationConfig: (annotationReply as any) || {
      id: '',
      enabled: false,
      score_threshold: ANNOTATION_DEFAULT.score_threshold,
      embedding_model: {
        embedding_provider_name: '',
        embedding_model_name: '',
      },
    },
    setAnnotationConfig: updateAnnotationReply,
  })

  const handleSwitch = useCallback(
    async (enabled: boolean) => {
      if (isDisabling) return
      if (enabled) setIsShowAnnotationConfigInit(true)
      else {
        setIsDisabling(true)
        try {
          await handleDisableAnnotation(annotationReply?.embedding_model as any)
        } catch (error) {
          toast.error(getErrorMessage(error) || t(($) => $['api.actionFailed'], { ns: 'common' }))
        } finally {
          setIsDisabling(false)
        }
      }
    },
    [
      annotationReply?.embedding_model,
      handleDisableAnnotation,
      isDisabling,
      setIsShowAnnotationConfigInit,
      t,
    ],
  )

  const [isHovering, setIsHovering] = useState(false)

  return (
    <>
      <FeatureCard
        icon={
          <div className="shrink-0 rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-indigo-indigo-600 p-1 shadow-xs">
            <span
              aria-hidden
              className="i-custom-vender-features-message-fast size-4 text-text-primary-on-surface"
            />
          </div>
        }
        title={t(($) => $['feature.annotation.title'], { ns: 'appDebug' })}
        value={!!annotationReply?.enabled}
        onChange={(state) => handleSwitch(state)}
        onMouseEnter={() => setIsHovering(true)}
        onMouseLeave={() => setIsHovering(false)}
        disabled={disabled || (!annotationReply?.enabled && isAnnotationQuotaUnavailable)}
        loading={isDisabling}
      >
        <>
          {!annotationReply?.enabled && (
            <div className="line-clamp-2 min-h-8 system-xs-regular text-text-tertiary">
              {t(($) => $['feature.annotation.description'], { ns: 'appDebug' })}
            </div>
          )}
          {!!annotationReply?.enabled && (
            <>
              {(!isHovering || isDisabling) && (
                <div className="flex items-center gap-4 pt-0.5">
                  <div className="">
                    <div className="mb-0.5 system-2xs-medium-uppercase text-text-tertiary">
                      {t(($) => $['feature.annotation.scoreThreshold.title'], { ns: 'appDebug' })}
                    </div>
                    <div className="system-xs-regular text-text-secondary">
                      {annotationReply.score_threshold ?? '-'}
                    </div>
                  </div>
                  <div className="h-6.75 w-px rotate-12 bg-divider-subtle"></div>
                  <div className="">
                    <div className="mb-0.5 system-2xs-medium-uppercase text-text-tertiary">
                      {t(($) => $['modelProvider.embeddingModel.key'], { ns: 'modelProvider' })}
                    </div>
                    <div className="system-xs-regular text-text-secondary">
                      {annotationReply.embedding_model?.embedding_model_name}
                    </div>
                  </div>
                </div>
              )}
              {isHovering && !isDisabling && (
                <div className="flex items-center justify-between">
                  <Button
                    className="w-44.5"
                    onClick={() => setIsShowAnnotationConfigInit(true)}
                    disabled={disabled}
                  >
                    <RiEqualizer2Line className="size-4" />
                    {t(($) => $['operation.params'], { ns: 'common' })}
                  </Button>
                  <Link
                    href={`/app/${appId}/annotations`}
                    className={cn(buttonVariants(), 'w-44.5')}
                  >
                    <RiExternalLinkLine className="size-4" />
                    {t(($) => $['feature.annotation.cacheManagement'], { ns: 'appDebug' })}
                  </Link>
                </div>
              )}
            </>
          )}
        </>
      </FeatureCard>
      {isShowAnnotationConfigInit && (
        <ConfigParamModal
          appId={appId}
          isInit
          isShow={isShowAnnotationConfigInit}
          onHide={() => {
            setIsShowAnnotationConfigInit(false)
            // showChooseFeatureTrue()
          }}
          onSave={async (embeddingModel, score) => {
            await handleEnableAnnotation(embeddingModel, score)
            setIsShowAnnotationConfigInit(false)
          }}
          annotationConfig={annotationReply as any}
        />
      )}
      {isShowAnnotationFullModal && (
        <AnnotationFullModal
          show={isShowAnnotationFullModal}
          onHide={() => setIsShowAnnotationFullModal(false)}
        />
      )}
    </>
  )
}

export default AnnotationReply