Settings Management in Payload CMS: Configuring AI Translation Features

14 de diciembre de 2024 por Moritz Thomas

Managing application settings in a content management system requires balancing flexibility, security, and user experience. This article explores how we implemented a Settings global in Payload CMS to manage AI translation features, providing a centralized configuration system for our Translation Management System.

Core Implementation

The Settings global in Payload CMS serves as a central configuration hub, particularly for AI-powered translation features. Here's how we implemented it:

const PayloadSettings: GlobalConfig = {
  slug: "payload-settings",
  label: "Payload Settings",
  access: {
    read: isUser,
    update: rbacHas(ROLE_ADMIN),
  },
  fields: [
    {
      name: "chatgptModel",
      label: "ChatGPT model used for translations",
      type: "text",
      admin: {
        components: {
          Field: (props) => <SelectComponent loader={loader} {...props} />,
        },
      },
    },
    {
      name: "askChatgptPrompt",
      label: "Ask ChatGPT Prompt",
      type: "textarea",
      admin: {
        description: () =>
          `Available placeholder: {locale}, {minVariations}, {maxVariations}, {context}, {term}`,
      },
    },
    {
      name: "bulkTranslationPrompt",
      label: "ChatGPT Prompt for bulk translations",
      type: "textarea",
    },
    {
      name: "addTranslationsAsDrafts",
      label: "Add translations as drafts",
      type: "checkbox",
    },
  ],
};

This implementation provides several key features:

  • Model selection for ChatGPT translations

  • Configurable prompts for different translation scenarios

  • Draft mode toggle for translation management

  • Role-based access control

Dynamic Model Selection

A crucial feature is the ability to dynamically select ChatGPT models. This is implemented through a custom endpoint that leverages the OpenAI SDK:

export default async function chatGptModelsRoute(req: PayloadRequest, res: Response) {
  if (!req.user) {
    return res.send(`Not authenticated`);
  }

  const result = await openai.models.list();

  res.status(200).send(
    result.data
      .sort((a, b) => b.created - a.created)
      .map((model) => model.id)
  );
}

This endpoint:

  1. Verifies user authentication

  2. Retrieves available models from OpenAI

  3. Returns a sorted list of model IDs

Custom Select Component

To handle the asynchronous nature of model loading, we implemented a custom select component:

export const SelectComponent: FC<Props & { loader: () => Promise<OptionObject[]> }> = ({
  path,
  label,
  required,
  loader,
}) => {
  const { value, setValue } = useField<string>({ path });
  const [options, setOptions] = useState<OptionObject[]>([]);

  useEffect(() => {
    loader().then((opts) => {
      if (!value) {
        setValue(opts[0].value);
      }
      setOptions(opts);
    });
  }, [loader]);

  return (
    <div className="custom-select">
      <Label htmlFor={path} label={label} required={required} />
      <SelectInput
        path={path}
        name={path}
        options={options}
        value={value}
        onChange={(e) => setValue(e.value)}
      />
    </div>
  );
};

This component provides:

  • Asynchronous option loading

  • Automatic default value selection

  • Integration with Payload's form system

Using Settings in the Application

Settings can be accessed throughout the application using Payload's global API:

const settings = await payload.findGlobal({
  slug: "payload-settings",
}) as PayloadSetting;

const model = settings.chatgptModel ?? "gpt-4-turbo-preview";
let content = settings.askChatgptPrompt;

This pattern allows for:

  • Centralized configuration management

  • Default values for essential settings

  • Type-safe access to configuration values

Security Considerations

The current implementation includes basic security through role-based access control:

  • Read access is limited to authenticated users

  • Update access is restricted to administrators only

Future Enhancements

Several areas have been identified for future improvement:

  1. API Key Management

    • Secure storage for different types of API keys

    • Variable visibility based on key sensitivity

    • Potential proxy implementation for client-side APIs

  2. Enhanced Error Handling

    • Improved network error handling

    • Loading state indicators

    • Fallback options for unavailable services

  3. Access Control Refinement

    • Granular permissions for different settings sections

    • Role-specific access patterns

    • Audit logging for configuration changes

  4. UI/UX Improvements

    • Better loading states for async components

    • Validation for prompt templates

    • Enhanced error feedback

  5. Performance Optimization

    • Caching for model lists

    • Batched updates for related settings

    • Optimistic UI updates

Conclusion

The Settings global provides a robust foundation for managing translation-related configuration in our system. While there are areas for future enhancement, the current implementation successfully manages AI model selection, prompt configuration, and basic security requirements.

The system's modular design allows for gradual enhancement without disrupting existing functionality. As the translation management system evolves, the Settings global can be extended to handle additional configuration needs while maintaining its core simplicity and security model.

Comentarios

Todavía no hay comentarios, sé el primero:

© 2024 por Moritz Thomas