Skip to content

The open alternative to Salesforce, designed for AI.

19.3 KB
Raw Blame
import { AI_ADMIN_PATH } from '@/settings/admin-panel/ai/constants/AiAdminPath';
import { AI_PROVIDER_SOURCE } from '@/settings/admin-panel/ai/constants/AiProviderSource';
import { getDataResidencyOptions } from '@/settings/admin-panel/ai/constants/DataResidencyOptions';
import { ADD_AI_PROVIDER } from '@/settings/admin-panel/ai/graphql/mutations/addAiProvider';
import { GET_ADMIN_AI_MODELS } from '@/settings/admin-panel/ai/graphql/queries/getAdminAiModels';
import { GET_AI_PROVIDERS } from '@/settings/admin-panel/ai/graphql/queries/getAiProviders';
import { GET_MODELS_DEV_PROVIDERS } from '@/settings/admin-panel/ai/graphql/queries/getModelsDevProviders';
import { useCustomAiProviderAccess } from '@/settings/admin-panel/ai/hooks/useCustomAiProviderAccess';
import { type GetAiProvidersResult } from '@/settings/admin-panel/ai/types/GetAiProvidersResult';
import { type RawAiProviderConfig } from '@/settings/admin-panel/ai/types/RawAiProviderConfig';
import { getProviderIcon } from '@/ai/utils/getProviderIcon';
import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';
import { Select } from '@/ui/input/components/Select';
import { TextInput } from '@/ui/input/components/TextInput';
import { useMutation, useQuery } from '@apollo/client/react';
import { Trans, useLingui } from '@lingui/react/macro';
import { plural } from '@lingui/core/macro';
import { isNonEmptyString } from '@sniptt/guards';
import { useMemo, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Link, useNavigate } from 'react-router-dom';
import { slugify } from 'transliteration';
import { type AiSdkPackage, isDataResidency } from 'twenty-shared/ai';
import { SettingsPath } from 'twenty-shared/types';
import { capitalize, getSettingsPath, isDefined } from 'twenty-shared/utils';
import { InlineBanner, useToast } from 'twenty-ui/components/feedback';
import { Section } from 'twenty-ui/components/layout';
import { IconPlus } from 'twenty-ui/icon';
import { OrganizationAdornment } from '@/settings/enterprise/components/OrganizationAdornment';
import { getErrorMessageFromApolloError } from '~/utils/get-error-message-from-apollo-error.util';
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';

type ModelsDevProvider = { id: string; modelCount: number; npm: AiSdkPackage };

type FormValues = {
  npm: AiSdkPackage;
  label: string;
  apiKey: string;
  baseUrl: string;
  region: string;
  accessKeyId: string;
  secretAccessKey: string;
  dataResidency: string;
};

