laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
use std::sync::Arc;

use async_trait::async_trait;
use indexmap::IndexMap;
use laravel::http::client;
use laravel::time::ToSpan;
use serde::Serialize;
use serde_json::Value;

use super::{backoff_seconds, decode_error, json_body, real_sleeper, refusal, retryable};
use crate::json;
use crate::limits::{Json, ModelLimits};
use crate::support::config;
use crate::translator::{
    Sleeper, Texts, TranslateError, Translated, Translations, Translator, log_to_console, translations_in, trim,
};

const ENDPOINT: &str = "https://api.openai.com/v1/chat/completions";

/// Tokens left for a reasoning model to think in, on top of the answer: OpenAI advises reserving
/// 25,000 for reasoning and output at first.
const REASONING_RESERVE: u64 = 25_000;

/// Structured Outputs takes up to 5,000 properties and 120,000 characters of names in a schema; a
/// larger one is asked for as plain JSON instead.
const MAX_SCHEMA_PROPERTIES: usize = 5000;

const MAX_SCHEMA_NAME_CHARS: usize = 120_000;

/// Translates with OpenAI's chat models, `gpt-5.4-nano` unless `TextsConfig::openai.model` says
/// otherwise.
///
/// It asks each model only for what it accepts ([`ModelLimits`]), sizes its batches by the answer
/// they produce, holds the answer to a JSON schema where the model supports it, and splits a batch
/// whose answer was cut short at the output limit instead of sending it again.
#[derive(Clone)]
pub struct OpenAiTranslator {
    sleeper: Arc<dyn Sleeper>,
}

impl OpenAiTranslator {
    /// A translator that reads its settings from the configuration on every request.
    pub fn new() -> Self {
        Self {
            sleeper: real_sleeper(),
        }
    }

    /// Wait through another [`Sleeper`] between attempts, such as one that records the waits.
    #[must_use]
    pub fn with_sleeper(mut self, sleeper: Arc<dyn Sleeper>) -> Self {
        self.sleeper = sleeper;

        self
    }

    fn model(&self) -> String {
        config().openai.model
    }

    fn limits(&self) -> ModelLimits {
        ModelLimits::for_model("openai", &self.model())
    }

    fn requested_output_tokens(&self) -> u64 {
        config().openai.max_output_tokens.max(256)
    }

    /// The `max_completion_tokens` sent: the answer, plus room to think for a reasoning model,
    /// whose reasoning tokens count against the same allowance.
    fn completion_tokens(&self) -> u64 {
        let limits = self.limits();
        let answer = self.requested_output_tokens().min(limits.max_output_tokens);

        limits
            .max_output_tokens
            .min(answer + if limits.reasoning { REASONING_RESERVE } else { 0 })
    }

