mojentic 3.0.2

An LLM integration framework for Rust
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! Gateway for [oMLX](https://github.com/jundot/omlx), an LLM server for Apple Silicon.
//!
//! oMLX speaks the OpenAI chat completions protocol, but this gateway does not
//! treat it as OpenAI. It sends every setting as configured, with no per-model
//! parameter adaptation and no OpenAI model registry. It maps the reasoning
//! trace oMLX reports (`reasoning_content`) to the response's `thinking`, and
//! it sends embeddings in one request with no client-side chunking.
//!
//! It reuses the OpenAI message adapter and the OpenAI stream parsers.

use crate::error::{MojenticError, Result};
use crate::llm::gateway::{
    CompletionConfig, LlmGateway, ModelContextWindow, ReasoningEffort, ResponseFormat, StreamChunk,
};
use crate::llm::gateways::openai::{add_response_format, openai_response_evidence};
use crate::llm::gateways::openai_legacy_stream::{
    legacy_body_stream, read_legacy_line, LegacyLine, OpenAiLegacyParser,
};
use crate::llm::gateways::openai_messages_adapter::{
    adapt_messages_to_openai_with_reasoning, convert_tool_calls,
};
use crate::llm::gateways::openai_stream_events::OpenAiEventParser;
use crate::llm::models::{LlmGatewayResponse, LlmMessage, ResponseEvidence};
use crate::llm::stream_events::{
    drive_event_stream, FrameParser, StreamEvent, StreamEventError, StreamEventStream,
};
use crate::llm::stream_timing::{system_clock, StreamClock, StreamTiming};
use crate::llm::tools::LlmTool;
use crate::llm::transport::Client;
use crate::llm::transport::RequestBuilder;
use async_trait::async_trait;
use futures::stream::Stream;
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use reqwest::{Method, Response};
use serde_json::Value;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, info, warn};

/// Response metadata key for the `Warning` header oMLX sends when it could
/// not enforce a requested structured output format.
///
/// When oMLX cannot compile a grammar for `json_object` or `json_schema`, it
/// falls back to instructions in the prompt and says so in a `Warning`
/// header. The gateway records the header value here and logs a warning. It
/// does not retry or fail: callers validate content as they would anyway.
pub const RESPONSE_FORMAT_WARNING: &str = "response_format_warning";

/// Host used when neither the configuration nor `OMLX_HOST` sets one.
const DEFAULT_HOST: &str = "http://localhost:8000";

/// Timeout used when `OMLX_TIMEOUT` is unset or unreadable: ten minutes.
const DEFAULT_TIMEOUT: Duration = Duration::from_millis(600_000);

/// The `model` oMLX reports on keep-alive stream frames.
const KEEPALIVE_MODEL: &str = "keepalive";

/// Characters left as they are in a model id path segment (RFC 3986 unreserved).
const PATH_SEGMENT: &AsciiSet =
    &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');

/// Configuration for connecting to an oMLX server.
///
/// [`Default`] reads the environment, so explicit fields take precedence over
/// the environment, which takes precedence over the built-in defaults:
///
/// | Field | Environment | Default |
/// | ----- | ----------- | ------- |
/// | `host` | `OMLX_HOST` | `http://localhost:8000` |
/// | `api_key` | `OMLX_API_KEY` | none |
/// | `timeout` | `OMLX_TIMEOUT`, in milliseconds | 10 minutes |
///
/// ```no_run
/// use mojentic::llm::gateways::{OmlxConfig, OmlxGateway};
///
/// let gateway = OmlxGateway::with_config(OmlxConfig {
///     host: "http://studio.local:8000".to_string(),
///     ..Default::default()
/// });
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct OmlxConfig {
    /// Server address without the `/v1` suffix. The gateway adds `/v1`.
    pub host: String,
    /// Sent as `Authorization: Bearer <key>`. No header is sent without one.
    pub api_key: Option<String>,
    /// Bounds non-streaming requests, including model load.
    /// Streams are cancelled by dropping them; a whole-response timeout
    /// would cut off long replies.
    /// `None` means no timeout.
    pub timeout: Option<Duration>,
}

