ferrum-server 0.12.1

OpenAI-compatible HTTP API server for Ferrum inference
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
//! OpenAI API compatibility types
//!
//! This module defines types that match the OpenAI API specification
//! for chat completions, completions, and model management.

use serde::{de, Deserialize, Serialize};
use std::collections::HashMap;

/// Chat completions request (OpenAI compatible)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionsRequest {
    /// Model to use for completion
    pub model: String,

    /// List of messages
    pub messages: Vec<ChatMessage>,

    /// Maximum number of tokens to generate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,

    /// Newer OpenAI chat field replacing `max_tokens` for completion budget.
    /// When both are supplied, Ferrum uses this value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<u32>,

    /// Temperature for sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// Top-p for nucleus sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,

    /// vLLM-compatible top-k sampling extension. Values `-1` and `0`
    /// disable top-k filtering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<i64>,

    /// vLLM-compatible minimum probability sampling extension. A value of
    /// `0` disables minimum-probability filtering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_p: Option<f32>,

    /// vLLM-compatible repetition penalty extension.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repetition_penalty: Option<f32>,

    /// Number of completions to generate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,

    /// Whether to stream responses
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,

    /// vLLM-compatible extension for benchmark/throughput workloads.
    /// When true, Ferrum ignores model EOS tokens and stops only on the
    /// requested token budget or explicit user stop sequences.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ignore_eos: Option<bool>,

    /// Stop sequences
    #[serde(default, deserialize_with = "deserialize_stop_sequences")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,

    /// Presence penalty
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,

    /// Frequency penalty
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,

    /// Logit bias
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logit_bias: Option<HashMap<String, f32>>,

    /// Return log probabilities. Ferrum rejects this until implemented so
    /// clients get an explicit OpenAI-style error instead of silent ignore.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<bool>,

    /// Number of top log probabilities to return.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_logprobs: Option<u32>,

    /// User identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,

    /// Random seed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<u64>,

    /// Response format constraint (e.g., `{"type": "json_object"}`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<OpenAiResponseFormat>,

    /// Standard reasoning control. Omission/null retains model and server
    /// defaults; explicit `none` requests disabled reasoning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<ferrum_types::ReasoningEffort>,

    /// OpenAI tool definitions. Function tools are parsed, carried through
    /// structured request data, and can shape model-emitted tool-call JSON.
    /// Tool execution itself stays caller-owned.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<ChatTool>>,

    /// OpenAI tool selection policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,

    /// Streaming response options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_options: Option<StreamOptions>,

    /// Legacy OpenAI functions compatibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub functions: Option<Vec<ChatFunction>>,

    /// Legacy OpenAI function-call selector.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call: Option<FunctionCallChoice>,

    /// Ferrum extension metadata. Used for opt-in product features such as
    /// `metadata.ferrum_session_id` when callers prefer body metadata over
    /// the `X-Ferrum-Session` header.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, serde_json::Value>>,

    /// vLLM-compatible chat-template variables. Ferrum forwards supported
    /// values to the model-provided chat template; templates that do not read
    /// a variable are unaffected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_template_kwargs: Option<HashMap<String, serde_json::Value>>,
}

/// OpenAI streaming options.
#[derive(Debug, Clone, Serialize)]
pub struct StreamOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_usage: Option<bool>,
}

impl<'de> Deserialize<'de> for StreamOptions {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Object {
            #[serde(default)]
            include_usage: Option<bool>,
        }

        let value = serde_json::Value::deserialize(deserializer)?;
        if !value.is_object() {
            return Err(de::Error::custom("stream_options must be a JSON object"));
        }
        let parsed = serde_json::from_value::<Object>(value).map_err(de::Error::custom)?;
        Ok(Self {
            include_usage: parsed.include_usage,
        })
    }
}

/// Tool definition in OpenAI chat-completion requests.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatTool {
    #[serde(rename = "type")]
    pub tool_type: String,
    pub function: ChatFunction,
}

/// Function schema for `tools[].function` and legacy `functions[]`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatFunction {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameters: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strict: Option<bool>,
}

/// OpenAI `tool_choice` accepts either a simple mode string or a specific
/// function-tool selector object.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolChoice {
    Mode(String),
    Function {
        #[serde(rename = "type")]
        tool_type: String,
        function: ToolChoiceFunction,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolChoiceFunction {
    pub name: String,
}

/// Legacy `function_call` accepts a simple mode string or a named function.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FunctionCallChoice {
    Mode(String),
    Function { name: String },
}

