inferno-ai 0.10.3

Enterprise AI/ML model runner with automatic updates, real-time monitoring, and multi-interface support
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
use crate::{
    backends::{BackendHandle, BackendType, InferenceParams},
    cli::serve::ServerState,
};
use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::IntoResponse,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use uuid::Uuid;

// OpenAI API compatible types

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionRequest {
    pub model: String,
    pub messages: Vec<ChatMessage>,
    #[serde(default = "default_max_tokens")]
    pub max_tokens: u32,
    #[serde(default = "default_temperature")]
    pub temperature: f32,
    #[serde(default = "default_top_k")]
    pub top_k: u32,
    #[serde(default = "default_top_p")]
    pub top_p: f32,
    #[serde(default)]
    pub n: Option<u32>,
    #[serde(default)]
    pub stream: bool,
    #[serde(default)]
    pub stop: Option<Vec<String>>,
    #[serde(default)]
    pub presence_penalty: Option<f32>,
    #[serde(default)]
    pub frequency_penalty: Option<f32>,
    #[serde(default)]
    pub user: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    pub role: String,
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionResponse {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<ChatChoice>,
    pub usage: Usage,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChoice {
    pub index: u32,
    pub message: ChatMessage,
    pub finish_reason: String,
}

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionRequest {
    pub model: String,
    pub prompt: StringOrArray,
    #[serde(default = "default_max_tokens")]
    pub max_tokens: u32,
    #[serde(default = "default_temperature")]
    pub temperature: f32,
    #[serde(default = "default_top_k")]
    pub top_k: u32,
    #[serde(default = "default_top_p")]
    pub top_p: f32,
    #[serde(default)]
    pub n: Option<u32>,
    #[serde(default)]
    pub stream: bool,
    #[serde(default)]
    pub logprobs: Option<u32>,
    #[serde(default)]
    pub echo: bool,
    #[serde(default)]
    pub stop: Option<Vec<String>>,
    #[serde(default)]
    pub presence_penalty: Option<f32>,
    #[serde(default)]
    pub frequency_penalty: Option<f32>,
    #[serde(default)]
    pub best_of: Option<u32>,
    #[serde(default)]
    pub user: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StringOrArray {
    String(String),
    Array(Vec<String>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionResponse {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<CompletionChoice>,
    pub usage: Usage,
}

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingRequest {
    pub model: String,
    pub input: StringOrArray,
    #[serde(default)]
    pub user: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingResponse {
    pub object: String,
    pub data: Vec<EmbeddingData>,
    pub model: String,
    pub usage: EmbeddingUsage,
}

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

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelObject {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub owned_by: String,
    pub permission: Vec<serde_json::Value>,
    pub root: String,
    pub parent: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelListResponse {
    pub object: String,
    pub data: Vec<ModelObject>,
}

// Streaming response types

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionChunk {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<ChatChunkChoice>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatChunkChoice {
    pub index: u32,
    pub delta: ChatDelta,
    pub finish_reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
}

// Default values

fn default_max_tokens() -> u32 {
    512
}

fn default_temperature() -> f32 {
    0.7
}

fn default_top_k() -> u32 {
    40
}

fn default_top_p() -> f32 {
    0.9
}

// API State

// Note: We use the ServerState from cli::serve module

// API Handlers

pub async fn chat_completions(
    State(state): State<Arc<ServerState>>,
    Json(request): Json<ChatCompletionRequest>,
) -> impl IntoResponse {
    // Convert chat messages to a single prompt
    let prompt = format_chat_messages(&request.messages);

    // Get or load the backend
    let backend = match get_or_load_backend(&state, &request.model).await {
        Ok(backend) => backend,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": {
                        "message": format!("Failed to load model: {}", e),
                        "type": "invalid_request_error",
                        "param": "model",
                        "code": null
                    }
                })),
            )
                .into_response();
        }
    };

    let stream = request.stream;
    let stop_sequences = request.stop.clone().unwrap_or_default();
    let inference_params = InferenceParams {
        max_tokens: request.max_tokens,
        temperature: request.temperature,
        top_k: request.top_k,
        top_p: request.top_p,
        stream: request.stream,
        stop_sequences,
        seed: None,
    };

    if stream {
        // Handle streaming response
        handle_streaming_chat(&request, backend, prompt, inference_params)
            .await
            .into_response()
    } else {
        // Handle non-streaming response
        handle_non_streaming_chat(&request, backend, prompt, inference_params)
            .await
            .into_response()
    }
}

pub async fn completions(
    State(state): State<Arc<ServerState>>,
    Json(request): Json<CompletionRequest>,
) -> impl IntoResponse {
    // Extract prompt
    let prompt = match &request.prompt {
        StringOrArray::String(s) => s.clone(),
        StringOrArray::Array(arr) => arr.join("\n"),
    };

    // Get or load the backend
    let backend = match get_or_load_backend(&state, &request.model).await {
        Ok(backend) => backend,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": {
                        "message": format!("Failed to load model: {}", e),
                        "type": "invalid_request_error",
                        "param": "model",
                        "code": null
                    }
                })),
            )
                .into_response();
        }
    };

    let stream = request.stream;
    let stop_sequences = request.stop.clone().unwrap_or_default();
    let inference_params = InferenceParams {
        max_tokens: request.max_tokens,
        temperature: request.temperature,
        top_k: request.top_k,
        top_p: request.top_p,
        stream: request.stream,
        stop_sequences,
        seed: None,
    };

    if stream {
        // Handle streaming response
        handle_streaming_completion(&request, backend, prompt, inference_params)
            .await
            .into_response()
    } else {
        // Handle non-streaming response
        handle_non_streaming_completion(&request, backend, prompt, inference_params)
            .await
            .into_response()
    }
}