/// Shows whether a key is set, never the key itself.
impl std::fmt::Debug for OmlxConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OmlxConfig")
            .field("host", &self.host)
            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
            .field("timeout", &self.timeout)
            .finish()
    }
}

impl Default for OmlxConfig {
    fn default() -> Self {
        Self {
            host: std::env::var("OMLX_HOST").unwrap_or_else(|_| DEFAULT_HOST.to_string()),
            api_key: std::env::var("OMLX_API_KEY").ok().filter(|key| !key.is_empty()),
            timeout: Some(timeout_from_env(std::env::var("OMLX_TIMEOUT").ok())),
        }
    }
}

/// Read an `OMLX_TIMEOUT` value in milliseconds, falling back to the default.
fn timeout_from_env(value: Option<String>) -> Duration {
    let Some(value) = value else {
        return DEFAULT_TIMEOUT;
    };
    match value.trim().parse::<u64>() {
        Ok(millis) => Duration::from_millis(millis),
        Err(_) => {
            warn!(value = %value, "OMLX_TIMEOUT is not a number of milliseconds, using the default");
            DEFAULT_TIMEOUT
        }
    }
}

/// Gateway for a local [oMLX](https://github.com/jundot/omlx) server.
///
/// Supports chat, structured output, tool calls, both streaming APIs,
/// embeddings, and loading and unloading models.
///
/// # Thinking
///
/// oMLX reports a model's reasoning trace as `reasoning_content`. The gateway
/// maps it to [`LlmGatewayResponse::thinking`] and, in the legacy streaming
/// API, to [`StreamChunk::Thinking`]. The events API has no thinking event
/// and yields none.
///
/// `reasoning_effort` of low, medium or high is sent unchanged to the model's
/// chat template as `"low"`, `"medium"` or `"high"`. Its effect depends on the
/// model. [`ReasoningEffort::Disabled`] sends `enable_thinking: false` and no
/// `reasoning_effort`, which turns thinking off. Leaving it unset keeps the
/// model's default; Qwen 3 models think by default.
///
/// # Truncation
///
/// When `max_tokens` ends generation during thinking, a non-streaming response
/// carries the partial reasoning in `content` and no thinking, with a finish
/// reason of `length`. A streaming response keeps it as thinking. The gateway
/// maps the fields as oMLX reports them. When the finish reason in
/// [`LlmGatewayResponse::evidence`] is not `stop`, `content` is not an answer.
///
/// # Example
///
/// ```no_run
/// use mojentic::llm::gateways::OmlxGateway;
/// use mojentic::llm::{LlmBroker, LlmMessage};
/// use std::sync::Arc;
///
/// # async fn run() -> mojentic::Result<()> {
/// let broker = LlmBroker::new("Qwen3.8-27B-MLX-8bit", Arc::new(OmlxGateway::new()), None);
/// let reply = broker.generate(&[LlmMessage::user("Hello")], None, None, None).await?;
/// # Ok(())
/// # }
/// ```
pub struct OmlxGateway {
    clock: Arc<dyn StreamClock>,
    client: Client,
    config: OmlxConfig,
}

impl OmlxGateway {
    /// Replace HTTP execution for all requests, including opt-in recovery.
    pub fn with_transport(
        mut self,
        transport: Arc<dyn crate::llm::transport::HttpTransport>,
    ) -> Self {
        self.client = self.client.with_transport(transport);
        self
    }

    /// Select a monotonic measurement clock. The default uses std::time::Instant.
    pub fn with_stream_clock(mut self, clock: Arc<dyn StreamClock>) -> Self {
        self.clock = clock;
        self
    }

    /// Opt into per-request recovery without changing legacy entrypoints.
    pub fn with_recovery(
        self,
        policy: crate::llm::recovery::RecoveryPolicy,
    ) -> Result<crate::llm::recovery::RecoveryGateway<Self>> {
        crate::llm::recovery::RecoveryGateway::new(self, policy)
    }

