Translate Text Call
Translate Text
Translate text calls are calls for translating text from one language to another. DeepL is the one provider that implements this call natively.
AI translate module, when enabled, allows using any provider that supports chat calls, for translation.
Example normalized text translation call
Using default provider:
$providerConfig = $this->aiProviderManager->getDefaultProviderForOperationType('translate_text');
$provider = $this->aiProviderManager->createInstance($providerConfig['provider_id'], $providerConfig);
$translation = $provider->translateText(
new TranslateTextInput($input_text, $langFrom?->getId(), $langTo->getId()),
$providerConfig['model_id']
);
Using non-default provider (for this example to work, you need to install Deepl provider module)
For the following example to work, you need to install DeepL module.
$translator = \Drupal::service('ai.provider')->createInstance('deepl');
// Note that for DeepL, plain 'en' is not supported, you need to use
// 'en-gb' or 'en-us'.
$input = new TranslateTextInput($text, 'fi', 'en-gb');
/** @var \Drupal\ai\OperationType\TranslateText\TranslateTextOutput $translation */
$translation = $translator->translateText($input, 'default', []);
// Will output 'Hello world'.
return $translation->getNormalized();
Text Translation Interfaces & Models
The following files defines the methods available when doing a text translation call as well as the input and output.
Text Translation Explorer
If you install the AI API Explorer, you can go configuration > AI > AI API Explorer > Text Translation Explorer
under /admin/config/ai/explorers/ai-translate-text
to test out different calls and see the code that you need for it.