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 laravel::http::client;
use laravel::time::ToSpan;
use serde::Serialize;
use serde_json::Value;

use super::openai::texts_as_json;
use super::{backoff_seconds, decode_error, json_body, real_sleeper, refusal, retryable};
use crate::limits::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.anthropic.com/v1/messages";
const API_VERSION: &str = "2023-06-01";

/// Tokens left for a model that thinks by default, on top of the answer: thinking counts against
/// `max_tokens`. Well under the 32,000 past which Anthropic sends thinking to batch processing.
const THINKING_RESERVE: u64 = 16_000;

/// Translates with Anthropic's [Messages API](https://docs.anthropic.com/en/api/messages),
/// `claude-haiku-4-5` unless `TextsConfig::claude.model` says otherwise.
///
/// The system prompt is marked for prompt caching, so repeated batches in a single scan reuse the
/// cached instructions. Like the OpenAI translator, it asks each model only for what it accepts,
/// sizes its batches by the answer they produce and splits a batch whose answer was cut short.
#[derive(Clone)]
pub struct ClaudeTranslator {
    sleeper: Arc<dyn Sleeper>,
}

impl ClaudeTranslator {
    /// 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().claude.model
    }

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

    fn max_tokens(&self) -> u64 {
        config().claude.max_tokens.max(256).min(self.limits().max_output_tokens)
    }

    /// 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) -> Result<Option<Value>, TranslateError> {
        let limits = self.limits();
        let settings = config().claude;
        let attempts = settings.retries.max(1);

        let body = Body {
            model: self.model(),
            max_tokens: limits
                .max_output_tokens
                .min(self.max_tokens() + if limits.reasoning { THINKING_RESERVE } else { 0 }),
            system: [SystemBlock {
                kind: "text",
                text: system,
                cache_control: CacheControl { kind: "ephemeral" },
            }],
            messages: [Message {
                role: "user",
                content: user,
            }],
            temperature: limits.temperature.then_some(0),
        };

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

        for attempt in 1..=attempts {
            let response = client::post(ENDPOINT)
                .header("x-api-key", &key)
                .header("anthropic-version", API_VERSION)
                .timeout((settings.timeout as i64).seconds())
                .json(&body)
                .await
                .map_err(|error| TranslateError::failed(error.to_string()))?;

            if !response.successful() {
                log_to_console(format!(
                    "⚠️  Claude 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.get("stop_reason"))
                .and_then(Value::as_str)
                == Some("max_tokens")
            {
                return Err(TranslateError::Truncated(
                    "Claude stopped at the output limit.".to_owned(),
                ));
            }

            // A model that thinks first answers a `thinking` block before the text one.
            let text: String = answer
                .as_ref()
                .and_then(|answer| answer.get("content"))
                .and_then(Value::as_array)
                .map(|blocks| {
                    blocks
                        .iter()
                        .filter(|block| block.get("type").and_then(Value::as_str) == Some("text"))
                        .filter_map(|block| block.get("text").and_then(Value::as_str))
                        .collect()
                })
                .unwrap_or_default();

            let content = strip_code_fences(trim(&text));

            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 ClaudeTranslator {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Translator for ClaudeTranslator {
    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,
            )
            .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 Claude 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),
            )
            .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.max_tokens() as usize)
    }
}

/// Strip markdown code fences that Claude sometimes wraps JSON output in, even when asked not to.
///
/// What `preg_replace('/^```(?:json)?\s*/m', '', ...)` and `preg_replace('/\s*```$/m', '', ...)`
/// do, one after the other, followed by a `trim`.
pub(crate) fn strip_code_fences(content: &str) -> String {
    let content = strip_opening_fences(content);
    let content = strip_closing_fences(&content);

    trim(&content).to_owned()
}

fn is_space(character: char) -> bool {
    matches!(character, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
}

/// A ```` ``` ````, with an optional `json` and the whitespace after it, at the start of a line.
fn strip_opening_fences(content: &str) -> String {
    let mut result = String::with_capacity(content.len());
    let mut index = 0;

    while index < content.len() {
        let at_line_start = index == 0 || content.as_bytes()[index - 1] == b'\n';

        if at_line_start && let Some(after) = content[index..].strip_prefix("```") {
            let after = after.strip_prefix("json").unwrap_or(after);
            let skipped = after.len() - after.trim_start_matches(is_space).len();

            index = content.len() - after.len() + skipped;

            continue;
        }

        let character = content[index..].chars().next().unwrap_or_default();

        result.push(character);
        index += character.len_utf8();
    }

    result
}

/// The whitespace before a ```` ``` ```` at the end of a line, and the fence itself.
fn strip_closing_fences(content: &str) -> String {
    let mut result = String::with_capacity(content.len());
    let mut rest = content;

    while let Some(position) = rest.find("```") {
        let after = &rest[position + 3..];

        if after.is_empty() || after.starts_with('\n') {
            result.push_str(rest[..position].trim_end_matches(is_space));

            rest = after;
        } else {
            result.push_str(&rest[..position + 3]);

            rest = after;
        }
    }

    result.push_str(rest);

    result
}

#[derive(Serialize)]
struct Body<'a> {
    model: String,
    max_tokens: u64,
    system: [SystemBlock<'a>; 1],
    messages: [Message<'a>; 1],
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<u8>,
}

#[derive(Serialize)]
struct SystemBlock<'a> {
    #[serde(rename = "type")]
    kind: &'static str,
    text: &'a str,
    cache_control: CacheControl,
}

#[derive(Serialize)]
struct CacheControl {
    #[serde(rename = "type")]
    kind: &'static str,
}

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

#[cfg(test)]
mod tests {
    use super::strip_code_fences;

    #[test]
    fn a_fenced_answer_loses_its_fences() {
        assert_eq!(
            strip_code_fences("```json\n{\"es\": \"Hola\"}\n```"),
            "{\"es\": \"Hola\"}"
        );
        assert_eq!(strip_code_fences("```\n{\"a\": 1}\n```"), "{\"a\": 1}");
    }

    #[test]
    fn an_answer_without_fences_is_left_alone() {
        assert_eq!(strip_code_fences("  {\"a\": \"b```c\"}  "), "{\"a\": \"b```c\"}");
    }
}