    /// Create a gateway configured from the environment. See [`OmlxConfig`].
    pub fn new() -> Self {
        Self::with_config(OmlxConfig::default())
    }

    /// Create a gateway with explicit configuration.
    pub fn with_config(config: OmlxConfig) -> Self {
        Self {
            client: Client::new(),
            clock: system_clock(),
            config,
        }
    }

    /// Create a gateway for `host`, reading the key and timeout from the environment.
    pub fn with_host(host: impl Into<String>) -> Self {
        Self::with_config(OmlxConfig {
            host: host.into(),
            ..Default::default()
        })
    }

    /// Load a model into memory ahead of its first request.
    ///
    /// Blocks until the model is in memory. A chat request loads its model on
    /// its own, so this is only for warming up. oMLX downloads models only
    /// through its admin dashboard; there is no pull operation.
    ///
    /// # Errors
    ///
    /// [`MojenticError::GatewayError`] with the HTTP status and response body
    /// when oMLX rejects the request, or [`MojenticError::HttpError`] when the
    /// request fails.
    pub async fn load_model(&self, model: &str) -> Result<()> {
        info!(model, "Loading oMLX model");
        self.model_action(model, "load").await
    }

    /// Unload a model from memory.
    ///
    /// # Errors
    ///
    /// [`MojenticError::GatewayError`] with the HTTP status and response body
    /// when oMLX rejects the request. Unloading a model that is not loaded is
    /// a 400 `invalid_request_error`. [`MojenticError::HttpError`] when the
    /// request fails.
    pub async fn unload_model(&self, model: &str) -> Result<()> {
        info!(model, "Unloading oMLX model");
        self.model_action(model, "unload").await
    }

    async fn model_action(&self, model: &str, action: &str) -> Result<()> {
        if model.trim().is_empty() {
            return Err(MojenticError::InvalidArgument(
                "oMLX model id must not be blank".to_string(),
            ));
        }
        let model = utf8_percent_encode(model, PATH_SEGMENT);
        let response = self
            .request(Method::POST, &format!("/models/{model}/{action}"), false)
            .send()
            .await?;
        success(response).await?;
        Ok(())
    }

    /// A request to `/v1{path}` with authorization and timeout applied.
    fn request(&self, method: Method, path: &str, streaming: bool) -> RequestBuilder {
        let url = format!("{}/v1{}", self.config.host.trim_end_matches('/'), path);
        let mut request = self.client.request(method, url);
        if let Some(key) = self.config.api_key.as_ref().filter(|key| !key.trim().is_empty()) {
            request = request.bearer_auth(key);
        }
        if !streaming {
            if let Some(timeout) = self.config.timeout {
                request = request.timeout(timeout);
            }
        }
        request
    }

    fn chat_request(&self, body: &Value) -> RequestBuilder {
        self.request(Method::POST, "/chat/completions", body["stream"] == true)
            .json(body)
    }

    /// Send a non-streaming chat request and read the response.
    async fn chat(&self, body: &Value, structured: bool) -> Result<ChatReply> {
        let response = success(self.chat_request(body).send().await?).await?;
        let warning = structured.then(|| format_warning(&response)).flatten();
        let body: Value = response.json().await?;
        let mut evidence = openai_response_evidence(&body);
        if let Some(warning) = warning {
            warn!(warning = %warning, "oMLX did not enforce the requested response format");
            evidence
                .metadata
                .insert(RESPONSE_FORMAT_WARNING.to_string(), Value::String(warning));
        }
        Ok(ChatReply { body, evidence })
    }
}

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

/// A chat completion body and the evidence read from it and its headers.
struct ChatReply {
    body: Value,
    evidence: ResponseEvidence,
}

impl ChatReply {
    fn message(&self) -> &Value {
        &self.body["choices"][0]["message"]
    }

    fn text(&self, field: &str) -> Option<String> {
        self.message()[field].as_str().map(String::from)
    }
}

