weirdnet-openai 0.2.5

Loopback-only OpenAI-compatible bridge over a weirdnet-agent inference pool: chat completions (streaming, images, audio, video), models, embeddings, speech and transcriptions, with a bearer token, a Host check and no CORS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! OpenAI request bodies to `weirdnet-agent` infer/2 requests.

use base64::Engine as _;
use serde_json::{Map, Value};
use weirdnet_agent::remote::infer::v2::{CacheMode, EmbedRequest, Request, ResponseFormat, ScriptTurn, SpeakInput, SpeakRequest, Voice};
use weirdnet_agent::{AudioFormat, Content, ContentPart, Message, Role, ToolCall, ToolSpec};

/// A request the bridge cannot take; answered with 400.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BadRequest(pub String);

fn bad(msg: impl Into<String>) -> BadRequest {
    BadRequest(msg.into())
}

fn object(body: Value) -> Result<Map<String, Value>, BadRequest> {
    match body {
        Value::Object(o) => Ok(o),
        _ => Err(bad("body must be a JSON object")),
    }
}

/// One content part: `text`, `image_url` (a `data:image/...` URL, as an object or a bare string),
/// `input_audio` (`data` and `format`) or `video_url` (a `data:video/...` URL, as an object or a
/// bare string). Other types are refused.
fn part(p: &Value) -> Result<ContentPart, BadRequest> {
    match p["type"].as_str() {
        Some("text") => Ok(ContentPart::text(p["text"].as_str().unwrap_or_default())),
        Some("image_url") => {
            let (url, detail) = match &p["image_url"] {
                Value::String(u) => (u.as_str(), None),
                o => (o["url"].as_str().ok_or_else(|| bad("image_url parts need `image_url.url`"))?, o["detail"].as_str()),
            };
            let mut part = ContentPart::image(url);
            if let (ContentPart::ImageUrl { image_url }, Some(d)) = (&mut part, detail) {
                image_url.detail = Some(d.to_string());
            }
            Ok(part)
        }
        Some("input_audio") => {
            let a = &p["input_audio"];
            Ok(ContentPart::audio(a["data"].as_str().unwrap_or_default(), a["format"].as_str().unwrap_or_default()))
        }
        Some("video_url") => {
            let url = match &p["video_url"] {
                Value::String(u) => u.as_str(),
                o => o["url"].as_str().ok_or_else(|| bad("video_url parts need `video_url.url`"))?,
            };
            if !url.starts_with("data:video/") {
                return Err(bad("video_url must be a data:video/...;base64, URL; remote video URLs are never fetched"));
            }
            Ok(ContentPart::video(url))
        }
        Some(other) => Err(bad(format!("content parts of type `{other}` are not supported"))),
        None => Err(bad("content parts need a `type`")),
    }
}

/// Message content: a string, or parts. Text-only parts are joined into a string (the form every
/// node reads); images, audio and video go through as parts, checked by [`Content::check`].
fn content(v: Option<&Value>) -> Result<Content, BadRequest> {
    match v {
        None | Some(Value::Null) => Ok(Content::default()),
        Some(Value::String(s)) => Ok(s.clone().into()),
        Some(Value::Array(parts)) => {
            let c = Content::from(parts.iter().map(part).collect::<Result<Vec<_>, _>>()?).normalized();
            c.check().map_err(bad)?;
            Ok(c)
        }
        Some(_) => Err(bad("`content` must be a string or an array of parts")),
    }
}

fn tool_calls(v: Option<&Value>) -> Result<Vec<ToolCall>, BadRequest> {
    let Some(Value::Array(calls)) = v else { return Ok(Vec::new()) };
    calls
        .iter()
        .map(|c| {
            let f = &c["function"];
            let name = f["name"].as_str().ok_or_else(|| bad("tool calls need `function.name`"))?;
            let arguments = match &f["arguments"] {
                Value::String(s) => serde_json::from_str(s).unwrap_or_else(|_| Value::String(s.clone())),
                Value::Null => Value::Object(Map::new()),
                other => other.clone(),
            };
            Ok(ToolCall { id: c["id"].as_str().unwrap_or_default().to_string(), name: name.to_string(), arguments })
        })
        .collect()
}

fn message(m: &Value) -> Result<Message, BadRequest> {
    let text = content(m.get("content"))?;
    match m["role"].as_str() {
        Some("system" | "developer") => Ok(Message::system(text)),
        Some("user") => Ok(Message::user(text)),
        Some("assistant") => Ok(Message::assistant(text, tool_calls(m.get("tool_calls"))?)),
        Some("tool") => Ok(Message::tool(m["tool_call_id"].as_str().ok_or_else(|| bad("tool messages need `tool_call_id`"))?, text)),
        Some(other) => Err(bad(format!("unknown role `{other}`"))),
        None => Err(bad("messages need a `role`")),
    }
}

