use-model-form-schemas.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { useMemo } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import type {
  4. Credential,
  5. CustomModelCredential,
  6. ModelLoadBalancingConfig,
  7. ModelProvider,
  8. } from '../../declarations'
  9. import {
  10. genModelNameFormSchema,
  11. genModelTypeFormSchema,
  12. } from '../../utils'
  13. import { FormTypeEnum } from '@/app/components/base/form/types'
  14. export const useModelFormSchemas = (
  15. provider: ModelProvider,
  16. providerFormSchemaPredefined: boolean,
  17. credentials?: Record<string, any>,
  18. credential?: Credential,
  19. model?: CustomModelCredential,
  20. draftConfig?: ModelLoadBalancingConfig,
  21. ) => {
  22. const { t } = useTranslation()
  23. const {
  24. provider_credential_schema,
  25. supported_model_types,
  26. model_credential_schema,
  27. } = provider
  28. const formSchemas = useMemo(() => {
  29. const modelTypeSchema = genModelTypeFormSchema(supported_model_types)
  30. const modelNameSchema = genModelNameFormSchema(model_credential_schema?.model)
  31. if (!!model) {
  32. modelTypeSchema.disabled = true
  33. modelNameSchema.disabled = true
  34. }
  35. return providerFormSchemaPredefined
  36. ? provider_credential_schema.credential_form_schemas
  37. : [
  38. modelTypeSchema,
  39. modelNameSchema,
  40. ...(draftConfig?.enabled ? [] : model_credential_schema.credential_form_schemas),
  41. ]
  42. }, [
  43. providerFormSchemaPredefined,
  44. provider_credential_schema?.credential_form_schemas,
  45. supported_model_types,
  46. model_credential_schema?.credential_form_schemas,
  47. model_credential_schema?.model,
  48. draftConfig?.enabled,
  49. model,
  50. ])
  51. const formSchemasWithAuthorizationName = useMemo(() => {
  52. const authorizationNameSchema = {
  53. type: FormTypeEnum.textInput,
  54. variable: '__authorization_name__',
  55. label: t('plugin.auth.authorizationName'),
  56. required: true,
  57. }
  58. return [
  59. authorizationNameSchema,
  60. ...formSchemas,
  61. ]
  62. }, [formSchemas, t])
  63. const formValues = useMemo(() => {
  64. let result = {}
  65. if (credential) {
  66. result = { ...result, __authorization_name__: credential?.credential_name }
  67. if (credentials)
  68. result = { ...result, ...credentials }
  69. }
  70. if (model)
  71. result = { ...result, __model_name: model?.model, __model_type: model?.model_type }
  72. return result
  73. }, [credentials, credential, model])
  74. return {
  75. formSchemas: formSchemasWithAuthorizationName,
  76. formValues,
  77. }
  78. }