getPrompts function

List<GptPrompt> getPrompts({
  1. required RawConfig rawConfig,
  2. required I18nLocale targetLocale,
  3. required GptConfig config,
  4. required String? namespace,
  5. required Map<String, dynamic> translations,
})

Returns the prompts that should be sent to GPT. There can be multiple prompts if the input is too long.

Implementation

List<GptPrompt> getPrompts({
  required RawConfig rawConfig,
  required I18nLocale targetLocale,
  required GptConfig config,
  required String? namespace,
  required Map<String, dynamic> translations,
}) {
  final systemPrompt = _getSystemPrompt(
    rawConfig: rawConfig,
    targetLocale: targetLocale,
    config: config,
    namespace: namespace,
  );
  final systemPromptLength = systemPrompt.length;

  final prompts = <GptPrompt>[];
  Map<String, dynamic> currentTranslationWindow = {};
  for (final entry in translations.entries) {
    if (currentTranslationWindow.isEmpty) {
      currentTranslationWindow[entry.key] = entry.value;
      continue;
    }

    final currentTranslation = jsonEncode(currentTranslationWindow);
    currentTranslationWindow[entry.key] = entry.value;
    final nextTranslation = jsonEncode(currentTranslationWindow);

    if (systemPromptLength + nextTranslation.length > config.maxInputLength) {
      prompts.add(GptPrompt(
        system: systemPrompt,
        user: currentTranslation,

        // currentTranslationWindow has been changed already
        userJSON: jsonDecode(currentTranslation),
      ));
      currentTranslationWindow = {
        entry.key: entry.value,
      };
    }
  }

  if (currentTranslationWindow.isNotEmpty) {
    // add the last prompt
    prompts.add(GptPrompt(
      system: systemPrompt,
      user: jsonEncode(currentTranslationWindow),
      userJSON: currentTranslationWindow,
    ));
  }

  return prompts;
}