fn tools(v: Option<&Value>) -> Result<Vec<ToolSpec>, BadRequest> {
    let Some(Value::Array(tools)) = v else { return Ok(Vec::new()) };
    tools
        .iter()
        .map(|t| {
            if t["type"].as_str().is_some_and(|k| k != "function") {
                return Err(bad("only function tools are supported"));
            }
            let f = &t["function"];
            let name = f["name"].as_str().ok_or_else(|| bad("tools need `function.name`"))?;
            let mut spec = ToolSpec::new(name, f["description"].as_str().unwrap_or_default());
            if !f["parameters"].is_null() {
                spec.input_schema = f["parameters"].clone();
            }
            Ok(spec)
        })
        .collect()
}

fn response_format(v: Option<&Value>) -> Result<Option<ResponseFormat>, BadRequest> {
    let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(None) };
    match v["type"].as_str() {
        Some("text") => Ok(Some(ResponseFormat::Text)),
        Some("json_object") => Ok(Some(ResponseFormat::Json)),
        Some("json_schema") => {
            let s = &v["json_schema"];
            Ok(Some(ResponseFormat::JsonSchema {
                name: s["name"].as_str().unwrap_or("response").to_string(),
                schema: s["schema"].clone(),
                strict: s["strict"].as_bool().unwrap_or(false),
            }))
        }
        _ => Err(bad("`response_format.type` must be text, json_object or json_schema")),
    }
}

fn f32_of(o: &Map<String, Value>, key: &str) -> Result<Option<f32>, BadRequest> {
    match o.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(v) => v.as_f64().map(|f| Some(f as f32)).ok_or_else(|| bad(format!("`{key}` must be a number"))),
    }
}

fn u32_of(o: &Map<String, Value>, key: &str) -> Result<Option<u32>, BadRequest> {
    match o.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(v) => v.as_u64().and_then(|n| u32::try_from(n).ok()).map(Some).ok_or_else(|| bad(format!("`{key}` must be a whole number"))),
    }
}

/// `model`, if given, must be a string.
fn model(o: &Map<String, Value>) -> Result<Option<String>, BadRequest> {
    match o.get("model") {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(m)) if !m.is_empty() => Ok(Some(m.clone())),
        _ => Err(bad("`model` must be a non-empty string")),
    }
}

/// A boolean parameter, false when absent.
fn flag(o: &Map<String, Value>, key: &str) -> Result<bool, BadRequest> {
    match o.get(key) {
        None | Some(Value::Null) => Ok(false),
        Some(Value::Bool(b)) => Ok(*b),
        Some(_) => Err(bad(format!("`{key}` must be true or false"))),
    }
}

/// A `/v1/chat/completions` body: the request and whether to stream. Known sampling parameters,
/// `seed`, `response_format` and `tools` are mapped, and `continue_final_message` (vLLM) continues
/// the last assistant message; other parameters are ignored.
pub fn chat(body: Value) -> Result<(Request, bool), BadRequest> {
    let o = object(body)?;
    let messages = match o.get("messages") {
        Some(Value::Array(m)) if !m.is_empty() => m.iter().map(message).collect::<Result<Vec<_>, _>>()?,
        _ => return Err(bad("`messages` must be a non-empty array")),
    };
    let stream = o.get("stream").and_then(Value::as_bool).unwrap_or(false);
    let continues = flag(&o, "continue_final_message")?;
    if continues {
        if flag(&o, "add_generation_prompt")? {
            return Err(bad("`continue_final_message` and `add_generation_prompt` cannot both be true"));
        }
        if !messages.last().is_some_and(|m| m.role == Role::Assistant && m.tool_calls.is_empty()) {
            return Err(bad("`continue_final_message` needs the last message to be an assistant message without tool calls"));
        }
    }
    let mut req = Request::messages(messages);
    if continues {
        req = req.continuing();
    }
    sampling_and_seed(&o, &mut req)?;
    req.response_format = response_format(o.get("response_format"))?;
    req.tools = tools(o.get("tools"))?;
    Ok((req, stream))
}