/// The response when its status is a success, otherwise a gateway error
/// carrying the status and the body as oMLX sent it.
async fn success(response: Response) -> Result<Response> {
    let status = response.status();
    if status.is_success() {
        return Ok(response);
    }
    let body = response.text().await.unwrap_or_default();
    Err(MojenticError::GatewayError(format!("oMLX API error: {status} - {body}")))
}

/// Every `Warning` header value, joined with `, `.
fn format_warning(response: &Response) -> Option<String> {
    format_warning_headers(response.headers())
}

pub(crate) fn format_warning_headers(headers: &reqwest::header::HeaderMap) -> Option<String> {
    let values: Vec<_> = headers
        .get_all(reqwest::header::WARNING)
        .iter()
        .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned())
        .collect();
    (!values.is_empty()).then(|| values.join(", "))
}

/// Whether the configuration asks for structured output.
fn requests_structured_output(config: &CompletionConfig) -> bool {
    matches!(config.response_format, Some(ResponseFormat::JsonObject { .. }))
}

/// Build a chat completion body from the configuration, unadapted.
///
/// `num_ctx` and `num_predict` are not sent: oMLX sets context length per model.
fn chat_body(model: &str, messages: &[LlmMessage], config: &CompletionConfig) -> Result<Value> {
    config.validate_reasoning()?;
    let mut body = serde_json::json!({
        "model": model,
        "messages": adapt_messages_to_openai_with_reasoning(messages, true)?,
    });
    if let Some(temperature) = config.temperature {
        body["temperature"] = serde_json::json!(temperature);
    }
    if let Some(max_tokens) = config.max_tokens {
        body["max_tokens"] = serde_json::json!(max_tokens);
    }
    if config.preserve_reasoning {
        body["chat_template_kwargs"] = serde_json::json!({"preserve_thinking": true});
    }
    if let Some(top_p) = config.top_p {
        body["top_p"] = serde_json::json!(top_p);
    }
    if let Some(top_k) = config.top_k {
        body["top_k"] = serde_json::json!(top_k);
    }
    match config.reasoning_effort {
        // oMLX turns thinking off with its own flag, not an effort level.
        Some(ReasoningEffort::Disabled) => body["enable_thinking"] = Value::Bool(false),
        Some(ReasoningEffort::Enabled) => body["enable_thinking"] = Value::Bool(true),
        Some(effort) => body["reasoning_effort"] = serde_json::to_value(effort)?,
        None => {}
    }
    add_response_format(&mut body, config);
    Ok(body)
}

fn tool_definitions(tools: &[Box<dyn LlmTool>]) -> Result<Value> {
    let descriptors: Vec<_> = tools.iter().map(|tool| tool.descriptor()).collect();
    Ok(serde_json::to_value(descriptors)?)
}

/// Whether a stream frame is one of oMLX's keep-alive frames.
fn is_keepalive(frame: &Value) -> bool {
    frame["model"] == KEEPALIVE_MODEL
}

/// Whether an SSE line is a `data:` line carrying a keep-alive frame.
fn is_keepalive_line(line: &str) -> bool {
    // Most lines are not keep-alives; skip the JSON parse for them.
    if !line.contains(KEEPALIVE_MODEL) {
        return false;
    }
    line.strip_prefix("data:")
        .and_then(|data| serde_json::from_str::<Value>(data.trim_start()).ok())
        .is_some_and(|frame| is_keepalive(&frame))
}

/// The OpenAI event parser, behind a filter that drops keep-alive frames so
/// their `keepalive` model never enters the completion evidence.
#[derive(Default)]
struct OmlxEventParser {
    inner: OpenAiEventParser,
}

impl FrameParser for OmlxEventParser {
    fn parse_line(&mut self, line: &str) -> Vec<StreamEvent> {
        if is_keepalive_line(line) {
            return Vec::new();
        }
        self.inner.parse_line(line)
    }