pub async fn embeddings(
    State(state): State<Arc<ServerState>>,
    Json(request): Json<EmbeddingRequest>,
) -> impl IntoResponse {
    // Extract input
    let inputs = match request.input {
        StringOrArray::String(s) => vec![s],
        StringOrArray::Array(arr) => arr,
    };

    // Get or load the backend
    let backend = match get_or_load_backend(&state, &request.model).await {
        Ok(backend) => backend,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": {
                        "message": format!("Failed to load model: {}", e),
                        "type": "invalid_request_error",
                        "param": "model",
                        "code": null
                    }
                })),
            )
                .into_response();
        }
    };

    let mut embeddings_data = Vec::new();
    let mut total_tokens = 0u32;

    for (index, input) in inputs.iter().enumerate() {
        // BackendHandle already provides async methods, no need for explicit locking
        match backend.get_embeddings(input).await {
            Ok(embedding) => {
                embeddings_data.push(EmbeddingData {
                    object: "embedding".to_string(),
                    embedding,
                    index: index as u32,
                });
                total_tokens += estimate_tokens(input);
            }
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(serde_json::json!({
                        "error": {
                            "message": format!("Failed to generate embeddings: {}", e),
                            "type": "internal_error",
                            "param": null,
                            "code": null
                        }
                    })),
                )
                    .into_response();
            }
        }
    }

    let response = EmbeddingResponse {
        object: "list".to_string(),
        data: embeddings_data,
        model: request.model,
        usage: EmbeddingUsage {
            prompt_tokens: total_tokens,
            total_tokens,
        },
    };

    Json(response).into_response()
}

pub async fn list_models(State(state): State<Arc<ServerState>>) -> impl IntoResponse {
    match state.model_manager.list_models().await {
        Ok(models) => {
            let model_objects: Vec<ModelObject> = models
                .into_iter()
                .map(|model| ModelObject {
                    id: model.name.clone(),
                    object: "model".to_string(),
                    created: model.modified.timestamp(),
                    owned_by: "inferno".to_string(),
                    permission: vec![],
                    root: model.name,
                    parent: None,
                })
                .collect();

            let response = ModelListResponse {
                object: "list".to_string(),
                data: model_objects,
            };

            Json(response).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "error": {
                    "message": format!("Failed to list models: {}", e),
                    "type": "internal_error",
                    "param": null,
                    "code": null
                }
            })),
        )
            .into_response(),
    }
}

// Helper functions