/// `model`, sampling parameters, `seed`, `cache` and `adapter_scale` (a weirdnet extension: how
/// strongly a LoRA adapter model applies, infer/2 `Request::adapter_scale`), shared by chat and
/// text completions.
fn sampling_and_seed(o: &Map<String, Value>, req: &mut Request) -> Result<(), BadRequest> {
    req.model = model(o)?;
    let s = &mut req.sampling;
    s.temperature = f32_of(o, "temperature")?;
    s.top_p = f32_of(o, "top_p")?;
    s.top_k = u32_of(o, "top_k")?;
    s.min_p = f32_of(o, "min_p")?;
    s.max_tokens = match u32_of(o, "max_completion_tokens")? {
        Some(n) => Some(n),
        None => u32_of(o, "max_tokens")?,
    };
    s.stop = match o.get("stop") {
        None | Some(Value::Null) => Vec::new(),
        Some(Value::String(s)) => vec![s.clone()],
        Some(Value::Array(a)) if a.iter().all(Value::is_string) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),
        Some(_) => return Err(bad("`stop` must be a string or an array of strings")),
    };
    s.presence_penalty = f32_of(o, "presence_penalty")?;
    s.frequency_penalty = f32_of(o, "frequency_penalty")?;
    s.repeat_penalty = match f32_of(o, "repeat_penalty")? {
        Some(p) => Some(p),
        None => f32_of(o, "repetition_penalty")?,
    };
    req.seed = match o.get("seed") {
        None | Some(Value::Null) => None,
        Some(v) => Some(v.as_u64().ok_or_else(|| bad("`seed` must be a whole number"))?),
    };
    req.cache = cache(o.get("cache"))?;
    req.adapter_scale = match f32_of(o, "adapter_scale")? {
        Some(s) if !s.is_finite() => return Err(bad("`adapter_scale` must be a finite number")),
        s => s,
    };
    Ok(())
}

/// The `cache` body parameter (a weirdnet extension): absent, `null`, `true` or `"use"` uses the
/// node's answer cache; `false`, `"bypass"` or `"off"` skips it; `"refresh"` skips the read and
/// stores the fresh answer.
fn cache(v: Option<&Value>) -> Result<CacheMode, BadRequest> {
    match v {
        None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(CacheMode::Use),
        Some(Value::Bool(false)) => Ok(CacheMode::Bypass),
        Some(Value::String(s)) => cache_word(s).ok_or_else(|| bad("`cache` must be true, false, \"use\", \"bypass\" or \"refresh\"")),
        Some(_) => Err(bad("`cache` must be true, false, \"use\", \"bypass\" or \"refresh\"")),
    }
}

/// A cache mode by name: `use`/`on`, `bypass`/`off`, `refresh` (any case).
fn cache_word(s: &str) -> Option<CacheMode> {
    match s.trim().to_ascii_lowercase().as_str() {
        "use" | "on" => Some(CacheMode::Use),
        "bypass" | "off" => Some(CacheMode::Bypass),
        "refresh" => Some(CacheMode::Refresh),
        _ => None,
    }
}

/// The `x-weirdnet-cache` request header: `off` (or `bypass`), `refresh`, or `use` (or `on`).
pub fn cache_header(value: &str) -> Result<CacheMode, BadRequest> {
    cache_word(value).ok_or_else(|| bad("`x-weirdnet-cache` must be off, refresh or use"))
}

/// The stricter of two cache modes: `bypass` over `refresh` over `use`.
pub fn stricter(a: CacheMode, b: CacheMode) -> CacheMode {
    fn rank(m: CacheMode) -> u8 {
        match m {
            CacheMode::Use => 0,
            CacheMode::Refresh => 1,
            // Bypass, and any later mode: neither read nor store.
            _ => 2,
        }
    }
    if rank(b) > rank(a) { b } else { a }
}

/// A `/v1/completions` body: a raw-prompt request and whether to stream. `prompt` is a string
/// (or an array of one string); sampling parameters and `seed` map as for chat. `n`, `best_of`
/// above 1, `echo`, `suffix` and `logprobs` are refused; other parameters are ignored.
pub fn completion(body: Value) -> Result<(Request, bool), BadRequest> {
    let o = object(body)?;
    let prompt = match o.get("prompt") {
        Some(Value::String(p)) => p.clone(),
        Some(Value::Array(a)) if a.len() == 1 && a[0].is_string() => a[0].as_str().unwrap_or_default().to_string(),
        Some(Value::Array(a)) if a.iter().all(Value::is_string) => return Err(bad("one prompt per request")),
        _ => return Err(bad("`prompt` must be a string")),
    };
    for key in ["n", "best_of"] {
        if u32_of(&o, key)?.is_some_and(|n| n > 1) {
            return Err(bad(format!("`{key}` above 1 is not supported")));
        }
    }
    if o.get("echo").and_then(Value::as_bool).unwrap_or(false) {
        return Err(bad("`echo` is not supported"));
    }
    for key in ["suffix", "logprobs"] {
        if o.get(key).is_some_and(|v| !v.is_null() && *v != Value::Bool(false)) {
            return Err(bad(format!("`{key}` is not supported")));
        }
    }
    let stream = o.get("stream").and_then(Value::as_bool).unwrap_or(false);
    let mut req = Request::prompt(prompt);
    sampling_and_seed(&o, &mut req)?;
    Ok((req, stream))
}