/// OpenAI-compatible response format specifier.
///
/// Mirrors OpenAI's `response_format` field on `/v1/chat/completions`:
///   - `{"type": "text"}`         — default, no constraint
///   - `{"type": "json_object"}`  — output must be valid JSON
///   - `{"type": "json_schema", "json_schema": {"name":..., "strict":true,
///      "schema": {...}}}` — output must conform to the inline JSON Schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAiResponseFormat {
    #[serde(rename = "type")]
    pub format_type: String,
    /// Present only when `format_type == "json_schema"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub json_schema: Option<OpenAiJsonSchema>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAiJsonSchema {
    /// Optional name for the schema (ignored internally, kept for round-trip).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The actual JSON Schema. Stored as raw JSON value so callers can pass
    /// any valid schema object; we re-serialise when forwarding to the
    /// guided-decoding pipeline. Optional at deserialization time so the
    /// HTTP layer can return an OpenAI-shaped `param` error for missing
    /// schemas instead of Axum's generic JSON rejection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<serde_json::Value>,
    /// OpenAI's `strict` flag. When true, Ferrum rejects schemas outside the
    /// currently supported guided-decoding subset instead of silently falling
    /// back to best-effort JSON.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strict: Option<bool>,
}

/// Chat message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "ChatMessageWire")]
pub struct ChatMessage {
    /// Message role
    pub role: MessageRole,

    /// Message content. Accepts either a plain string or the OpenAI
    /// "typed parts" array form (`[{"type":"text","text":"..."}]`)
    /// — both shapes deserialize into a single String. Non-text parts
    /// fail deserialization so multimodal input is rejected instead of
    /// silently dropped.
    #[serde(default)]
    #[serde(deserialize_with = "deserialize_message_content")]
    pub content: String,

    /// vLLM-compatible parsed reasoning text. When Ferrum parses
    /// `<think>...</think>`, `content` contains only the final visible
    /// answer and this field contains the reasoning block text.
    /// Historical input also accepts `reasoning_content`. A string in
    /// `reasoning` takes precedence, including an empty string; missing or
    /// null `reasoning` falls back to the alias. Output uses only `reasoning`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<String>,

    /// Message name (for function calls)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Assistant tool calls.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ChatToolCall>>,

    /// Tool response correlation id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,

    /// Legacy assistant function call.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call: Option<ChatFunctionCall>,
}

/// Deserialization wire shape. Both reasoning field names are parsed separately
/// so receiving both is not a duplicate-field error; conversion below leaves
/// one canonical value for the rest of Ferrum.
#[derive(Deserialize)]
struct ChatMessageWire {
    role: MessageRole,
    #[serde(default, deserialize_with = "deserialize_message_content")]
    content: String,
    #[serde(default)]
    reasoning: serde_json::Value,
    #[serde(default)]
    reasoning_content: serde_json::Value,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    tool_calls: Option<Vec<ChatToolCall>>,
    #[serde(default)]
    tool_call_id: Option<String>,
    #[serde(default)]
    function_call: Option<ChatFunctionCall>,
}

impl TryFrom<ChatMessageWire> for ChatMessage {
    type Error = String;

    fn try_from(message: ChatMessageWire) -> Result<Self, Self::Error> {
        let reasoning = match message.reasoning {
            serde_json::Value::String(reasoning) => Some(reasoning),
            serde_json::Value::Null => match message.reasoning_content {
                serde_json::Value::String(reasoning) => Some(reasoning),
                serde_json::Value::Null => None,
                _ => return Err("reasoning_content must be a string or null".to_string()),
            },
            _ => return Err("reasoning must be a string or null".to_string()),
        };

        Ok(Self {
            role: message.role,
            content: message.content,
            reasoning,
            name: message.name,
            tool_calls: message.tool_calls,
            tool_call_id: message.tool_call_id,
            function_call: message.function_call,
        })
    }
}

/// Assistant tool call in OpenAI responses and historical conversation input.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatToolCall {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<u32>,
    pub id: String,
    #[serde(rename = "type")]
    pub tool_type: String,
    pub function: ChatFunctionCall,
}