    fn partial_evidence(&self) -> Option<ResponseEvidence> {
        self.inner.partial_evidence()
    }
}

/// Legacy stream chunks for one line: keep-alives dropped, reasoning as thinking.
fn legacy_chunks(parser: &mut OpenAiLegacyParser, line: &str) -> Vec<StreamChunk> {
    match read_legacy_line(line) {
        Some(LegacyLine::Done) => parser.done(),
        Some(LegacyLine::Frame(frame)) if is_keepalive(&frame) => Vec::new(),
        Some(LegacyLine::Frame(frame)) => {
            let reasoning = frame["choices"][0]["delta"]["reasoning_content"]
                .as_str()
                .filter(|text| !text.is_empty())
                .map(|text| StreamChunk::Thinking(text.to_string()));
            reasoning.into_iter().chain(parser.frame(&frame)).collect()
        }
        None => Vec::new(),
    }
}

#[async_trait]
impl LlmGateway for OmlxGateway {
    fn stream_clock(&self) -> Arc<dyn StreamClock> {
        self.clock.clone()
    }

    async fn get_model_context_window(&self, model: &str) -> Result<Option<ModelContextWindow>> {
        let response = success(self.request(Method::GET, "/models", false).send().await?).await?;
        let body: Value = response.json().await?;
        let models = body["data"]
            .as_array()
            .ok_or_else(|| MojenticError::GatewayError("Invalid response format".into()))?;
        let Some(entry) = models.iter().find(|entry| entry["id"].as_str() == Some(model)) else {
            return Ok(None);
        };
        entry
            .get("max_model_len")
            .map(|value| ModelContextWindow::advertised(value, "max_model_len".into()))
            .transpose()
    }

    async fn complete(
        &self,
        model: &str,
        messages: &[LlmMessage],
        tools: Option<&[Box<dyn LlmTool>]>,
        config: &CompletionConfig,
    ) -> Result<LlmGatewayResponse> {
        info!("Delegating to oMLX for completion");
        debug!("Model: {}, Message count: {}", model, messages.len());

        let mut body = chat_body(model, messages, config)?;
        if let Some(tools) = tools {
            body["tools"] = tool_definitions(tools)?;
        }

        let reply = self.chat(&body, requests_structured_output(config)).await?;
        let tool_calls =
            reply.message()["tool_calls"].as_array().map(|calls| convert_tool_calls(calls));

        Ok(LlmGatewayResponse {
            content: reply.text("content"),
            object: None,
            tool_calls: tool_calls.unwrap_or_default(),
            thinking: reply.text("reasoning_content"),
            evidence: reply.evidence,
        })
    }

    async fn complete_json(
        &self,
        model: &str,
        messages: &[LlmMessage],
        schema: Value,
        config: &CompletionConfig,
    ) -> Result<Value> {
        self.complete_json_response(model, messages, schema, config)
            .await?
            .object
            .ok_or_else(|| MojenticError::GatewayError("No content in response".to_string()))
    }

    async fn complete_json_response(
        &self,
        model: &str,
        messages: &[LlmMessage],
        schema: Value,
        config: &CompletionConfig,
    ) -> Result<LlmGatewayResponse<Value>> {
        info!("Requesting structured output from oMLX");

        let config = CompletionConfig {
            response_format: Some(ResponseFormat::JsonObject {
                schema: Some(schema),
            }),
            ..config.clone()
        };
        let body = chat_body(model, messages, &config)?;

        let reply = self.chat(&body, true).await?;
        let content = reply
            .text("content")
            .ok_or_else(|| MojenticError::GatewayError("No content in response".to_string()))?;
        let object: Value = serde_json::from_str(&content)?;

        Ok(LlmGatewayResponse {
            content: Some(content),
            object: Some(object),
            tool_calls: Vec::new(),
            thinking: reply.text("reasoning_content"),
            evidence: reply.evidence,
        })
    }