/// A `/v1/embeddings` body. Only `encoding_format: "float"`.
pub fn embed(body: Value) -> Result<EmbedRequest, BadRequest> {
    let o = object(body)?;
    let inputs = match o.get("input") {
        Some(Value::String(s)) => vec![s.clone()],
        Some(Value::Array(a)) if !a.is_empty() && a.iter().all(Value::is_string) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),
        _ => return Err(bad("`input` must be a string or a non-empty array of strings")),
    };
    if o.get("encoding_format").and_then(Value::as_str).is_some_and(|f| f != "float") {
        return Err(bad("only encoding_format = \"float\" is supported"));
    }
    let mut req = EmbedRequest::new(inputs);
    req.model = model(&o)?;
    Ok(req)
}

/// A `/v1/audio/speech` body (OpenAI's shape plus Weirdnet extensions under `weirdnet`): the
/// request and whether to stream the audio as it comes (`stream_format: "audio"`).
///
/// - `input` (the text), `model`, `voice` (a preset name, or `{"id": name}`; never mapped to another
///   voice: a name the model lacks is refused by the catalog check with its presets),
///   `instructions`, `response_format` (`wav`, `pcm`, `mp3`, `opus` or `flac`; absent: the model's
///   first format), `speed` (a multiple of the model's pace, sent as per mille).
/// - `stream_format`: `"audio"` streams the bytes as the node sends them; `"sse"` is refused;
///   absent: the whole file in one answer.
/// - `weirdnet`: `language`, `seed`, `sample_rate`, `design` (a voice description), `ref_audio` (a
///   `data:` URL only; remote URLs are never fetched) with `ref_text` and `consent` (a cloned voice),
///   `script` (`[{"speaker": 0, "text": "..."}]`, instead of `input`) and `raw` (`input` goes to the
///   engine with no template). At most one of `voice`, `design` and `ref_audio`.
pub fn speech(body: Value) -> Result<(SpeakRequest, bool), BadRequest> {
    let o = object(body)?;
    let empty = Map::new();
    let w = match o.get("weirdnet") {
        None | Some(Value::Null) => &empty,
        Some(Value::Object(w)) => w,
        Some(_) => return Err(bad("`weirdnet` must be an object")),
    };
    let text = match o.get("input") {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) => Some(s.clone()),
        Some(_) => return Err(bad("`input` must be a string")),
    };
    let raw = flag(w, "raw")?;
    let input = match (text, w.get("script")) {
        (Some(_), Some(s)) if !s.is_null() => return Err(bad("send `input` or `weirdnet.script`, not both")),
        (_, Some(Value::Array(turns))) => {
            if raw {
                return Err(bad("`weirdnet.raw` applies to `input`, not to a script"));
            }
            SpeakInput::Script(turns.iter().map(script_turn).collect::<Result<_, _>>()?)
        }
        (_, Some(s)) if !s.is_null() => return Err(bad("`weirdnet.script` must be an array of {\"speaker\": n, \"text\": \"...\"}")),
        (Some(t), _) if raw => SpeakInput::Raw(t),
        (Some(t), _) => SpeakInput::Text(t),
        (None, _) => return Err(bad("`input` (the text to speak) is required")),
    };
    let mut req = SpeakRequest::with_input(input);
    req.model = model(&o)?;

    let preset = match o.get("voice") {
        None | Some(Value::Null) => None,
        Some(Value::String(v)) => Some(v.clone()),
        Some(Value::Object(v)) => match v.get("id") {
            Some(Value::String(id)) => Some(id.clone()),
            _ => return Err(bad("`voice` must be a preset name or {\"id\": name}")),
        },
        Some(_) => return Err(bad("`voice` must be a preset name or {\"id\": name}")),
    };
    let design = string_of(w, "weirdnet.design", "design")?;
    let ref_audio = string_of(w, "weirdnet.ref_audio", "ref_audio")?;
    let ref_text = string_of(w, "weirdnet.ref_text", "ref_text")?;
    let consent = match w.get("consent") {
        None | Some(Value::Null) => None,
        Some(Value::Bool(b)) => Some(*b),
        Some(_) => return Err(bad("`weirdnet.consent` must be true or false")),
    };
    if [preset.is_some(), design.is_some(), ref_audio.is_some()].iter().filter(|b| **b).count() > 1 {
        return Err(bad("choose one voice: `voice` (a preset), `weirdnet.design` or `weirdnet.ref_audio`"));
    }
    if ref_audio.is_none() && (ref_text.is_some() || consent.is_some()) {
        return Err(bad("`weirdnet.ref_text` and `weirdnet.consent` go with `weirdnet.ref_audio` (a voice to clone)"));
    }
    req.voice = match (preset, design, ref_audio) {
        (Some(name), _, _) => Some(Voice::preset(name)),
        (_, Some(description), _) => Some(Voice::design(description)),
        (_, _, Some(url)) => {
            let (mime, audio) = data_url(&url, "weirdnet.ref_audio")?;
            Some(Voice::clone_from(audio, audio_format_of_mime(&mime), ref_text, consent.unwrap_or(false)))
        }
        _ => None,
    };

    req.instructions = match o.get("instructions") {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) if s.trim().is_empty() => None,
        Some(Value::String(s)) => Some(s.clone()),
        Some(_) => return Err(bad("`instructions` must be a string")),
    };
    req.format = match o.get("response_format") {
        None | Some(Value::Null) => None,
        Some(Value::String(f)) => Some(AudioFormat::parse(f).ok_or_else(|| {
            bad(format!(
                "`response_format` `{f}` is not one this bridge knows; use one of wav, pcm, mp3, opus or flac (the model's formats are in /v1/models)"
            ))
        })?),
        Some(_) => return Err(bad("`response_format` must be a string")),
    };
    req.speed = match f32_of(&o, "speed")? {
        None => None,
        Some(s) if !s.is_finite() || s <= 0.0 || s > 100.0 => return Err(bad("`speed` must be a positive number (1.0 is the model's pace)")),
        Some(s) => Some(((f64::from(s) * 1000.0).round() as u32).max(1)),
    };
    let stream = match o.get("stream_format") {
        None | Some(Value::Null) => false,
        Some(Value::String(f)) if f == "audio" => true,
        Some(Value::String(f)) if f == "sse" => {
            return Err(bad("`stream_format` \"sse\" is not supported; use \"audio\" (raw bytes as they come) or leave it out for the whole file"));
        }
        Some(_) => return Err(bad("`stream_format` must be \"audio\" (or absent)")),
    };
    req.stream = stream;
    req.language = string_of(w, "weirdnet.language", "language")?;
    req.seed = match w.get("seed") {
        None | Some(Value::Null) => None,
        Some(v) => Some(v.as_u64().ok_or_else(|| bad("`weirdnet.seed` must be a whole number"))?),
    };
    req.sample_rate = match w.get("sample_rate") {
        None | Some(Value::Null) => None,
        Some(v) => Some(v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad("`weirdnet.sample_rate` must be a whole number of Hz"))?),
    };
    Ok((req, stream))
}