async fn get_or_load_backend(
    state: &Arc<ServerState>,
    model_name: &str,
) -> anyhow::Result<BackendHandle> {
    // If distributed inference is available, we don't need a direct backend
    // This function should not be called when using distributed inference
    if state.distributed.is_some() {
        return Err(anyhow::anyhow!(
            "Cannot load direct backend when using distributed inference"
        ));
    }

    // Check if we have a loaded backend and if it matches the requested model
    if let Some(ref loaded_model) = state.loaded_model {
        if loaded_model == model_name {
            if let Some(ref backend) = state.backend {
                return Ok(backend.clone());
            }
        }
    }

    // For now, if the model doesn't match, we load a new one
    // In a more sophisticated implementation, we'd cache multiple backends
    let model_info = state.model_manager.resolve_model(model_name).await?;
    let backend_type = BackendType::from_model_path(&model_info.path).ok_or_else(|| {
        anyhow::anyhow!(
            "No suitable backend found for model: {}",
            model_info.path.display()
        )
    })?;
    let backend_handle = BackendHandle::new_shared(backend_type, &state.config.backend_config)?;
    backend_handle.load_model(&model_info).await?;

    Ok(backend_handle)
}

fn format_chat_messages(messages: &[ChatMessage]) -> String {
    messages
        .iter()
        .map(|msg| format!("{}: {}", msg.role, msg.content))
        .collect::<Vec<_>>()
        .join("\n")
}

fn estimate_tokens(text: &str) -> u32 {
    (text.len() as f32 / 4.0).ceil() as u32
}

async fn handle_non_streaming_chat(
    request: &ChatCompletionRequest,
    backend: BackendHandle,
    prompt: String,
    params: InferenceParams,
) -> impl IntoResponse {
    // BackendHandle already provides async methods, no need for explicit locking

    match backend.infer(&prompt, &params).await {
        Ok(output) => {
            let response = ChatCompletionResponse {
                id: format!("chatcmpl-{}", Uuid::new_v4()),
                object: "chat.completion".to_string(),
                created: chrono::Utc::now().timestamp(),
                model: request.model.clone(),
                choices: vec![ChatChoice {
                    index: 0,
                    message: ChatMessage {
                        role: "assistant".to_string(),
                        content: output.clone(),
                        name: None,
                    },
                    finish_reason: "stop".to_string(),
                }],
                usage: Usage {
                    prompt_tokens: estimate_tokens(&prompt),
                    completion_tokens: estimate_tokens(&output),
                    total_tokens: estimate_tokens(&prompt) + estimate_tokens(&output),
                },
            };

            Json(response).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "error": {
                    "message": format!("Inference failed: {}", e),
                    "type": "internal_error",
                    "param": null,
                    "code": null
                }
            })),
        )
            .into_response(),
    }
}

async fn handle_streaming_chat(
    request: &ChatCompletionRequest,
    backend: BackendHandle,
    prompt: String,
    params: InferenceParams,
) -> impl IntoResponse {
    use axum::response::sse::{Event, Sse};
    use futures::stream::StreamExt;

    let model = request.model.clone();
    let request_id = format!("chatcmpl-{}", Uuid::new_v4());

    let stream = async_stream::stream! {
        // BackendHandle already provides async methods, no need for explicit locking

        match backend.infer_stream(&prompt, &params).await {
            Ok(mut token_stream) => {
                // Send initial chunk with role
                let initial_chunk = ChatCompletionChunk {
                    id: request_id.clone(),
                    object: "chat.completion.chunk".to_string(),
                    created: chrono::Utc::now().timestamp(),
                    model: model.clone(),
                    choices: vec![ChatChunkChoice {
                        index: 0,
                        delta: ChatDelta {
                            role: Some("assistant".to_string()),
                            content: None,
                        },
                        finish_reason: None,
                    }],
                };

                yield Ok::<axum::response::sse::Event, axum::Error>(Event::default().data(serde_json::to_string(&initial_chunk).unwrap()));

                // Stream tokens
                while let Some(token_result) = token_stream.next().await {
                    match token_result {
                        Ok(token) => {
                            let chunk = ChatCompletionChunk {
                                id: request_id.clone(),
                                object: "chat.completion.chunk".to_string(),
                                created: chrono::Utc::now().timestamp(),
                                model: model.clone(),
                                choices: vec![ChatChunkChoice {
                                    index: 0,
                                    delta: ChatDelta {
                                        role: None,
                                        content: Some(token),
                                    },
                                    finish_reason: None,
                                }],
                            };

                            yield Ok(Event::default().data(serde_json::to_string(&chunk).unwrap()));
                        }
                        Err(e) => {
                            tracing::error!("Stream error: {}", e);
                            break;
                        }
                    }
                }

                // Send final chunk
                let final_chunk = ChatCompletionChunk {
                    id: request_id.clone(),
                    object: "chat.completion.chunk".to_string(),
                    created: chrono::Utc::now().timestamp(),
                    model: model.clone(),
                    choices: vec![ChatChunkChoice {
                        index: 0,
                        delta: ChatDelta {
                            role: None,
                            content: None,
                        },
                        finish_reason: Some("stop".to_string()),
                    }],
                };

                yield Ok(Event::default().data(serde_json::to_string(&final_chunk).unwrap()));
                yield Ok(Event::default().data("[DONE]"));
            }
            Err(e) => {
                let error_msg = serde_json::json!({
                    "error": {
                        "message": format!("Stream failed: {}", e),
                        "type": "internal_error"
                    }
                });
                yield Ok(Event::default().data(serde_json::to_string(&error_msg).unwrap()));
            }
        }
    };

    Sse::new(stream)
        .keep_alive(axum::response::sse::KeepAlive::default())
        .into_response()
}