/// Function call payload. OpenAI serializes arguments as a JSON string.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatFunctionCall {
    pub name: String,
    pub arguments: String,
}

/// Deserialize chat message content from either a plain string or the
/// OpenAI typed-parts array form. Real OpenAI clients (and `vllm bench
/// serve`'s openai-chat backend) send `content` as
/// `[{"type":"text","text":"..."}]` even for plain text; refusing that
/// breaks every standard client.
fn deserialize_message_content<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = serde_json::Value::deserialize(deserializer)?;
    match value {
        serde_json::Value::Null => Ok(String::new()),
        serde_json::Value::String(s) => Ok(s),
        serde_json::Value::Array(parts) => {
            let mut text_parts = Vec::with_capacity(parts.len());
            for part in parts {
                let ty = part
                    .get("type")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| de::Error::custom("message content part missing type"))?;
                if ty != "text" {
                    return Err(de::Error::custom(format!(
                        "unsupported message content part type `{ty}`"
                    )));
                }
                if let Some(text) = part.get("text").and_then(|v| v.as_str()) {
                    text_parts.push(text.to_string());
                }
            }
            Ok(text_parts.join("\n"))
        }
        _ => Err(de::Error::custom(
            "message content must be a string, null, or an array of text parts",
        )),
    }
}

fn deserialize_stop_sequences<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    match value {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::String(stop)) => Ok(Some(vec![stop])),
        Some(serde_json::Value::Array(values)) => {
            let mut stops = Vec::with_capacity(values.len());
            for value in values {
                match value {
                    serde_json::Value::String(stop) => stops.push(stop),
                    _ => {
                        return Err(de::Error::custom(
                            "stop must be a string or an array of strings",
                        ))
                    }
                }
            }
            Ok(Some(stops))
        }
        _ => Err(de::Error::custom(
            "stop must be a string or an array of strings",
        )),
    }
}

/// Message roles
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageRole {
    System,
    User,
    Assistant,
    Function,
    Tool,
}

/// Whether an assistant message is intermediate commentary or the terminal
/// answer for a Responses API turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum AssistantMessagePhase {
    Commentary,
    FinalAnswer,
}

/// Chat completions response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionsResponse {
    /// Response ID
    pub id: String,

    /// Object type
    pub object: String,

    /// Creation timestamp
    pub created: u64,

    /// Model used
    pub model: String,

    /// Choices array
    pub choices: Vec<ChatChoice>,

    /// Token usage information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
}

/// Chat choice
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChoice {
    /// Choice index
    pub index: u32,

    /// Message content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<ChatMessage>,

    /// Delta for streaming
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta: Option<ChatMessage>,

    /// Finish reason
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_reason: Option<String>,
}

/// Legacy completions request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionsRequest {
    /// Model to use
    pub model: String,

    /// Prompt text. OpenAI's legacy completions endpoint also accepts prompt
    /// arrays, but Ferrum currently supports only a single string and rejects
    /// other shapes with `param=prompt`.
    #[serde(default)]
    pub prompt: CompletionPrompt,

    /// Maximum tokens
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,

    /// Temperature
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,

    /// Top-p
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,

    /// Number of completions to generate. Ferrum currently supports only
    /// `n=1` and rejects larger values explicitly.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,

    /// Stream responses
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,

    /// Stop sequences
    #[serde(default, deserialize_with = "deserialize_stop_sequences")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Vec<String>>,

    /// Legacy completions log probabilities. Explicitly rejected until
    /// implemented so clients don't mistake a silent ignore for support.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<u32>,

    /// Logit bias.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logit_bias: Option<HashMap<String, f32>>,
}

/// Legacy completions prompt. Kept as a parsed enum so the HTTP layer can
/// return an OpenAI-shaped field error instead of a generic JSON rejection.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CompletionPrompt {
    Text(String),
    Unsupported(serde_json::Value),
}

impl Default for CompletionPrompt {
    fn default() -> Self {
        Self::Unsupported(serde_json::Value::Null)
    }
}

impl CompletionPrompt {
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(text) => Some(text),
            Self::Unsupported(_) => None,
        }
    }
}

/// Completions response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionsResponse {
    pub id: String,
    pub object: String,
    pub created: u64,
    pub model: String,
    pub choices: Vec<CompletionChoice>,
    pub usage: Option<Usage>,
}