    async fn get_available_models(&self) -> Result<Vec<String>> {
        debug!("Fetching available oMLX models");

        let response = success(self.request(Method::GET, "/models", false).send().await?).await?;
        let body: Value = response.json().await?;

        let mut models: Vec<String> = body["data"]
            .as_array()
            .ok_or_else(|| MojenticError::GatewayError("Invalid response format".to_string()))?
            .iter()
            .filter_map(|model| model["id"].as_str().map(String::from))
            .collect();
        models.sort();
        Ok(models)
    }

    /// Embed `text` in one request.
    ///
    /// oMLX has no standard embedding model, so `model` is required. There is
    /// no client-side chunking; the server applies its model's input limit.
    ///
    /// # Errors
    ///
    /// [`MojenticError::InvalidArgument`] without sending a request when
    /// `model` is missing or blank. [`MojenticError::GatewayError`] with the
    /// status and body when oMLX rejects the request, for example a 400 for a
    /// model that is not an embedding model.
    async fn calculate_embeddings(&self, text: &str, model: Option<&str>) -> Result<Vec<f32>> {
        let model = model.filter(|model| !model.trim().is_empty()).ok_or_else(|| {
            MojenticError::InvalidArgument(
                "oMLX embeddings need a model: oMLX has no default embedding model".to_string(),
            )
        })?;
        debug!("Calculating embeddings with model: {}", model);

        let body = serde_json::json!({"model": model, "input": text});
        let response =
            success(self.request(Method::POST, "/embeddings", false).json(&body).send().await?)
                .await?;
        let body: Value = response.json().await?;

        let embedding = body["data"][0]["embedding"]
            .as_array()
            .ok_or_else(|| MojenticError::GatewayError("Invalid embeddings response".to_string()))?
            .iter()
            .filter_map(|value| value.as_f64().map(|number| number as f32))
            .collect();
        Ok(embedding)
    }

    fn complete_stream<'a>(
        &'a self,
        model: &'a str,
        messages: &'a [LlmMessage],
        tools: Option<&'a [Box<dyn LlmTool>]>,
        config: &'a CompletionConfig,
    ) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
        let timing = StreamTiming::new(self.stream_clock());
        let measure = timing.clone();
        let source: Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> =
            Box::pin(async_stream::stream! {
                info!("Starting oMLX streaming completion");
                debug!("Model: {}, Message count: {}", model, messages.len());

                let mut body = match chat_body(model, messages, config) {
                    Ok(body) => body,
                    Err(e) => {
                        yield Err(e);
                        return;
                    }
                };
                body["stream"] = serde_json::json!(true);
                if let Some(tools) = tools {
                    match tool_definitions(tools) {
                        Ok(definitions) => body["tools"] = definitions,
                        Err(e) => {
                            yield Err(e);
                            return;
                        }
                    }
                }

                measure.dispatch();
                let response = match self.chat_request(&body).send().await {
                    Ok(response) => response,
                    Err(e) => {
                        yield Err(e.into());
                        return;
                    }
                };
                let response = match success(response).await {
                    Ok(response) => response,
                    Err(e) => {
                        yield Err(e);
                        return;
                    }
                };

                let mut parser = OpenAiLegacyParser::default();
                let chunks = legacy_body_stream(response.bytes_stream(), move |line: &str| {
                    measure.observe_line(line);
                    legacy_chunks(&mut parser, line)
                });
                for await chunk in chunks {
                    yield chunk;
                }
            });
        timing.legacy(source, "omlx")
    }

    fn complete_stream_events<'a>(
        &'a self,
        model: &'a str,
        messages: &'a [LlmMessage],
        config: &'a CompletionConfig,
    ) -> std::result::Result<StreamEventStream<'a>, StreamEventError> {
        info!("Starting oMLX stream events");
        let mut body =
            chat_body(model, messages, config).map_err(StreamEventError::RequestFailed)?;
        body["stream"] = serde_json::json!(true);
        body["stream_options"] = serde_json::json!({"include_usage": true});

        Ok(drive_event_stream(
            self.chat_request(&body),
            OmlxEventParser::default(),
            self.stream_clock(),
            "omlx",
        ))
    }
}