    /// One request with the parameters the model accepts, asked again when the JSON does not decode
    /// or the API is busy, never when the answer was cut short.
    async fn ask(&self, system: &str, user: &str, schema: &Schema) -> Result<Option<Value>, TranslateError> {
        let limits = self.limits();
        let settings = config().openai;
        let attempts = settings.retries.max(1);

        // A published config holds no effort, which falls back to the model's own.
        let effort = limits.reasoning_effort.as_ref().map(|own| {
            settings
                .reasoning_effort
                .clone()
                .filter(|effort| !effort.is_empty())
                .unwrap_or_else(|| own.clone())
        });

        let response_format = if limits.json == Json::Schema && schema.fits() {
            Some(ResponseFormat::Schema {
                kind: "json_schema",
                json_schema: JsonSchema {
                    name: "translations",
                    strict: true,
                    schema,
                },
            })
        } else if limits.json != Json::None {
            Some(ResponseFormat::Object { kind: "json_object" })
        } else {
            None
        };

        let body = Body {
            model: self.model(),
            messages: [
                Message {
                    role: "system",
                    content: system,
                },
                Message {
                    role: "user",
                    content: user,
                },
            ],
            max_completion_tokens: self.completion_tokens(),
            temperature: limits.temperature.then_some(0),
            reasoning_effort: effort,
            response_format,
        };

        let token = settings.api_key.clone().unwrap_or_default();

        for attempt in 1..=attempts {
            let response = client::post(ENDPOINT)
                .token(&token)
                .timeout((settings.timeout as i64).seconds())
                .json(&body)
                .await
                .map_err(|error| TranslateError::failed(error.to_string()))?;

            if !response.successful() {
                log_to_console(format!(
                    "⚠️  OpenAI answered {}: {}",
                    response.status().as_u16(),
                    refusal(&response)
                ));

                if !retryable(&response) || attempt == attempts {
                    return Ok(None);
                }

                self.sleeper.sleep(backoff_seconds(attempt)).await;

                continue;
            }

            let answer = json_body(&response);

            if answer
                .as_ref()
                .and_then(|answer| answer.pointer("/choices/0/finish_reason"))
                .and_then(Value::as_str)
                == Some("length")
            {
                return Err(TranslateError::Truncated(
                    "OpenAI stopped at the output limit.".to_owned(),
                ));
            }

            let content = answer
                .as_ref()
                .and_then(|answer| answer.pointer("/choices/0/message/content"))
                .and_then(Value::as_str)
                .unwrap_or_default();

            let content = trim(content);

            match serde_json::from_str::<Value>(content) {
                Ok(decoded @ (Value::Object(_) | Value::Array(_))) => return Ok(Some(decoded)),
                _ => {
                    if attempt < attempts {
                        log_to_console(format!(
                            "⚠️  Attempt {attempt}: Failed to decode JSON (error: {}), retrying...",
                            decode_error(content)
                        ));
                    }
                }
            }
        }

        Ok(None)
    }
}

impl Default for OpenAiTranslator {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Translator for OpenAiTranslator {
    async fn translate(&self, text: &str, from: &str, to: &[String]) -> Result<Translated, TranslateError> {
        let languages = to.join(", ");

        let answer = self
            .ask(
                &format!(
                    "You are a helpful assistant that translates from {from} into multiple languages: {languages}. Reply ONLY with a valid JSON object (no markdown, no code blocks, no explanations), where each property is the language code and the value is the translated text. Preserve placeholders like :name, :count, or any text wrapped in colons (:) exactly as they are. IMPORTANT: Do NOT create nested objects. Return a flat JSON object.{}",
                    self.context_instruction()
                ),
                text,
                &Schema::languages(to),
            )
            .await?;

        let Some(answer) = answer else {
            return Err(TranslateError::failed("Failed to decode translation response."));
        };

        let wrapped = Value::Object([("text".to_owned(), answer)].into_iter().collect());

        Ok(translations_in(&wrapped, &["text".to_owned()], to)
            .swap_remove("text")
            .unwrap_or_default())
    }

    async fn translate_many(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        match self.translate_batch(texts, from, to).await {
            Err(TranslateError::Truncated(_)) => {
                log_to_console(
                    "❌ The answer did not fit the model's output limit. Skipping this batch and continuing...",
                );

                Ok(Translations::new())
            }
            other => other,
        }
    }