fn string_of(o: &Map<String, Value>, name: &str, key: &str) -> Result<Option<String>, BadRequest> {
    match o.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) if s.trim().is_empty() => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(bad(format!("`{name}` must be a string"))),
    }
}

fn script_turn(t: &Value) -> Result<ScriptTurn, BadRequest> {
    let speaker = t["speaker"].as_u64().and_then(|n| u8::try_from(n).ok()).ok_or_else(|| bad("each script turn needs a `speaker` from 0 to 255"))?;
    let text = t["text"].as_str().ok_or_else(|| bad("each script turn needs `text`"))?;
    Ok(ScriptTurn::new(speaker, text))
}

/// The MIME type and bytes of a base64 `data:` URL. Anything else (`http(s)://`, `file://`, a
/// non-base64 `data:` URL) is refused: the bridge never fetches a URL.
fn data_url(url: &str, name: &str) -> Result<(String, Vec<u8>), BadRequest> {
    let Some(rest) = url.strip_prefix("data:") else {
        return Err(bad(format!("`{name}` must be a data: URL (data:audio/wav;base64,...); remote and file URLs are never fetched")));
    };
    let Some((head, data)) = rest.split_once(',') else {
        return Err(bad(format!("`{name}` is not a valid data: URL")));
    };
    let mut params = head.split(';');
    let mime = params.next().unwrap_or_default().trim().to_ascii_lowercase();
    if !params.any(|p| p.trim().eq_ignore_ascii_case("base64")) {
        return Err(bad(format!("`{name}` must be a base64 data: URL (data:audio/wav;base64,...)")));
    }
    let bytes = base64::engine::general_purpose::STANDARD.decode(data.trim()).map_err(|e| bad(format!("`{name}` has invalid base64: {e}")))?;
    Ok((mime, bytes))
}