impl crate::llm::recovery::RecoveryProvider for OmlxGateway {
    fn recovery_transport(&self) -> Option<Arc<dyn crate::llm::transport::HttpTransport>> {
        self.client.transport()
    }

    fn recovery_provider(&self) -> crate::llm::recovery::Provider {
        crate::llm::recovery::Provider::Omlx
    }
    fn prepare_recovery(
        &self,
        model: &str,
        messages: &[LlmMessage],
        tools: Option<&[Box<dyn LlmTool>]>,
        config: &CompletionConfig,
        schema: Option<Value>,
        stream: bool,
    ) -> Result<reqwest::Request> {
        let mut config = config.clone();
        if let Some(schema) = schema {
            config.response_format = Some(ResponseFormat::JsonObject {
                schema: Some(schema),
            });
        }
        let mut body = chat_body(model, messages, &config)?;
        body["stream"] = Value::Bool(stream);
        if let Some(tools) = tools {
            body["tools"] = tool_definitions(tools)?;
        }
        let mut request = self.chat_request(&body).build()?;
        *request.timeout_mut() = None;
        Ok(request)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::stream::StreamExt;

    #[tokio::test]
    async fn blank_model_actions_fail_before_a_request() {
        let gateway = OmlxGateway::with_host("http://127.0.0.1:1");
        for model in ["", "  ", "\t"] {
            assert!(matches!(
                gateway.load_model(model).await,
                Err(MojenticError::InvalidArgument(_))
            ));
            assert!(matches!(
                gateway.unload_model(model).await,
                Err(MojenticError::InvalidArgument(_))
            ));
        }
    }

    #[tokio::test]
    async fn event_stream_is_not_cut_off_by_the_whole_response_timeout() {
        use crate::llm::stream_events::testing::endless_stream_fixture;
        let (fixture, closed) =
            endless_stream_fixture("data: {\"choices\":[{\"delta\":{\"content\":\"first\"}}]}\n\n")
                .await;
        let url = fixture.url();
        let gateway = OmlxGateway::with_config(OmlxConfig {
            host: url,
            api_key: None,
            timeout: Some(Duration::from_millis(50)),
        });
        let gateway = gateway.with_transport(fixture.transport());
        let messages = [LlmMessage::user("Hi")];
        let config = CompletionConfig::default();
        let mut stream = gateway.complete_stream_events("m", &messages, &config).unwrap();
        assert!(matches!(stream.next().await, Some(crate::llm::StreamEvent::Content(_))));

        assert!(futures::FutureExt::now_or_never(stream.next()).is_none());
        drop(stream);
        closed.await.expect("body released on drop");
    }

    #[tokio::test]
    async fn legacy_stream_outlives_the_timeout_and_cancels_on_drop() {
        use crate::llm::stream_events::testing::endless_stream_fixture;
        let (fixture, closed) =
            endless_stream_fixture("data: {\"choices\":[{\"delta\":{\"content\":\"first\"}}]}\n\n")
                .await;
        let url = fixture.url();
        let gateway = OmlxGateway::with_config(OmlxConfig {
            host: url,
            api_key: None,
            timeout: Some(Duration::from_millis(50)),
        });
        let gateway = gateway.with_transport(fixture.transport());
        let messages = [LlmMessage::user("Hi")];
        let config = CompletionConfig::default();
        let mut stream = gateway.complete_stream("m", &messages, None, &config);
        assert!(matches!(stream.next().await, Some(Ok(StreamChunk::Content(_)))));

        assert!(futures::FutureExt::now_or_never(stream.next()).is_none());
        drop(stream);
        closed.await.expect("body released on drop");
    }

    #[tokio::test]
    async fn legacy_stream_keeps_a_character_split_across_network_chunks() {
        use crate::llm::stream_events::testing::{
            split_body_fixture, split_inside_first_multibyte_char,
        };
        let body = concat!(
            "data: {\"model\":\"m\",\"choices\":[{\"index\":0,\"delta\":{\"reasoning_content\":\"\u{1f914} hmm\"}}]}\n\n",
            "data: {\"model\":\"m\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"caf\u{e9}\"}}]}\n\n",
            "data: [DONE]\n\n",
        );
        let fixture = split_body_fixture(split_inside_first_multibyte_char(body)).await;
        let url = fixture.url();
        let gateway = OmlxGateway::with_config(OmlxConfig {
            host: url,
            api_key: None,
            timeout: None,
        });
        let gateway = gateway.with_transport(fixture.transport());
        let messages = vec![LlmMessage::user("Hi")];
        let config = CompletionConfig::default();

        let items: Vec<_> = gateway.complete_stream("m", &messages, None, &config).collect().await;

        assert!(
            matches!(
                items.as_slice(),
                [Ok(StreamChunk::Thinking(thinking)), Ok(StreamChunk::Content(content)), Ok(StreamChunk::Metrics(_))]
                    if thinking == "\u{1f914} hmm" && content == "caf\u{e9}"
            ),
            "{items:?}"
        );
    }

    #[test]
    fn debug_output_hides_the_api_key() {
        let config = OmlxConfig {
            host: "http://localhost:8000".into(),
            api_key: Some("secret-key".into()),
            timeout: None,
        };

        let shown = format!("{config:?}");

        assert!(!shown.contains("secret-key"), "{shown}");
        assert!(shown.contains("<redacted>"), "{shown}");
    }

    #[test]
    fn timeout_env_is_milliseconds_with_a_ten_minute_default() {
        assert_eq!(timeout_from_env(None), Duration::from_secs(600));
        assert_eq!(timeout_from_env(Some("2500".into())), Duration::from_millis(2500));
        assert_eq!(timeout_from_env(Some(" 1000 ".into())), Duration::from_secs(1));
        assert_eq!(timeout_from_env(Some("ten".into())), Duration::from_secs(600));
        assert_eq!(timeout_from_env(Some("-5".into())), Duration::from_secs(600));
    }

    #[test]
    fn a_keepalive_line_has_exactly_the_keepalive_model() {
        assert!(is_keepalive_line(r#"data: {"model":"keepalive","choices":[]}"#));
        assert!(is_keepalive_line(r#"data:{"model":"keepalive","choices":[]}"#));
        assert!(!is_keepalive_line(r#"data: {"model":"keepalive-7b","choices":[]}"#));
        assert!(!is_keepalive_line(
            r#"data: {"model":"m","choices":[{"delta":{"content":"keepalive"}}]}"#
        ));
        assert!(!is_keepalive_line(": keepalive"));
        assert!(!is_keepalive_line("data: [DONE]"));
    }

    #[test]
    fn the_event_parser_ignores_keepalive_evidence() {
        let mut parser = OmlxEventParser::default();

        let events = parser.parse_line(
            r#"data: {"id":"c","created":0,"model":"keepalive","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}"#,
        );

        assert!(events.is_empty());
        assert_eq!(parser.partial_evidence(), None);
    }

    #[test]
    fn reasoning_comes_before_content_in_one_delta() {
        let mut parser = OpenAiLegacyParser::default();

        let chunks = legacy_chunks(
            &mut parser,
            r#"data: {"model":"m","choices":[{"delta":{"reasoning_content":"why","content":"what"}}]}"#,
        );

        assert!(matches!(
            chunks.as_slice(),
            [StreamChunk::Thinking(why), StreamChunk::Content(what)] if why == "why" && what == "what"
        ));
    }

    #[test]
    fn only_json_formats_request_structured_output() {
        let with = |format| CompletionConfig {
            response_format: format,
            ..Default::default()
        };

        assert!(!requests_structured_output(&with(None)));
        assert!(!requests_structured_output(&with(Some(ResponseFormat::Text))));
        assert!(requests_structured_output(&with(Some(ResponseFormat::JsonObject {
            schema: None
        }))));
    }
}