export const SettingsAdminNewAiProvider = () => {
  const apolloAdminClient = useApolloAdminClient();
  const navigate = useNavigate();
  const { t } = useLingui();
  const { enqueueToast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedModelsDevId, setSelectedModelsDevId] = useState<string | null>(
    null,
  );
  const [isCustomMode, setIsCustomMode] = useState(false);
  const {
    hasAccess: hasCustomAiProviderAccess,
    gateDescription: customAiProviderGateDescription,
    tooltipContent: customAiProviderTooltipContent,
  } = useCustomAiProviderAccess();

  const [addAiProvider] = useMutation(ADD_AI_PROVIDER, {
    client: apolloAdminClient,
  });

  const { data: modelsDevData } = useQuery<{
    getModelsDevProviders: ModelsDevProvider[];
  }>(GET_MODELS_DEV_PROVIDERS, { client: apolloAdminClient });

  const { data: providersData } = useQuery<GetAiProvidersResult>(
    GET_AI_PROVIDERS,
    { client: apolloAdminClient },
  );

  const modelsDevProviders = useMemo(
    () => modelsDevData?.getModelsDevProviders ?? [],
    [modelsDevData?.getModelsDevProviders],
  );

  const modelsDevByIdMap = useMemo(
    () =>
      new Map(modelsDevProviders.map((provider) => [provider.id, provider])),
    [modelsDevProviders],
  );

  const providerOptions = modelsDevProviders.map((provider) => ({
    value: provider.id,
    label: `${capitalize(provider.id)} (${plural(provider.modelCount, {
      one: '# model',
      other: '# models',
    })})`,
    Icon: getProviderIcon(provider.id),
  }));

  const form = useForm<FormValues>({
    mode: 'onSubmit',
    defaultValues: {
      npm: '@ai-sdk/openai-compatible',
      label: '',
      apiKey: '',
      baseUrl: '',
      region: '',
      accessKeyId: '',
      secretAccessKey: '',
      dataResidency: '',
    },
  });

  const hasSelected = selectedModelsDevId !== null || isCustomMode;
  const npmPackage = form.watch('npm');
  const isBedrock = npmPackage === '@ai-sdk/amazon-bedrock';
  const isOpenAiCompatible = npmPackage === '@ai-sdk/openai-compatible';
  const needsApiKey = !isBedrock;
  const isModelsDevWithoutNativeSdk =
    selectedModelsDevId !== null && isOpenAiCompatible;

  const providerName = slugify(form.watch('label'), { separator: '-' });
  const builtInProviderPath =
    providersData?.getAiProviders[providerName]?.source ===
    AI_PROVIDER_SOURCE.CATALOG
      ? getSettingsPath(SettingsPath.AdminPanelAiProviderDetail, {
          providerName,
        })
      : undefined;

  const handleProviderSelected = (providerId: string) => {
    setSelectedModelsDevId(providerId);
    setIsCustomMode(false);

    const suggestion = modelsDevByIdMap.get(providerId);

    form.setValue('npm', suggestion?.npm ?? '@ai-sdk/openai-compatible');

    form.setValue('label', capitalize(providerId));
  };

  const handleCustomMode = () => {
    setSelectedModelsDevId(null);
    setIsCustomMode(true);
    form.setValue('npm', '@ai-sdk/openai-compatible');
    form.setValue('label', '');
  };

  const handleSave = async () => {
    const values = form.getValues();

    if (!values.label.trim()) {
      form.setError('label', {
        type: 'manual',
        message: t`Label is required`,
      });

      return;
    }

    if (!providerName) {
      form.setError('label', {
        type: 'manual',
        message: t`Label must contain at least one alphanumeric character`,
      });

      return;
    }

    const config: Partial<RawAiProviderConfig> = {
      npm: values.npm,
      label: values.label.trim(),
      ...(selectedModelsDevId && { name: selectedModelsDevId }),
      ...(needsApiKey &&
        values.apiKey.trim() && {
          apiKey: values.apiKey.trim(),
        }),
      ...(isOpenAiCompatible &&
        values.baseUrl.trim() && {
          baseUrl: values.baseUrl.trim(),
        }),
      ...(isDataResidency(values.dataResidency) && {
        dataResidency: values.dataResidency,
      }),
    };

    if (isBedrock) {
      if (!values.region.trim()) {
        form.setError('region', {
          type: 'manual',
          message: t`Region is required for Bedrock`,
        });

        return;
      }
      config.region = values.region.trim();

      const apiKey = values.apiKey.trim();
      const accessKeyId = values.accessKeyId.trim();
      const secretAccessKey = values.secretAccessKey.trim();

      if (
        isNonEmptyString(apiKey) &&
        (isNonEmptyString(accessKeyId) || isNonEmptyString(secretAccessKey))
      ) {
        form.setError('apiKey', {
          type: 'manual',
          message: t`Use either an API key or an access key pair, not both`,
        });

        return;
      }

      // Role auth ignores both fields, so half a key pair would run under an identity nobody chose
      if (isNonEmptyString(accessKeyId) !== isNonEmptyString(secretAccessKey)) {
        form.setError(
          isNonEmptyString(accessKeyId) ? 'secretAccessKey' : 'accessKeyId',
          {
            type: 'manual',
            message: t`Enter both keys, or neither to use the instance IAM role`,
          },
        );

        return;
      }

      if (isNonEmptyString(apiKey)) {
        config.apiKey = apiKey;
      } else if (isNonEmptyString(accessKeyId)) {
        config.accessKeyId = accessKeyId;
        config.secretAccessKey = secretAccessKey;
      } else {
        config.authType = 'role';
      }
    }

    if (!isBedrock && !isOpenAiCompatible && !values.apiKey.trim()) {
      form.setError('apiKey', {
        type: 'manual',
        message: t`API key is required`,
      });

      return;
    }

    if (isOpenAiCompatible && !values.baseUrl.trim()) {
      form.setError('baseUrl', {
        type: 'manual',
        message: t`Base URL is required`,
      });

      return;
    }

    setIsSubmitting(true);

    try {
      await addAiProvider({
        variables: {
          providerName,
          providerConfig: config,
        },
        refetchQueries: [
          { query: GET_AI_PROVIDERS },
          { query: GET_ADMIN_AI_MODELS },
        ],
      });

      enqueueToast({
        status: 'success',
        children: t`Provider "${values.label.trim()}" added`,
      });
      navigate(AI_ADMIN_PATH);
    } catch (error) {
      if (isGraphqlErrorOfType(error, 'BUILT_IN_AI_PROVIDER_NAME')) {
        form.setError('label', {
          type: 'manual',
          message: getErrorMessageFromApolloError(error),
        });

        return;
      }

      enqueueToast({ status: 'error', children: t`Failed to add provider` });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={form.handleSubmit(handleSave)}>
      <SettingsPageLayout
        title={t`New AI Provider`}
        links={[
          {
            children: <Trans>Admin Panel</Trans>,
            href: getSettingsPath(SettingsPath.AdminPanel),
          },
          { children: <Trans>New AI Provider</Trans> },
        ]}
        actionButton={
          <SaveAndCancelButtons
            onCancel={() => navigate(AI_ADMIN_PATH)}
            isSaveDisabled={
              isSubmitting || !hasSelected || !hasCustomAiProviderAccess
            }
            onSave={handleSave}
          />
        }
      >
        <SettingsPageContainer>
          {!hasCustomAiProviderAccess && (
            <InlineBanner
              layout="compact"
              status="error"
              action={
                <InlineBanner.Action
                  href={getSettingsPath(SettingsPath.AdminPanelOrganization)}
                  nativeButton={false}
                  role="link"
                  render={
                    <Link
                      to={getSettingsPath(SettingsPath.AdminPanelOrganization)}
                    />
                  }
                >{t`Activate`}</InlineBanner.Action>
              }
            >
              {customAiProviderGateDescription}
            </InlineBanner>
          )}

          <Section.Root>
            <Section.Header
              title={t`Provider`}
              description={t`Select a known provider or create a custom one`}
              actions={
                <OrganizationAdornment
                  tooltipContent={customAiProviderTooltipContent}
                />
              }
            />
            <Select
              dropdownId="ai-provider-models-dev-select"
              value={selectedModelsDevId ?? undefined}
              onChange={handleProviderSelected}
              options={providerOptions}
              withSearchInput
              fullWidth
              callToActionButton={{
                text: t`Custom provider`,
                onClick: handleCustomMode,
                Icon: IconPlus,
              }}
            />
          </Section.Root>

          {isDefined(builtInProviderPath) && (
            <InlineBanner
              layout="compact"
              status="info"
              action={
                <InlineBanner.Action
                  href={builtInProviderPath}
                  nativeButton={false}
                  role="link"
                  render={<Link to={builtInProviderPath} />}
                >{t`Open`}</InlineBanner.Action>
              }
            >{t`This provider is built in. Set its API key from its page.`}</InlineBanner>
          )}

          {isModelsDevWithoutNativeSdk && (
            <InlineBanner
              layout="compact"
              status="info"
            >{t`This provider doesn't have a native SDK yet — it will use OpenAI-compatible mode. Need native support? Reach out to us.`}</InlineBanner>
          )}

          {hasSelected && (
            <>
              <Section.Root>
                <Section.Header
                  title={t`Label`}
                  description={t`A display name for this provider`}
                />
                <Controller
                  name="label"
                  control={form.control}
                  render={({
                    field: { onChange, value },
                    fieldState: { error },
                  }) => (
                    <TextInput
                      value={value}
                      onChange={onChange}
                      placeholder={
                        isCustomMode
                          ? t`e.g. My OpenAI Proxy`
                          : t`e.g. OpenAI EU`
                      }
                      fullWidth
                      error={error?.message}
                    />
                  )}
                />
              </Section.Root>

              {needsApiKey && (
                <Section.Root>
                  <Section.Header
                    title={t`API Key`}
                    description={t`Your provider API key for authentication`}
                  />
                  <Controller
                    name="apiKey"
                    control={form.control}
                    render={({
                      field: { onChange, value },
                      fieldState: { error },
                    }) => (
                      <TextInput
                        value={value}
                        onChange={onChange}
                        placeholder={t`sk-...`}
                        fullWidth
                        type="password"
                        error={error?.message}
                      />
                    )}
                  />
                </Section.Root>
              )}

              {isOpenAiCompatible && (
                <Section.Root>
                  <Section.Header
                    title={t`Base URL`}
                    description={t`The API endpoint for your OpenAI-compatible provider`}
                  />
                  <Controller
                    name="baseUrl"
                    control={form.control}
                    render={({
                      field: { onChange, value },
                      fieldState: { error },
                    }) => (
                      <TextInput
                        value={value}
                        onChange={onChange}
                        placeholder={t`https://api.example.com/v1`}
                        fullWidth
                        error={error?.message}
                      />
                    )}
                  />
                </Section.Root>
              )}

              <Section.Root>
                <Section.Header
                  title={t`Data Residency`}
                  description={t`Region where inference data is processed (optional)`}
                />
                <Controller
                  name="dataResidency"
                  control={form.control}
                  render={({ field: { onChange, value } }) => (
                    <Select
                      dropdownId="ai-provider-data-residency-select"
                      value={value}
                      onChange={onChange}
                      options={[
                        { value: '', label: t`None` },
                        ...getDataResidencyOptions(t),
                      ]}
                      fullWidth
                    />
                  )}
                />
              </Section.Root>

              {isBedrock && (
                <>
                  <Section.Root>
                    <Section.Header
                      title={t`Region`}
                      description={t`The AWS region for Bedrock`}
                    />
                    <Controller
                      name="region"
                      control={form.control}
                      render={({
                        field: { onChange, value },
                        fieldState: { error },
                      }) => (
                        <TextInput
                          value={value}
                          onChange={onChange}
                          placeholder={t`us-east-1`}
                          fullWidth
                          error={error?.message}
                        />
                      )}
                    />
                  </Section.Root>

                  <Section.Root>
                    <Section.Header
                      title={t`API Key`}
                      description={t`Optional — a Bedrock API key, used instead of an access key pair or the IAM role`}
                    />
                    <Controller
                      name="apiKey"
                      control={form.control}
                      render={({
                        field: { onChange, value },
                        fieldState: { error },
                      }) => (
                        <TextInput
                          value={value}
                          onChange={onChange}
                          fullWidth
                          type="password"
                          error={error?.message}
                        />
                      )}
                    />
                  </Section.Root>

                  <Section.Root>
                    <Section.Header
                      title={t`Access Key ID`}
                      description={t`Optional — uses IAM role if empty`}
                    />
                    <Controller
                      name="accessKeyId"
                      control={form.control}
                      render={({
                        field: { onChange, value },
                        fieldState: { error },
                      }) => (
                        <TextInput
                          value={value}
                          onChange={onChange}
                          placeholder={t`AKIA...`}
                          fullWidth
                          error={error?.message}
                        />
                      )}
                    />
                  </Section.Root>

                  <Section.Root>
                    <Section.Header
                      title={t`Secret Access Key`}
                      description={t`Optional — uses IAM role if empty`}
                    />
                    <Controller
                      name="secretAccessKey"
                      control={form.control}
                      render={({
                        field: { onChange, value },
                        fieldState: { error },
                      }) => (
                        <TextInput
                          value={value}
                          onChange={onChange}
                          fullWidth
                          type="password"
                          error={error?.message}
                        />
                      )}
                    />
                  </Section.Root>
                </>
              )}
            </>
          )}
        </SettingsPageContainer>
      </SettingsPageLayout>
    </form>
  );
};