Skip to contents

qlm_translate() makes translation a recorded stage of a coding workflow. It returns a qlm_translation: the translated texts as a named character vector, with a provenance record for each. Translate once, review and save the result, then reuse it across coding runs.

This article explains the workflow shared by translation providers. For Google Cloud setup, credential storage and a complete six-language UDHR example, see Google translation of a multilingual corpus. The output below uses two documents from the saved Google run described in that article. Site builds execute the local inspection, saving and conversion steps; API calls are shown for interactive use and are never evaluated during builds. The saved fixture contains actual translations, with project identifiers replaced by placeholders.

Choose a translation model

Supply a model explicitly. The same output structure is used by the native translation adapters and ordinary chat models:

Route Example model Default API-key source
DeepL deepl/quality_optimized DEEPL_API_KEY, then the optional deepl keyring entry
Qwen-MT dashscope/qwen-mt-plus DASHSCOPE_API_KEY
Google Translation LLM google-translate/translation-llm GOOGLE_TRANSLATE_API_KEY, then the optional google-translate keyring entry
Chat model openai/gpt-4o-mini The provider’s credentials, resolved through ellmer

An explicit api_key takes precedence over automatic lookup. Google also needs project_id or GOOGLE_CLOUD_PROJECT. Provider setup links and supported options are documented in ?qlm_translate; see the dedicated Google article for its setup walkthrough.

Translate and inspect

Load the saved French and Spanish translations from the article’s companion data file. The records retain both complete source documents and their English translations; the tables below show excerpts for readability.

translated <- readRDS("data/translated_udhr_google.rds")[c("fra", "spa")]
texts <- inputs(translated)
translation_model <- "google-translate/translation-llm"

To create this kind of result with your own inputs, run the following after setting up your chosen provider’s credentials:

translated <- qlm_translate(
  texts,
  model = translation_model,
  to = "en-GB",
  on_error = "continue"
)

The saved result has the same structure. The excerpts below only shorten the printed view; translated retains the complete texts and metadata.

translated
## <qlm_translation: 2 translations; model google-translate/translation-llm; target en-GB>
## fra: Preamble Whereas recognition of the inherent dignity and of the equal an...
## spa: Preamble Whereas recognition of the inherent dignity and of the equal an...
knitr::kable(data.frame(
  .id = names(translated),
  translation = substr(as.character(translated), 1, 160)
))
.id translation
fra fra Preamble

Whereas recognition of the inherent dignity and of the equal and inalienable rights of all members of the human family is the foundation of freedom, j | |spa |spa |Preamble

Whereas recognition of the inherent dignity and of the equal and inalienable rights of all members of the human family is the foundation of freedom, j |

Input names become the names of the translations, and the .id of any coding run. A failed translation is NA. Extract the source texts and inspect the translation record before using the output:

original <- inputs(translated)
knitr::kable(data.frame(
  .id = names(translated),
  source = substr(as.character(original), 1, 160)
))
.id source
fra Préambule

Considérant que la reconnaissance de la dignité inhérente à tous les membres de la famille humaine et de leurs droits égaux et inaliénables constitue | |spa |Preámbulo

Considerando que la libertad, la justicia y la paz en el mundo tienen por base el reconocimiento de la dignidad intrínseca y de los derechos iguales |

provenance <- attr(translated, "provenance")
knitr::kable(provenance[c(
  ".id", "status", "model", "reported_model", "detected_language"
)])
.id status model reported_model detected_language
fra ok google-translate/translation-llm translation-llm fr
spa ok google-translate/translation-llm translation-llm es

Provenance retains source texts and hashes, requested settings and instructions, model responses and attempts. Providers differ in whether they report detected source languages.

Set from whenever you know the source language. Language detection fails silently: given text in a language they do not support, the providers tested returned fluent but invented translations, recorded as successful. With from set, DeepL, Google and Qwen-MT refuse an unsupported language instead, and the document is NA with the reason; chat models do not refuse. from applies to the whole call, so for a corpus in several languages, translate each language separately and combine the results with c(). Here the corpus has a docvar language holding a tag such as "fr" for each document:

languages <- unique(quanteda::docvars(texts, "language"))
parts <- lapply(languages, function(lang) {
  qlm_translate(quanteda::corpus_subset(texts, language == lang),
                model = translation_model, to = "en-GB", from = lang)
})
translated <- do.call(c, parts)

If you leave from unset, compare the recorded detected_language with the languages you expect before using the translations.

context, instructions, protect, glossary and params let you request additional control where the selected provider supports it; an option a provider cannot honour raises an error. Settings that only one provider has, such as DeepL’s formality or Google’s project_id, are passed by name, as in qlm_translate(texts, "deepl/quality_optimized", formality = "more"). On the chat route, ellmer::params() settings are recorded as requested; ellmer may warn about unsupported settings. ?qlm_translate lists what each provider accepts.

Review, retry and save

Review fidelity, omissions, terminology and register with someone who knows the source language. Source-language detection and successful API responses do not establish translation quality. For coding research, assess downstream coding against original-language gold labels as well.

With on_error = "continue", a failed document is NA while successful translations remain available. The provenance gives the reason for each failure:

provenance[provenance$status != "ok", c(".id", "status", ".error")]
## [1] .id    status .error
## <0 rows> (or 0-length row.names)

The saved run has no failures. This retry code makes API calls only when needed and is shown without execution:

failed <- is.na(translated)
if (any(failed)) {
  retried <- qlm_translate(
    inputs(translated)[failed],
    model = translation_model,
    to = "en-GB",
    on_error = "continue"
  )
  translated[failed] <- retried
}

Save the complete object and reload it without contacting the provider:

saved_path <- file.path(tempdir(), "translated.rds")
saveRDS(translated, saved_path)
restored <- readRDS(saved_path)
isTRUE(all.equal(restored, translated))
## [1] TRUE

Use a permanent path for your own analysis; this article uses a temporary file.

Subsetting with [, renaming and c() keep each translation with its record. Assigning text, as in translated["fra"] <- "corrected text", records an edit and updates its hash. as.character(translated) drops the provenance. Saving the whole object retains the exact texts used, even if a model alias later produces different wording.

Code the translated texts

Pass the translations directly to qlm_code(), choosing a codebook suited to your research question. This illustrative sentiment-coding call is not run when building the article; no coding output is claimed for the saved translations:

coded <- qlm_code(translated, data_codebook_sentiment, model = "openai/gpt-4o-mini")
qlm_trail(coded, path = "translation_trail")

The coding run retains the translated inputs and compact translation history. Keep the saved translation object for bilingual review of the complete source texts. qlm_replicate(coded, ...) reuses the stored translated inputs and carries that history forward; it does not translate again.

Transcription can precede translation in the same workflow:

transcripts <- qlm_transcribe(audio_files)
translated <- qlm_translate(transcripts, model = translation_model,
  to = "en-GB")

Work with a corpus

A quanteda corpus can be supplied as input; inputs(translated) then returns the original corpus. Convert the translations with quanteda::corpus() when you need quanteda operations. The saved example’s input was a corpus, so its document variables come back:

source_corpus <- inputs(translated)
translated_corpus <- quanteda::corpus(translated)
knitr::kable(quanteda::docvars(translated_corpus))
Key Name ISO Direction
fra French fra ltr
spa Spanish spa ltr
identical(quanteda::docvars(translated_corpus),
          quanteda::docvars(source_corpus))
## [1] TRUE
identical(quanteda::docnames(translated_corpus), names(translated))
## [1] TRUE

The corpus contains translated texts with the same document names and original docvars. Original corpus metadata is restored, with outdated text summary caches cleared. Translation and coding records are stored in the quallmer user-metadata namespace. Quanteda remains optional for translation itself.

For a complete example of corpus selection, language detection, bilingual review, conversion and tokenization, follow the Google UDHR article. Text-similarity comparison is separate from corpus conversion and is not yet implemented.