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 { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ModelProvider, PreferredProviderTypeEnum } from '../declarations'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { getErrorMessage } from '@/utils/error-message'
import { ConfigurationMethodEnum } from '../declarations'
import { useUpdateModelList, useUpdateModelProviders } from '../hooks'

export function useChangeProviderPriority(
  provider: ModelProvider | ModelProviderSummaryResponse | undefined,
) {
  const { t } = useTranslation(['common'])
  const queryClient = useQueryClient()
  const updateModelList = useUpdateModelList()
  const updateModelProviders = useUpdateModelProviders()
  const providerName = provider?.provider ?? ''
  const modelProviderModelListQueryKey =
    consoleQuery.workspaces.current.modelProviders.byProvider.models.get.queryKey({
      input: {
        params: {
          provider: providerName,
        },
      },
    })
  const { mutate: changePriority, isPending: isChangingPriority } = useMutation(
    consoleQuery.workspaces.current.modelProviders.byProvider.preferredProviderType.post.mutationOptions(
      {
        context: { silent: true },
        onSuccess: () => {
          queryClient.invalidateQueries({
            queryKey: modelProviderModelListQueryKey,
            exact: true,
            refetchType: 'none',
          })
          updateModelProviders()
          provider?.configurate_methods.forEach((method) => {
            if (method === ConfigurationMethodEnum.predefinedModel)
              provider?.supported_model_types.forEach((modelType) => updateModelList(modelType))
          })
        },
        onError: (error) => {
          toast.error(
            getErrorMessage(error) ??
              t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
          )
        },
      },
    ),
  )
  const handleChangePriority = (key: PreferredProviderTypeEnum) => {
    if (!providerName) return
    changePriority({
      params: { provider: providerName },
      body: { preferred_provider_type: key },
    })
  }
  return { isChangingPriority, handleChangePriority }
}