/// The `input_audio`-style format name for an audio MIME type: `audio/wav` is `wav`,
/// `audio/mpeg` is `mp3`, and otherwise the subtype (`audio/flac` is `flac`).
pub(crate) fn audio_format_of_mime(mime: &str) -> String {
    let mime = mime.split(';').next().unwrap_or_default().trim().to_ascii_lowercase();
    let sub = mime.split_once('/').map_or(mime.as_str(), |(_, s)| s);
    match sub {
        "wav" | "x-wav" | "wave" | "vnd.wave" => "wav",
        "mpeg" | "mp3" | "mpeg3" | "x-mpeg-3" | "mpga" => "mp3",
        "x-flac" | "flac" => "flac",
        "ogg" | "opus" => "ogg",
        "x-m4a" | "m4a" | "mp4" | "aac" => "m4a",
        other => other.strip_prefix("x-").unwrap_or(other),
    }
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use weirdnet_agent::Role;
    use weirdnet_agent::remote::infer::v2::Input;

    #[test]
    fn maps_messages_sampling_tools_and_format() {
        let (req, stream) = chat(json!({
            "model": "m", "stream": true, "temperature": 0, "max_tokens": 9, "stop": "\n", "seed": 7, "repetition_penalty": 1.1,
            "messages": [
                {"role": "developer", "content": "be brief"},
                {"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]},
                {"role": "assistant", "content": null, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{\"x\":1}"}}]},
                {"role": "tool", "tool_call_id": "c1", "content": "ok"}
            ],
            "tools": [{"type": "function", "function": {"name": "f", "description": "d", "parameters": {"type": "object"}}}],
            "response_format": {"type": "json_schema", "json_schema": {"name": "r", "schema": {"type": "object"}, "strict": true}},
            "logit_bias": {}
        }))
        .unwrap();
        assert!(stream);
        assert_eq!(req.model.as_deref(), Some("m"));
        let Input::Messages(m) = &req.input else { panic!() };
        assert_eq!(m.iter().map(|m| m.role).collect::<Vec<_>>(), [Role::System, Role::User, Role::Assistant, Role::Tool]);
        assert_eq!(m[1].content, "ab", "text-only parts become a plain string");
        assert_eq!(m[2].tool_calls[0].arguments, json!({"x": 1}));
        assert_eq!(m[3].tool_call_id.as_deref(), Some("c1"));
        assert_eq!((req.sampling.temperature, req.sampling.max_tokens, req.sampling.repeat_penalty), (Some(0.0), Some(9), Some(1.1)));
        assert_eq!((req.sampling.stop.clone(), req.seed), (vec!["\n".to_string()], Some(7)));
        assert_eq!(req.tools[0].input_schema, json!({"type": "object"}));
        assert!(matches!(req.response_format, Some(ResponseFormat::JsonSchema { strict: true, .. })));
    }

    #[test]
    fn images_and_audio_pass_through_as_parts() {
        let png = "data:image/png;base64,iVBORw0KGgo=";
        let body = json!({"messages": [{"role": "user", "content": [
            {"type": "text", "text": "what is this?"},
            {"type": "image_url", "image_url": {"url": png, "detail": "low"}},
            {"type": "image_url", "image_url": png},
            {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}
        ]}]});
        let (r, _) = chat(body).unwrap();
        let m = &r.inline_messages().unwrap()[0];
        let Content::Parts(parts) = &m.content else { panic!("parts expected") };
        assert_eq!(parts.len(), 4);
        assert!(matches!(&parts[1], ContentPart::ImageUrl { image_url } if image_url.url == png && image_url.detail.as_deref() == Some("low")));
        assert_eq!(parts[2], ContentPart::image(png));
        assert_eq!(parts[3], ContentPart::audio("UklGRg==", "wav"));
        assert!(r.needs().vision && r.needs().audio);
    }

    #[test]
    fn refuses_what_it_cannot_carry() {
        assert!(chat(json!({"messages": []})).is_err());
        assert!(chat(json!({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {}}]}]})).is_err());
        let remote = json!({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}]}]});
        assert!(chat(remote).unwrap_err().0.contains("data:image"));
        assert!(chat(json!({"messages": [{"role": "user", "content": [{"type": "file", "file": {}}]}]})).unwrap_err().0.contains("`file`"));
        assert!(chat(json!({"messages": [{"role": "user", "content": "x"}], "temperature": "hot"})).is_err());
        assert!(chat(json!([1])).is_err());
        assert!(embed(json!({"input": "x", "encoding_format": "base64"})).is_err());
        assert!(completion(json!({"prompt": ["a", "b"]})).is_err());
        assert!(completion(json!({"prompt": "a", "n": 2})).is_err());
        assert!(completion(json!({"prompt": "a", "echo": true})).is_err());
        assert!(completion(json!({"prompt": "a", "logprobs": 2})).is_err());
        assert!(completion(json!({"prompt": 3})).is_err());
        assert_eq!(embed(json!({"input": ["a", "b"], "model": "e"})).unwrap().inputs, ["a", "b"]);
    }

    #[test]
    fn continue_final_message_moves_the_last_assistant_message_into_the_prefix() {
        let msgs = json!([{"role": "user", "content": "q"}, {"role": "assistant", "content": "Hel"}]);
        let (req, _) = chat(json!({"messages": msgs, "continue_final_message": true, "add_generation_prompt": false})).unwrap();
        assert_eq!(req.inline_messages().unwrap().len(), 1);
        assert_eq!(req.assistant_prefix.as_ref().map(|p| p.text.as_str()), Some("Hel"));
        // Without the flag a trailing assistant message stays a message.
        let (req, _) = chat(json!({"messages": msgs})).unwrap();
        assert_eq!((req.inline_messages().unwrap().len(), req.assistant_prefix.is_none()), (2, true));
        assert!(chat(json!({"messages": msgs, "continue_final_message": true, "add_generation_prompt": true})).is_err());
        assert!(chat(json!({"messages": [{"role": "user", "content": "q"}], "continue_final_message": true})).is_err());
        assert!(chat(json!({"messages": msgs, "continue_final_message": "yes"})).is_err());
    }
}

