aien-translate
aien-dev/aien-translate
Brought by drakestapleton
aien-translate / src / engine.rs
| 1 | //! Talks to AIEN's inference server (aien-serve-http, OpenAI-style API). |
| 2 | |
| 3 | use crate::langs::Lang; |
| 4 | use serde_json::{json, Value}; |
| 5 | use std::time::Duration; |
| 6 | use tokio::sync::{Mutex, Semaphore}; |
| 7 | |
| 8 | pub struct Engine { |
| 9 | client: reqwest::Client, |
| 10 | base: String, |
| 11 | model: Mutex<Option<String>>, |
| 12 | /// The GPU is shared, so send one request at a time. |
| 13 | gate: Semaphore, |
| 14 | } |
| 15 | |
| 16 | impl Engine { |
| 17 | pub fn new(base: &str) -> Self { |
| 18 | Self { |
| 19 | client: reqwest::Client::builder() |
| 20 | .timeout(Duration::from_secs(300)) |
| 21 | .build() |
| 22 | .expect("http client"), |
| 23 | base: base.trim_end_matches('/').to_string(), |
| 24 | model: Mutex::new(None), |
| 25 | gate: Semaphore::new(1), |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /// Model id served by the engine, asked once and remembered. |
| 30 | pub async fn model(&self) -> Result<String, String> { |
| 31 | let mut m = self.model.lock().await; |
| 32 | if let Some(id) = m.as_ref() { |
| 33 | return Ok(id.clone()); |
| 34 | } |
| 35 | // While the engine restarts (model swap, rebuild) the list is unreachable or empty; wait. |
| 36 | let deadline = std::time::Instant::now() + DOWN_WAIT_LIMIT; |
| 37 | let id = loop { |
| 38 | let got: Result<String, String> = async { |
| 39 | let v: Value = self |
| 40 | .client |
| 41 | .get(format!("{}/v1/models", self.base)) |
| 42 | .timeout(Duration::from_secs(10)) |
| 43 | .send() |
| 44 | .await |
| 45 | .map_err(|e| format!("engine unreachable: {e}"))? |
| 46 | .json() |
| 47 | .await |
| 48 | .map_err(|e| format!("engine model list unreadable: {e}"))?; |
| 49 | Ok(v["data"][0]["id"].as_str().ok_or("engine serves no model")?.to_string()) |
| 50 | } |
| 51 | .await; |
| 52 | match got { |
| 53 | Ok(id) => break id, |
| 54 | Err(e) if std::time::Instant::now() < deadline => { |
| 55 | eprintln!("aien-translate: {e}; waiting for the engine"); |
| 56 | tokio::time::sleep(DOWN_RETRY).await; |
| 57 | } |
| 58 | Err(e) => return Err(e), |
| 59 | } |
| 60 | }; |
| 61 | *m = Some(id.clone()); |
| 62 | Ok(id) |
| 63 | } |
| 64 | |
| 65 | /// Translate a batch. Returns one entry per input, or an error if the |
| 66 | /// model's answer could not be matched up with the inputs. |
| 67 | pub async fn translate( |
| 68 | &self, |
| 69 | from: Option<&Lang>, |
| 70 | to: &Lang, |
| 71 | texts: &[String], |
| 72 | keep: &[String], |
| 73 | ) -> Result<Vec<String>, String> { |
| 74 | let model = self.model().await?; |
| 75 | let from_name = from.map(|l| l.english).unwrap_or("its original language"); |
| 76 | let keep_list = if keep.is_empty() { "none".to_string() } else { keep.join(", ") }; |
| 77 | let system = format!( |
| 78 | "You are a professional translator for software websites and documentation.\n\ |
| 79 | Translate every string in the JSON array the user sends from {from_name} into {to}.\n\ |
| 80 | Rules:\n\ |
| 81 | - Reply with ONLY a JSON array of exactly {n} strings, in the same order. No commentary.\n\ |
| 82 | - Keep these exactly as written: URLs, email addresses, anything in backticks, commands, \ |
| 83 | file paths, code, placeholders like {{name}}, {{{{name}}}} or %s, and these names: {keep_list}.\n\ |
| 84 | - Strings may contain markers like <g1>...</g1> (around words that are a link or bold) and <x2/> (code): \ |
| 85 | keep every marker exactly once, around the translated words they belong to.\n\ |
| 86 | - Translate meaning naturally; keep punctuation style and capitalization style sensible for {to}.\n\ |
| 87 | - If a string is already in {to} or cannot be translated, return it unchanged.", |
| 88 | to = to.english, |
| 89 | n = texts.len(), |
| 90 | ); |
| 91 | let user = serde_json::to_string(texts).unwrap(); |
| 92 | let chars: usize = texts.iter().map(|t| t.chars().count()).sum(); |
| 93 | let max_tokens = (128 + chars * 3).min(ENGINE_MAX_TOKENS); |
| 94 | let body = json!({ |
| 95 | "model": model, |
| 96 | "temperature": 0, |
| 97 | "max_tokens": max_tokens, |
| 98 | "stream": true, |
| 99 | "messages": [ |
| 100 | {"role": "system", "content": system}, |
| 101 | {"role": "user", "content": user}, |
| 102 | ], |
| 103 | }); |
| 104 | |
| 105 | let _permit = self.gate.acquire().await.map_err(|e| e.to_string())?; |
| 106 | let resp = match self.send_when_free(&body).await { |
| 107 | Ok(r) => r, |
| 108 | Err(e) => { |
| 109 | *self.model.lock().await = None; |
| 110 | return Err(e); |
| 111 | } |
| 112 | }; |
| 113 | let status = resp.status(); |
| 114 | let streaming = resp |
| 115 | .headers() |
| 116 | .get(reqwest::header::CONTENT_TYPE) |
| 117 | .and_then(|v| v.to_str().ok()) |
| 118 | .is_some_and(|v| v.starts_with("text/event-stream")); |
| 119 | if !status.is_success() || !streaming { |
| 120 | let v: Value = resp.json().await.map_err(|e| format!("engine reply unreadable: {e}"))?; |
| 121 | if !status.is_success() { |
| 122 | return Err(format!("engine error {status}: {}", v["error"]["message"])); |
| 123 | } |
| 124 | let content = v["choices"][0]["message"]["content"].as_str().unwrap_or(""); |
| 125 | return parse_array(content, texts.len()); |
| 126 | } |
| 127 | let content = read_until_list_closes(resp).await?; |
| 128 | parse_array(&content, texts.len()) |
| 129 | } |
| 130 | |
| 131 | /// Send a chat request, waiting while the engine says it is busy (503). |
| 132 | /// It is busy for a moment after a reply is cut short, and for longer when |
| 133 | /// another job holds the GPU. It says how long to wait in `Retry-After`. |
| 134 | async fn send_when_free(&self, body: &Value) -> Result<reqwest::Response, String> { |
| 135 | let deadline = std::time::Instant::now() + BUSY_WAIT_LIMIT; |
| 136 | let down_deadline = std::time::Instant::now() + DOWN_WAIT_LIMIT; |
| 137 | let mut said_down = false; |
| 138 | loop { |
| 139 | let resp = match self |
| 140 | .client |
| 141 | .post(format!("{}/v1/chat/completions", self.base)) |
| 142 | .json(body) |
| 143 | .send() |
| 144 | .await |
| 145 | { |
| 146 | Ok(r) => r, |
| 147 | // The engine restarts when its model is swapped or rebuilt. Wait for it to come back |
| 148 | // rather than failing every batch (which would leave whole languages in English). |
| 149 | Err(e) if e.is_connect() && std::time::Instant::now() < down_deadline => { |
| 150 | if !said_down { |
| 151 | eprintln!("aien-translate: engine unreachable ({e}); waiting for it to come back"); |
| 152 | said_down = true; |
| 153 | } |
| 154 | *self.model.lock().await = None; |
| 155 | tokio::time::sleep(DOWN_RETRY).await; |
| 156 | continue; |
| 157 | } |
| 158 | Err(e) => return Err(format!("engine request failed: {e}")), |
| 159 | }; |
| 160 | if resp.status() != reqwest::StatusCode::SERVICE_UNAVAILABLE { |
| 161 | return Ok(resp); |
| 162 | } |
| 163 | let wait = resp |
| 164 | .headers() |
| 165 | .get(reqwest::header::RETRY_AFTER) |
| 166 | .and_then(|v| v.to_str().ok()) |
| 167 | .and_then(|v| v.trim().parse::<f64>().ok()) |
| 168 | .map(Duration::from_secs_f64) |
| 169 | .unwrap_or(Duration::from_secs(1)) |
| 170 | .clamp(Duration::from_millis(200), Duration::from_secs(5)); |
| 171 | if std::time::Instant::now() + wait > deadline { |
| 172 | return Ok(resp); |
| 173 | } |
| 174 | tokio::time::sleep(wait).await; |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// How long to keep retrying a busy engine before giving up on a batch. |
| 180 | const BUSY_WAIT_LIMIT: Duration = Duration::from_secs(30 * 60); |
| 181 | |
| 182 | /// How long to wait for an engine that is down (restarting, model being swapped) before |
| 183 | /// giving up on a batch, and how often to try again meanwhile. |
| 184 | const DOWN_WAIT_LIMIT: Duration = Duration::from_secs(45 * 60); |
| 185 | const DOWN_RETRY: Duration = Duration::from_secs(15); |
| 186 | |
| 187 | /// aien-serve-http clamps `max_tokens` to this, so asking for more only hides |
| 188 | /// where a reply will stop. |
| 189 | pub const ENGINE_MAX_TOKENS: usize = 4096; |
| 190 | |
| 191 | /// Read a streamed reply, and hang up as soon as its list is complete. The |
| 192 | /// model sometimes keeps writing after the list (seen: invented text up to the |
| 193 | /// token cap, 140 s of GPU time); dropping the connection makes the server |
| 194 | /// stop generating. |
| 195 | async fn read_until_list_closes(mut resp: reqwest::Response) -> Result<String, String> { |
| 196 | let mut buf: Vec<u8> = Vec::new(); |
| 197 | let mut content = String::new(); |
| 198 | while let Some(chunk) = resp.chunk().await.map_err(|e| format!("engine stream failed: {e}"))? { |
| 199 | buf.extend_from_slice(&chunk); |
| 200 | while let Some(pos) = buf.iter().position(|&b| b == b'\n') { |
| 201 | let line: Vec<u8> = buf.drain(..=pos).collect(); |
| 202 | let line = String::from_utf8_lossy(&line); |
| 203 | let Some(data) = line.trim().strip_prefix("data:") else { continue }; |
| 204 | let data = data.trim(); |
| 205 | if data == "[DONE]" { |
| 206 | return Ok(content); |
| 207 | } |
| 208 | let Ok(v) = serde_json::from_str::<Value>(data) else { continue }; |
| 209 | if let Some(err) = v.get("error") { |
| 210 | return Err(format!("engine error: {}", err["message"])); |
| 211 | } |
| 212 | if let Some(d) = v["choices"][0]["delta"]["content"].as_str() { |
| 213 | content.push_str(d); |
| 214 | } |
| 215 | } |
| 216 | if list_closed(&content) { |
| 217 | return Ok(content); |
| 218 | } |
| 219 | } |
| 220 | Ok(content) |
| 221 | } |
| 222 | |
| 223 | /// Where a reply's list stands, scanning from its first `[` and skipping any |
| 224 | /// brackets inside strings (translations can contain text like `["x"]`). |
| 225 | enum ListScan { |
| 226 | NoList, |
| 227 | Closed { start: usize, end: usize }, |
| 228 | Open { start: usize, in_string: bool }, |
| 229 | } |
| 230 | |
| 231 | fn scan_list(content: &str) -> ListScan { |
| 232 | let Some(start) = content.find('[') else { return ListScan::NoList }; |
| 233 | let (mut depth, mut in_string, mut escaped) = (0usize, false, false); |
| 234 | for (i, ch) in content[start..].char_indices() { |
| 235 | if in_string { |
| 236 | if escaped { |
| 237 | escaped = false; |
| 238 | } else if ch == '\\' { |
| 239 | escaped = true; |
| 240 | } else if ch == '"' { |
| 241 | in_string = false; |
| 242 | } |
| 243 | continue; |
| 244 | } |
| 245 | match ch { |
| 246 | '"' => in_string = true, |
| 247 | '[' | '{' => depth += 1, |
| 248 | ']' | '}' => { |
| 249 | depth = depth.saturating_sub(1); |
| 250 | if depth == 0 { |
| 251 | return ListScan::Closed { start, end: start + i }; |
| 252 | } |
| 253 | } |
| 254 | _ => {} |
| 255 | } |
| 256 | } |
| 257 | ListScan::Open { start, in_string } |
| 258 | } |
| 259 | |
| 260 | /// True once the reply contains a complete list. |
| 261 | pub fn list_closed(content: &str) -> bool { |
| 262 | matches!(scan_list(content), ListScan::Closed { .. }) |
| 263 | } |
| 264 | |
| 265 | /// Pull the JSON array of strings out of a model reply. Text after the list is |
| 266 | /// ignored. A list whose strings are all complete but whose closing `]` is |
| 267 | /// missing (the model sometimes stops one character early) is closed and |
| 268 | /// accepted; the item count is still checked. |
| 269 | pub fn parse_array(content: &str, expect: usize) -> Result<Vec<String>, String> { |
| 270 | let list = match scan_list(content) { |
| 271 | ListScan::NoList => return Err("no JSON array in reply".into()), |
| 272 | ListScan::Closed { start, end } => content[start..=end].to_string(), |
| 273 | ListScan::Open { in_string: true, .. } => return Err("reply ends in the middle of a string".into()), |
| 274 | ListScan::Open { start, in_string: false } => { |
| 275 | let mut s = content[start..].trim_end().trim_end_matches(',').to_string(); |
| 276 | s.push(']'); |
| 277 | s |
| 278 | } |
| 279 | }; |
| 280 | let arr: Vec<String> = |
| 281 | serde_json::from_str(&list).map_err(|e| format!("reply is not a string array: {e}"))?; |
| 282 | if arr.len() != expect { |
| 283 | return Err(format!("reply has {} items, expected {expect}", arr.len())); |
| 284 | } |
| 285 | Ok(arr) |
| 286 | } |
| 287 | |
| 288 | #[cfg(test)] |
| 289 | mod tests { |
| 290 | use super::parse_array; |
| 291 | use serde_json::Value; |
| 292 | |
| 293 | fn fixture(name: &str) -> (Vec<String>, String) { |
| 294 | let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR")); |
| 295 | let v: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); |
| 296 | let items = serde_json::from_value(v["items"].clone()).unwrap(); |
| 297 | (items, v["content"].as_str().unwrap().to_string()) |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn parses_fenced_reply() { |
| 302 | let r = parse_array("```json\n[\"你好\", \"世界\"]\n```", 2).unwrap(); |
| 303 | assert_eq!(r, vec!["你好", "世界"]); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn rejects_wrong_count() { |
| 308 | assert!(parse_array("[\"a\"]", 2).is_err()); |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn bracket_inside_a_string_is_not_the_end() { |
| 313 | let r = parse_array(r#"["e.g. `[\"x\"]` here", "two"]"#, 2).unwrap(); |
| 314 | assert_eq!(r, vec![r#"e.g. `["x"]` here"#, "two"]); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn text_after_the_list_is_ignored() { |
| 319 | let r = parse_array("[\"a\", \"b\"]\n\n[{\"name\": \"junk\"", 2).unwrap(); |
| 320 | assert_eq!(r, vec!["a", "b"]); |
| 321 | } |
| 322 | |
| 323 | #[test] |
| 324 | fn one_missing_closing_bracket_is_repaired() { |
| 325 | assert_eq!(parse_array("[\"a\", \"b\"", 2).unwrap(), vec!["a", "b"]); |
| 326 | assert_eq!(parse_array("[\"a\", \"b\",\n", 2).unwrap(), vec!["a", "b"]); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn reply_cut_off_inside_a_string_is_refused() { |
| 331 | assert!(parse_array("[\"a\", \"b is cut o", 2).is_err()); |
| 332 | } |
| 333 | |
| 334 | /// Real reply: the model ended without the list's closing `]`, and one |
| 335 | /// item contains `["こんにちは世界"]`. |
| 336 | #[test] |
| 337 | fn real_reply_missing_close_ja() { |
| 338 | let (items, content) = fixture("reply_missing_close_ja.json"); |
| 339 | let r = parse_array(&content, items.len()).unwrap(); |
| 340 | assert_eq!(r.len(), 29); |
| 341 | assert!(r[28].contains("オリジナル"), "{}", r[28]); |
| 342 | } |
| 343 | |
| 344 | /// Real reply: a complete list, then invented text until the token cap. |
| 345 | #[test] |
| 346 | fn real_reply_trailing_junk_fr() { |
| 347 | let (items, content) = fixture("reply_trailing_junk_fr.json"); |
| 348 | let r = parse_array(&content, items.len()).unwrap(); |
| 349 | assert_eq!(r.len(), 29); |
| 350 | assert!(!r.iter().any(|s| s.contains("\"name\""))); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn list_closed_detection() { |
| 355 | use super::list_closed; |
| 356 | assert!(!list_closed("[\"a\", \"b")); |
| 357 | assert!(!list_closed("[\"a ] still inside\"")); |
| 358 | assert!(list_closed("[\"a\", \"b\"]")); |
| 359 | assert!(list_closed("sure: [\"a\"] and more")); |
| 360 | assert!(!list_closed("no list yet")); |
| 361 | } |
| 362 | } |