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.

2.3 KB
Raw Blame
import type { Credential, ModelProvider } from '../../declarations'
import { useMutation } from '@tanstack/react-query'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { getErrorMessage } from '@/utils/error-message'
import { useUpdateModelList, useUpdateModelProviders } from '../../hooks'

export function useActivateCredential(provider: ModelProvider) {
  const { t } = useTranslation(['common'])
  const updateModelProviders = useUpdateModelProviders()
  const updateModelList = useUpdateModelList()
  const { mutate, isPending } = useMutation(
    consoleQuery.workspaces.current.modelProviders.byProvider.credentials.switch.post.mutationOptions(
      { context: { silent: true } },
    ),
  )
  const [optimisticId, setOptimisticId] = useState<string>()
  const currentId = provider.custom_configuration.current_credential_id
  const selectedCredentialId = optimisticId ?? currentId
  const selectedIdRef = useRef(selectedCredentialId)
  const supportedModelTypesRef = useRef(provider.supported_model_types)

  useEffect(() => {
    selectedIdRef.current = selectedCredentialId
    supportedModelTypesRef.current = provider.supported_model_types
  }, [selectedCredentialId, provider.supported_model_types])
  const activate = useCallback(
    (credential: Credential) => {
      if (credential.credential_id === selectedIdRef.current) return
      setOptimisticId(credential.credential_id)
      mutate(
        {
          params: { provider: provider.provider },
          body: { credential_id: credential.credential_id },
        },
        {
          onSuccess: () => {
            updateModelProviders()
            supportedModelTypesRef.current.forEach((type) => updateModelList(type))
          },
          onError: (error) => {
            setOptimisticId(undefined)
            toast.error(
              getErrorMessage(error) ??
                t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
            )
          },
        },
      )
    },
    [mutate, provider.provider, t, updateModelProviders, updateModelList],
  )
  return {
    selectedCredentialId,
    isActivating: isPending,
    activate,
  }
}