#[cfg(test)]
mod media_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn video_parts_take_data_urls_only() {
        let mp4 = "data:video/mp4;base64,AAAAIGZ0eXBpc29t";
        for p in [json!({"type": "video_url", "video_url": {"url": mp4}}), json!({"type": "video_url", "video_url": mp4})] {
            assert_eq!(part(&p), Ok(ContentPart::video(mp4)));
        }
        for url in ["https://example.com/a.mp4", "file:///a.mp4", "data:image/png;base64,AAAA"] {
            let e = part(&json!({"type": "video_url", "video_url": {"url": url}})).unwrap_err();
            assert!(e.0.contains("data:video/"), "{e:?}");
        }
        assert!(part(&json!({"type": "video_url", "video_url": {}})).is_err());
    }

    #[test]
    fn speech_bodies() {
        let (r, stream) =
            speech(json!({"model": "tts", "input": "Hi", "voice": "vivian", "instructions": "warm", "response_format": "pcm", "speed": 1.2}))
                .unwrap();
        assert!(!stream && !r.stream);
        assert_eq!(r.model.as_deref(), Some("tts"));
        assert_eq!(r.input, SpeakInput::Text("Hi".into()));
        assert_eq!(r.voice, Some(Voice::preset("vivian")));
        assert_eq!(r.instructions.as_deref(), Some("warm"));
        assert_eq!(r.format, Some(AudioFormat::Pcm16));
        assert_eq!(r.speed, Some(1200));

        let (r, stream) =
            speech(json!({"input": "Hi", "stream_format": "audio", "weirdnet": {"raw": true, "seed": 3, "language": "en", "sample_rate": 16000}}))
                .unwrap();
        assert!(stream && r.stream);
        assert_eq!(r.input, SpeakInput::Raw("Hi".into()));
        assert_eq!((r.seed, r.language.as_deref(), r.sample_rate), (Some(3), Some("en"), Some(16000)));

        let (r, _) = speech(json!({"weirdnet": {"script": [{"speaker": 0, "text": "a"}, {"speaker": 1, "text": "b"}]}})).unwrap();
        assert_eq!(r.input, SpeakInput::Script(vec![ScriptTurn::new(0, "a"), ScriptTurn::new(1, "b")]));

        let (r, _) =
            speech(json!({"input": "Hi", "weirdnet": {"ref_audio": "data:audio/mpeg;base64,SUQz", "ref_text": "it says", "consent": true}})).unwrap();
        assert_eq!(r.voice, Some(Voice::clone_from(b"ID3".to_vec(), "mp3", Some("it says".into()), true)));
        let (r, _) = speech(json!({"input": "Hi", "weirdnet": {"design": "a calm narrator"}})).unwrap();
        assert_eq!(r.voice, Some(Voice::design("a calm narrator")));

        for (body, needle) in [
            (json!({"input": "Hi", "weirdnet": {"script": []}, "model": "x"}), "not both"),
            (json!({"input": 3}), "`input` must be a string"),
            (json!({"input": "Hi", "voice": 3}), "preset name"),
            (json!({"input": "Hi", "speed": -1}), "positive"),
            (json!({"input": "Hi", "stream_format": "chunks"}), "\"audio\""),
            (json!({"input": "Hi", "weirdnet": "x"}), "`weirdnet` must be an object"),
            (json!({"input": "Hi", "weirdnet": {"ref_audio": "http://x/a.wav"}}), "data: URL"),
            (json!({"weirdnet": {"raw": true, "script": [{"speaker": 0, "text": "a"}]}}), "applies to `input`"),
            (json!({"weirdnet": {"script": [{"speaker": 300, "text": "a"}]}}), "from 0 to 255"),
        ] {
            let e = speech(body.clone()).unwrap_err();
            assert!(e.0.contains(needle), "{body}: {e:?}");
        }
    }

    #[test]
    fn audio_mime_names() {
        for (mime, f) in [
            ("audio/wav", "wav"),
            ("audio/x-wav", "wav"),
            ("audio/mpeg", "mp3"),
            ("audio/flac", "flac"),
            ("audio/ogg; codecs=opus", "ogg"),
            ("audio/webm", "webm"),
        ] {
            assert_eq!(audio_format_of_mime(mime), f, "{mime}");
        }
    }
}