    async fn translate_batch(&self, texts: &Texts, from: &str, to: &[String]) -> Result<Translations, TranslateError> {
        let languages = to.join(", ");
        let keys: Vec<String> = texts.keys().cloned().collect();

        log_to_console(format!(
            "➡️ Sending {} texts to OpenAI for translation into [{languages}] using model [{}]...",
            texts.len(),
            self.model()
        ));

        let answer = self
            .ask(
                &format!(
                    "You are a helpful assistant that translates JSON key-value pairs from {from} into multiple languages: {languages}. Reply ONLY with a valid JSON object (no markdown, no code blocks, no explanations) where each key from the input maps to an object of translations per language. Preserve any placeholder like :name, :count, or any text wrapped in colons (:). CRITICAL: Keep ALL keys EXACTLY as they appear in the input, including dots and numbers (e.g., 'properties.parking_type', 'items.0.name'). Do NOT interpret dots as nested objects. Do NOT create any nested structure. Return keys as-is. You MAY use the keys as context to improve the translation, since they indicate where the text is used (for example nav., errors. or buttons.).{}",
                    self.context_instruction()
                ),
                &texts_as_json(texts),
                &Schema::keys(&keys, to),
            )
            .await?;

        let Some(answer) = answer else {
            log_to_console(format!(
                "❌ No usable answer for keys: {}. Skipping this batch and continuing...",
                keys.join(", ")
            ));

            return Ok(Translations::new());
        };

        let translations = translations_in(&answer, &keys, to);

        log_to_console(format!(
            "✅ Received translations for: {}",
            translations.keys().cloned().collect::<Vec<_>>().join(", ")
        ));

        Ok(translations)
    }

    /// The answer asked for, capped by the model's own limit.
    fn output_token_limit(&self) -> Option<usize> {
        Some(self.requested_output_tokens().min(self.limits().max_output_tokens) as usize)
    }
}

/// `json_encode($texts, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)`.
pub(crate) fn texts_as_json(texts: &Texts) -> String {
    if texts.is_empty() {
        return "[]".to_owned();
    }

    json::pretty(texts, false)
}

#[derive(Serialize)]
struct Message<'a> {
    role: &'static str,
    content: &'a str,
}

#[derive(Serialize)]
struct Body<'a> {
    model: String,
    messages: [Message<'a>; 2],
    max_completion_tokens: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    reasoning_effort: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    response_format: Option<ResponseFormat<'a>>,
}

#[derive(Serialize)]
#[serde(untagged)]
enum ResponseFormat<'a> {
    Schema {
        #[serde(rename = "type")]
        kind: &'static str,
        json_schema: JsonSchema<'a>,
    },
    Object {
        #[serde(rename = "type")]
        kind: &'static str,
    },
}

#[derive(Serialize)]
struct JsonSchema<'a> {
    name: &'static str,
    strict: bool,
    schema: &'a Schema,
}

/// The Structured Outputs schema of the answer: every key, every language, nothing else. With no
/// keys, the flat `{language: translation}` of a single text.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct Schema {
    #[serde(rename = "type")]
    kind: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    properties: Option<IndexMap<String, Schema>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    required: Option<Vec<String>>,
    #[serde(rename = "additionalProperties", skip_serializing_if = "Option::is_none")]
    additional_properties: Option<bool>,
}

impl Schema {
    fn string() -> Self {
        Self {
            kind: "string",
            properties: None,
            required: None,
            additional_properties: None,
        }
    }

    fn object(properties: IndexMap<String, Schema>, required: Vec<String>) -> Self {
        Self {
            kind: "object",
            properties: Some(properties),
            required: Some(required),
            additional_properties: Some(false),
        }
    }

    pub(crate) fn languages(languages: &[String]) -> Self {
        Self::object(
            languages
                .iter()
                .map(|language| (language.clone(), Self::string()))
                .collect(),
            languages.to_vec(),
        )
    }

    pub(crate) fn keys(keys: &[String], languages: &[String]) -> Self {
        Self::object(
            keys.iter()
                .map(|key| (key.clone(), Self::languages(languages)))
                .collect(),
            keys.to_vec(),
        )
    }

    /// Whether the schema is within Structured Outputs' limits on properties and name length.
    pub(crate) fn fits(&self) -> bool {
        let mut properties = 0;
        let mut chars = 0;
        let mut pending = vec![self];

        while let Some(node) = pending.pop() {
            for (name, child) in node.properties.iter().flatten() {
                properties += 1;
                chars += name.len();
                pending.push(child);
            }
        }

        properties <= MAX_SCHEMA_PROPERTIES && chars <= MAX_SCHEMA_NAME_CHARS
    }
}