async fn handle_non_streaming_completion(
    request: &CompletionRequest,
    backend: BackendHandle,
    prompt: String,
    params: InferenceParams,
) -> impl IntoResponse {
    // BackendHandle already provides async methods, no need for explicit locking

    match backend.infer(&prompt, &params).await {
        Ok(output) => {
            let response = CompletionResponse {
                id: format!("cmpl-{}", Uuid::new_v4()),
                object: "text_completion".to_string(),
                created: chrono::Utc::now().timestamp(),
                model: request.model.clone(),
                choices: vec![CompletionChoice {
                    text: output.clone(),
                    index: 0,
                    logprobs: None,
                    finish_reason: "stop".to_string(),
                }],
                usage: Usage {
                    prompt_tokens: estimate_tokens(&prompt),
                    completion_tokens: estimate_tokens(&output),
                    total_tokens: estimate_tokens(&prompt) + estimate_tokens(&output),
                },
            };

            Json(response).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "error": {
                    "message": format!("Inference failed: {}", e),
                    "type": "internal_error",
                    "param": null,
                    "code": null
                }
            })),
        )
            .into_response(),
    }
}

async fn handle_streaming_completion(
    request: &CompletionRequest,
    backend: BackendHandle,
    prompt: String,
    params: InferenceParams,
) -> impl IntoResponse {
    use axum::response::sse::{Event, Sse};
    use futures::stream::StreamExt;

    let model = request.model.clone();
    let request_id = format!("cmpl-{}", Uuid::new_v4());

    let stream = async_stream::stream! {
        // BackendHandle already provides async methods, no need for explicit locking

        match backend.infer_stream(&prompt, &params).await {
            Ok(mut token_stream) => {
                while let Some(token_result) = token_stream.next().await {
                    match token_result {
                        Ok(token) => {
                            let response = CompletionResponse {
                                id: request_id.clone(),
                                object: "text_completion".to_string(),
                                created: chrono::Utc::now().timestamp(),
                                model: model.clone(),
                                choices: vec![CompletionChoice {
                                    text: token,
                                    index: 0,
                                    logprobs: None,
                                    finish_reason: "".to_string(),
                                }],
                                usage: Usage {
                                    prompt_tokens: 0,
                                    completion_tokens: 1,
                                    total_tokens: 1,
                                },
                            };

                            yield Ok::<axum::response::sse::Event, axum::Error>(Event::default().data(serde_json::to_string(&response).unwrap()));
                        }
                        Err(e) => {
                            tracing::error!("Stream error: {}", e);
                            break;
                        }
                    }
                }

                yield Ok(Event::default().data("[DONE]"));
            }
            Err(e) => {
                let error_msg = serde_json::json!({
                    "error": {
                        "message": format!("Stream failed: {}", e),
                        "type": "internal_error"
                    }
                });
                yield Ok(Event::default().data(serde_json::to_string(&error_msg).unwrap()));
            }
        }
    };

    Sse::new(stream)
        .keep_alive(axum::response::sse::KeepAlive::default())
        .into_response()
}