/// Completion choice
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionChoice {
    pub text: String,
    pub index: u32,
    pub finish_reason: Option<String>,
}

/// Token usage information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

/// Model list response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelListResponse {
    pub object: String,
    pub data: Vec<ModelInfo>,
}

/// Model information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
    pub id: String,
    pub object: String,
    pub created: u64,
    pub owned_by: String,
    pub modalities: Vec<String>,
    /// Effective input-plus-output capacity reported by the loaded LLM engine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_model_len: Option<usize>,
    /// Optional model-declared controls; omission means support is unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ModelReasoningCapabilities>,
    pub permission: Vec<ModelPermission>,
    pub root: Option<String>,
    pub parent: Option<String>,
}

/// Optional extension for clients to discover actual reasoning controls.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelReasoningCapabilities {
    /// Only populated from a declaration, including an explicitly empty set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supported_efforts: Option<Vec<ferrum_types::ReasoningEffort>>,
    /// Present only when template probing establishes an enable/disable control.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thinking: Option<ModelThinkingCapability>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelThinkingCapability {
    /// Effective service default, including an explicit server override.
    pub default_enabled: bool,
}

/// Model permission
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelPermission {
    pub id: String,
    pub object: String,
    pub created: u64,
    pub allow_create_engine: bool,
    pub allow_sampling: bool,
    pub allow_logprobs: bool,
    pub allow_search_indices: bool,
    pub allow_view: bool,
    pub allow_fine_tuning: bool,
    pub organization: String,
    pub group: Option<String>,
    pub is_blocking: bool,
}

// ======================== Embeddings API ========================

/// Embeddings request (OpenAI-compatible, extended for images)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingsRequest {
    /// Model identifier
    pub model: String,

    /// Input to embed — text string, array of strings, or objects with text/image fields
    pub input: EmbeddingInput,

    /// Encoding format: "float" (default) or "base64"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding_format: Option<String>,
}

/// Polymorphic embedding input.
/// Supports: single string, array of strings, single object, array of objects.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EmbeddingInput {
    /// Single text string (OpenAI standard)
    Single(String),
    /// Batch of text strings (OpenAI standard)
    Batch(Vec<String>),
    /// Single multimodal item (Jina-style extension)
    SingleObject(EmbeddingItem),
    /// Batch of multimodal items
    BatchObjects(Vec<EmbeddingItem>),
}

/// A single embedding input item — text or image.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingItem {
    /// Text to embed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Image: file path or base64 data URI
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
}

/// Embeddings response (OpenAI-compatible)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingsResponse {
    pub object: String,
    pub data: Vec<EmbeddingData>,
    pub model: String,
    pub usage: EmbeddingUsage,
}

/// Single embedding result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingData {
    pub object: String,
    pub embedding: Vec<f32>,
    pub index: usize,
}

/// Token usage for embeddings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingUsage {
    pub prompt_tokens: u32,
    pub total_tokens: u32,
}

// ======================== Audio Transcription API ========================

/// Transcription response (OpenAI-compatible)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranscriptionResponse {
    pub text: String,
}

// ======================== Error types ========================

/// OpenAI API error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAiError {
    pub error: OpenAiErrorDetail,
}

/// OpenAI error detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAiErrorDetail {
    pub message: String,
    #[serde(rename = "type")]
    pub error_type: String,
    pub param: Option<String>,
    pub code: Option<String>,
}

/// OpenAI error types
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum OpenAiErrorType {
    InvalidRequestError,
    AuthenticationError,
    PermissionError,
    NotFoundError,
    RateLimitError,
    InternalServerError,
    ServiceUnavailableError,
}

/// Server-sent event for streaming
#[derive(Debug, Clone)]
pub struct SseEvent {
    pub event: Option<String>,
    pub data: String,
    pub id: Option<String>,
    pub retry: Option<u32>,
}

impl SseEvent {
    pub fn data(data: String) -> Self {
        Self {
            event: None,
            data,
            id: None,
            retry: None,
        }
    }

    pub fn json(value: &serde_json::Value) -> Result<Self, serde_json::Error> {
        Ok(Self::data(serde_json::to_string(value)?))
    }