#[cfg(test)]
mod completion_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn maps_a_prompt_and_its_sampling() {
        let (req, stream) = completion(
            json!({"model": "base", "prompt": ["Once"], "max_tokens": 5, "temperature": 0.5, "stop": ["\n"], "seed": 3, "n": 1, "logprobs": null}),
        )
        .unwrap();
        assert!(!stream);
        assert_eq!((req.raw_prompt(), req.model.as_deref()), (Some("Once"), Some("base")));
        assert_eq!((req.sampling.max_tokens, req.sampling.temperature, req.seed), (Some(5), Some(0.5), Some(3)));
        assert_eq!(req.sampling.stop, ["\n"]);
        assert!(req.tools.is_empty());
    }

    #[test]
    fn cache_parameter_and_header() {
        let base = || json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]});
        let with = |v: Value| {
            let mut b = base();
            b["cache"] = v;
            chat(b).map(|(r, _)| r.cache)
        };
        assert_eq!(chat(base()).unwrap().0.cache, CacheMode::Use);
        assert_eq!(with(json!(null)), Ok(CacheMode::Use));
        assert_eq!(with(json!(true)), Ok(CacheMode::Use));
        assert_eq!(with(json!(false)), Ok(CacheMode::Bypass));
        assert_eq!(with(json!("refresh")), Ok(CacheMode::Refresh));
        assert_eq!(with(json!("Bypass")), Ok(CacheMode::Bypass));
        assert!(with(json!("sometimes")).is_err());
        assert!(with(json!(0)).is_err());
        let (r, _) = completion(json!({"prompt": "Once", "cache": false})).unwrap();
        assert_eq!(r.cache, CacheMode::Bypass);

        assert_eq!(chat(base()).unwrap().0.adapter_scale, None);
        let mut b = base();
        b["adapter_scale"] = json!(0.5);
        assert_eq!(chat(b).unwrap().0.adapter_scale, Some(0.5));
        let (r, _) = completion(json!({"prompt": "Once", "adapter_scale": 2})).unwrap();
        assert_eq!(r.adapter_scale, Some(2.0));
        assert!(completion(json!({"prompt": "Once", "adapter_scale": "high"})).is_err());

        assert_eq!(cache_header("off"), Ok(CacheMode::Bypass));
        assert_eq!(cache_header(" REFRESH "), Ok(CacheMode::Refresh));
        assert_eq!(cache_header("use"), Ok(CacheMode::Use));
        assert!(cache_header("hit").is_err());
        assert_eq!(stricter(CacheMode::Use, CacheMode::Refresh), CacheMode::Refresh);
        assert_eq!(stricter(CacheMode::Bypass, CacheMode::Refresh), CacheMode::Bypass);
        assert_eq!(stricter(CacheMode::Refresh, CacheMode::Use), CacheMode::Refresh);
    }
}