    pub fn to_string(&self) -> String {
        let mut result = String::new();

        if let Some(event) = &self.event {
            result.push_str(&format!("event: {}\n", event));
        }

        if let Some(id) = &self.id {
            result.push_str(&format!("id: {}\n", id));
        }

        if let Some(retry) = self.retry {
            result.push_str(&format!("retry: {}\n", retry));
        }

        result.push_str(&format!("data: {}\n\n", self.data));
        result
    }
}

/// TTS speech request (OpenAI compatible /v1/audio/speech)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeechRequest {
    /// Model name (e.g., "qwen3-tts", "tts-1")
    #[serde(default = "default_tts_model")]
    pub model: String,

    /// Text to synthesize
    pub input: String,

    /// Voice preset (ignored for now — uses default speaker)
    #[serde(default = "default_voice")]
    pub voice: String,

    /// Response format: "wav", "pcm" (default: "wav")
    #[serde(default = "default_audio_format")]
    pub response_format: String,

    /// Language hint: "auto", "chinese", "english"
    #[serde(default = "default_language")]
    pub language: String,

    /// Enable streaming (chunked transfer)
    #[serde(default)]
    pub stream: bool,
}

fn default_tts_model() -> String {
    "qwen3-tts".to_string()
}
fn default_voice() -> String {
    "default".to_string()
}
fn default_audio_format() -> String {
    "wav".to_string()
}
fn default_language() -> String {
    "auto".to_string()
}

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

    fn chat_request_with_assistant_fields(fields: &str) -> String {
        format!(r#"{{"model":"test","messages":[{{"role":"assistant","content":null{fields}}}]}}"#)
    }

    #[test]
    fn chat_request_normalizes_reasoning_content_at_the_wire_boundary() {
        let cases = [
            ("missing", "", None),
            ("compatibility null", r#", "reasoning_content": null"#, None),
            (
                "compatibility empty",
                r#", "reasoning_content": """#,
                Some(""),
            ),
            (
                "compatibility text",
                r#", "reasoning_content": "compatibility""#,
                Some("compatibility"),
            ),
            (
                "canonical text",
                r#", "reasoning": "canonical""#,
                Some("canonical"),
            ),
            (
                "compatibility then canonical",
                r#", "reasoning_content": "compatibility", "reasoning": "canonical""#,
                Some("canonical"),
            ),
            (
                "canonical then compatibility",
                r#", "reasoning": "canonical", "reasoning_content": "compatibility""#,
                Some("canonical"),
            ),
            (
                "canonical empty wins",
                r#", "reasoning": "", "reasoning_content": "compatibility""#,
                Some(""),
            ),
            (
                "canonical null falls back",
                r#", "reasoning": null, "reasoning_content": "compatibility""#,
                Some("compatibility"),
            ),
            (
                "canonical text ignores invalid compatibility",
                r#", "reasoning_content": 7, "reasoning": "canonical""#,
                Some("canonical"),
            ),
            (
                "canonical empty ignores invalid compatibility",
                r#", "reasoning": "", "reasoning_content": {"unexpected": true}"#,
                Some(""),
            ),
        ];

        for (name, fields, expected) in cases {
            let request: ChatCompletionsRequest =
                serde_json::from_str(&chat_request_with_assistant_fields(fields))
                    .unwrap_or_else(|error| panic!("{name}: {error}"));
            assert_eq!(request.messages[0].reasoning.as_deref(), expected, "{name}");

            let normalized = serde_json::to_value(request).expect("normalized request JSON");
            let message = &normalized["messages"][0];
            assert!(message.get("reasoning_content").is_none(), "{name}");
            match expected {
                Some(expected) => assert_eq!(message["reasoning"], expected, "{name}"),
                None => assert!(message.get("reasoning").is_none(), "{name}"),
            }
        }
    }

    #[test]
    fn chat_request_rejects_non_string_reasoning_fields() {
        for (name, fields) in [
            ("compatibility", r#", "reasoning_content": 7"#),
            (
                "canonical is not masked by compatibility",
                r#", "reasoning": 7, "reasoning_content": "compatibility""#,
            ),
            (
                "canonical null validates compatibility",
                r#", "reasoning": null, "reasoning_content": 7"#,
            ),
        ] {
            let error = serde_json::from_str::<ChatCompletionsRequest>(
                &chat_request_with_assistant_fields(fields),
            )
            .expect_err(name);
            assert!(error.to_string().contains("string"), "{name}: {error}");
        }
    }
}