litert-lm 0.2.1

Rust wrapper for LiteRT-LM providing MCP and OpenAI-compatible interfaces with auto-download, process pools, and streaming
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
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::sse::{Event, Sse},
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use futures_util::stream::StreamExt;
use serde::{Deserialize, Serialize};
use std::convert::Infallible;
use std::sync::Arc;
use tower_http::trace::TraceLayer;

use crate::process::ProcessPool;

use crate::manager::LitManager;

#[derive(Clone)]
pub struct AppState {
    pub pool: Arc<ProcessPool>,
    pub manager: Arc<LitManager>,
}

/// Check if this is a DSpy-rs formatted prompt by looking for multiple specific patterns
fn is_dspy_request(prompt: &str) -> bool {
    // DSpy-rs has very specific patterns - we need at least 3 of these to be confident:
    // 1. "Your input fields are:" or "Your output fields are:"
    // 2. Field markers like "[[ ## field_name ## ]]"
    // 3. "All interactions will be structured"
    // 4. "Given the fields" instruction pattern

    let has_field_declaration = prompt.contains("Your input fields are:")
        || prompt.contains("Your output fields are:");
    let has_field_markers = prompt.contains("[[ ## ") && prompt.contains(" ## ]]");
    let has_structure_instruction = prompt.contains("All interactions will be structured");
    let has_completion_marker = prompt.contains("[[ ## completed ## ]]")
        || prompt.contains("ending with the marker for `completed`");

    // Require at least 3 of these patterns to be present
    let pattern_count = [
        has_field_declaration,
        has_field_markers,
        has_structure_instruction,
        has_completion_marker,
    ].iter().filter(|&&x| x).count();

    pattern_count >= 3
}

/// Extract output field names from DSpy-rs formatted prompt
fn extract_dspy_output_fields(prompt: &str) -> Vec<String> {
    let mut fields = Vec::new();

    // Look for "Your output fields are:" section
    if let Some(output_section) = prompt.split("Your output fields are:").nth(1) {
        // Extract field names from lines like "1. `field_name` (String)"
        for line in output_section.lines() {
            if let Some(field_start) = line.find('`') {
                if let Some(field_end) = line[field_start + 1..].find('`') {
                    let field_name = &line[field_start + 1..field_start + 1 + field_end];
                    fields.push(field_name.to_string());
                }
            }
            // Stop at the next section
            if line.contains("All interactions will be structured") {
                break;
            }
        }
    }

    fields
}

/// Extract the actual user question from DSpy-rs formatted prompt
fn extract_dspy_question(prompt: &str) -> Option<String> {
    // Find the user's actual question after the format template
    // Look for pattern: user: [[ ## <field> ## ]]\n<actual_question>
    if let Some(user_section) = prompt.split("user: [[ ## ").nth(1) {
        if let Some(question_start) = user_section.find("## ]]\n") {
            let question = &user_section[question_start + 6..];
            return Some(question.trim().to_string());
        }
    }
    None
}

/// Format LLM response with DSpy-rs field markers
fn format_dspy_response(llm_output: &str, output_fields: &[String]) -> String {
    let cleaned_output = llm_output.trim();

    // For now, put the entire response in the first output field
    // This is a simple heuristic - could be improved with better parsing
    let mut formatted = String::new();

    if let Some(first_field) = output_fields.first() {
        formatted.push_str(&format!("[[ ## {} ## ]]\n", first_field));
        formatted.push_str(cleaned_output);
        formatted.push_str("\n\n");
    }

    // Add completion marker
    formatted.push_str("[[ ## completed ## ]]\n");

    formatted
}

#[derive(Debug, Deserialize)]
pub struct ChatCompletionRequest {
    pub model: String,
    pub messages: Vec<Message>,
    #[serde(default)]
    pub stream: bool,
    #[serde(default = "default_max_tokens")]
    #[allow(dead_code)]
    pub max_tokens: u32,
    #[serde(default = "default_temperature")]
    #[allow(dead_code)]
    pub temperature: f32,
}

fn default_max_tokens() -> u32 {
    2048
}

fn default_temperature() -> f32 {
    0.7
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum ContentPart {
    Text { text: String },
    ImageUrl { image_url: serde_json::Value },
}

#[derive(Debug, Serialize, Clone)]
pub struct Message {
    pub role: String,
    #[serde(serialize_with = "serialize_content")]
    pub content: MessageContent,
}

#[derive(Debug, Clone)]
pub enum MessageContent {
    String(String),
    Parts(Vec<ContentPart>),
}

fn serialize_content<S>(content: &MessageContent, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    match content {
        MessageContent::String(s) => serializer.serialize_str(s),
        MessageContent::Parts(parts) => parts.serialize(serializer),
    }
}

impl<'de> Deserialize<'de> for Message {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct MessageHelper {
            role: String,
            content: serde_json::Value,
        }

        let helper = MessageHelper::deserialize(deserializer)?;
        let content = match helper.content {
            serde_json::Value::String(s) => MessageContent::String(s),
            serde_json::Value::Array(arr) => {
                let parts: Vec<ContentPart> = serde_json::from_value(serde_json::Value::Array(arr))
                    .map_err(serde::de::Error::custom)?;
                MessageContent::Parts(parts)
            }
            _ => return Err(serde::de::Error::custom("content must be string or array")),
        };

        Ok(Message {
            role: helper.role,
            content,
        })
    }
}

impl Message {
    pub fn content_as_string(&self) -> String {
        match &self.content {
            MessageContent::String(s) => s.clone(),
            MessageContent::Parts(parts) => {
                parts
                    .iter()
                    .filter_map(|part| match part {
                        ContentPart::Text { text } => Some(text.clone()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            }
        }
    }
}

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

#[derive(Debug, Serialize)]
pub struct Choice {
    pub index: u32,
    pub message: Message,
    pub finish_reason: String,
}

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

#[derive(Debug, Serialize)]
pub struct ChatCompletionChunk {
    pub id: String,
    pub object: &'static str,
    pub created: u64,
    pub model: String,
    pub choices: Vec<ChoiceChunk>,
}

#[derive(Debug, Serialize)]
pub struct ChoiceChunk {
    pub index: u32,
    pub delta: Delta,
    pub finish_reason: Option<String>,
}

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

pub async fn chat_completions(
    State(state): State<AppState>,
    Json(req): Json<ChatCompletionRequest>,
) -> Response {
    tracing::info!(
        model = %req.model,
        message_count = req.messages.len(),
        stream = req.stream,
        "Received chat completion request"
    );

    // Build prompt from messages
    let mut prompt = req
        .messages
        .iter()
        .map(|m| format!("{}: {}", m.role, m.content_as_string()))
        .collect::<Vec<_>>()
        .join("\n");

    tracing::debug!(
        model = %req.model,
        prompt_length = prompt.len(),
        "Built prompt from messages"
    );
    tracing::trace!(prompt = %prompt, "Full prompt text");

    // Check if streaming is requested
    if req.stream {
        tracing::debug!("Routing to streaming handler");
        return chat_completions_stream(state, req, prompt).await;
    }

    // Detect if this is a DSpy-rs structured output request
    let is_dspy = is_dspy_request(&prompt);
    let output_fields = if is_dspy {
        tracing::debug!("Detected DSpy-rs structured output request");
        // Extract output field names from the system message
        let fields = extract_dspy_output_fields(&prompt);
        tracing::debug!(fields = ?fields, "Extracted DSpy-rs output fields");

        // For small models, simplify by extracting just the actual question
        if let Some(question) = extract_dspy_question(&prompt) {
            tracing::debug!(original_length = prompt.len(), simplified_length = question.len(), "Simplified DSpy prompt for small model");
            prompt = question;
            tracing::trace!(simplified_prompt = %prompt, "Using simplified question");
        } else {
            tracing::warn!("Failed to extract question from DSpy prompt, using original");
        }

        fields
    } else {
        vec![]
    };

    // Non-streaming response
    tracing::debug!("Sending prompt to process pool");
    let mut response_text = match state.pool.send_prompt(&prompt).await {
        Ok(text) => {
            tracing::info!(
                response_length = text.len(),
                "Received completion from LLM"
            );
            tracing::trace!(response = %text, "LLM response text");
            text
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to get completion from process pool");
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };

    // If DSpy-rs request, format the response with field markers
    if is_dspy && !output_fields.is_empty() {
        tracing::debug!(field_count = output_fields.len(), "Formatting response for DSpy-rs");
        response_text = format_dspy_response(&response_text, &output_fields);
        tracing::trace!(formatted_response = %response_text, "DSpy-rs formatted response");
    }

    let response = ChatCompletionResponse {
        id: format!("chatcmpl-{}", uuid::Uuid::new_v4()),
        object: "chat.completion".to_string(),
        created: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        model: req.model.clone(),
        choices: vec![Choice {
            index: 0,
            message: Message {
                role: "assistant".to_string(),
                content: MessageContent::String(response_text),
            },
            finish_reason: "stop".to_string(),
        }],
        usage: Usage {
            prompt_tokens: 0,
            completion_tokens: 0,
            total_tokens: 0,
        },
    };

    Json(response).into_response()
}

async fn chat_completions_stream(
    state: AppState,
    req: ChatCompletionRequest,
    mut prompt: String,
) -> Response {
    let model_name = req.model.clone();
    let completion_id = format!("chatcmpl-{}", uuid::Uuid::new_v4());

    // Detect if this is a DSpy-rs structured output request and simplify for streaming
    let is_dspy = is_dspy_request(&prompt);
    let output_fields = if is_dspy {
        tracing::debug!("Detected DSpy-rs structured output request in streaming mode");
        let fields = extract_dspy_output_fields(&prompt);
        tracing::debug!(fields = ?fields, "Extracted DSpy-rs output fields");

        // Simplify by extracting just the actual question
        if let Some(question) = extract_dspy_question(&prompt) {
            tracing::debug!(original_length = prompt.len(), simplified_length = question.len(), "Simplified DSpy prompt for streaming");
            prompt = question;
            tracing::trace!(simplified_prompt = %prompt, "Using simplified question for streaming");
        } else {
            tracing::warn!("Failed to extract question from DSpy prompt in streaming mode, using original");
        }

        fields
    } else {
        vec![]
    };

    tracing::info!(
        completion_id = %completion_id,
        model = %model_name,
        is_dspy = is_dspy,
        "Starting streaming completion"
    );

    // Get a process from the pool and stream
    let stream = match state.pool.get_process().await {
        Ok(process) => {
            tracing::debug!("Acquired process from pool for streaming");
            match process.send_prompt_stream(&prompt).await {
                Ok(s) => {
                    tracing::debug!("Stream initialized successfully");
                    s
                }
                Err(e) => {
                    tracing::error!(error = %e, "Failed to initialize prompt stream");
                    return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
                }
            }
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to acquire process from pool");
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };

    let created = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();

    // Create state for the stream transformation
    struct StreamState {
        dspy_header_sent: bool,
        is_dspy: bool,
        first_field: Option<String>,
        completion_sent: bool,
    }

    let state = StreamState {
        dspy_header_sent: false,
        is_dspy: is_dspy,
        first_field: output_fields.first().cloned(),
        completion_sent: false,
    };

    use futures_util::stream;

    // Transform the stream to add DSpy markers if needed
    let transformed_stream = stream::unfold((stream, state), move |(mut s, mut state)| async move {
        match s.next().await {
            Some(Ok(mut token)) => {
                // For DSpy requests, wrap the first chunk with field marker
                if state.is_dspy && !state.dspy_header_sent {
                    if let Some(ref first_field) = state.first_field {
                        token = format!("[[ ## {} ## ]]\n{}", first_field, token);
                        state.dspy_header_sent = true;
                    }
                }

                Some((Ok(token), (s, state)))
            }
            Some(Err(e)) => Some((Err(e), (s, state))),
            None => {
                // Stream ended - if DSpy and haven't sent completion, send it now
                if state.is_dspy && !state.completion_sent {
                    state.completion_sent = true;
                    Some((Ok("\n\n[[ ## completed ## ]]\n".to_string()), (s, state)))
                } else {
                    None
                }
            }
        }
    });

    let mut first_chunk = true;
    let mut chunk_sent_completion = false;
    let sse_stream = transformed_stream.map(move |chunk_result| {
        let event = match chunk_result {
            Ok(token) => {
                // Check if this is a completion marker chunk (before moving token)
                let is_completion = token.contains("[[ ## completed ## ]]");
                let finish_reason = if is_completion && !chunk_sent_completion {
                    chunk_sent_completion = true;
                    Some("stop".to_string())
                } else {
                    None
                };

                // First chunk includes the role
                let delta = if first_chunk {
                    first_chunk = false;
                    Delta {
                        role: Some("assistant".to_string()),
                        content: Some(token),
                    }
                } else {
                    Delta {
                        role: None,
                        content: Some(token),
                    }
                };

                let chunk = ChatCompletionChunk {
                    id: completion_id.clone(),
                    object: "chat.completion.chunk",
                    created,
                    model: model_name.clone(),
                    choices: vec![ChoiceChunk {
                        index: 0,
                        delta,
                        finish_reason,
                    }],
                };

                let json_data = serde_json::to_string(&chunk)
                    .unwrap_or_else(|_| "{}".to_string());

                Event::default().data(json_data)
            }
            Err(e) => {
                // Send error event
                Event::default().event("error").data(e.to_string())
            }
        };
        Ok::<Event, Infallible>(event)
    });

    Sse::new(sse_stream).into_response()
}

// Models endpoint structures
#[derive(Debug, Serialize)]
pub struct ModelObject {
    pub id: String,
    pub object: &'static str,
    pub created: u64,
    pub owned_by: &'static str,
}

#[derive(Debug, Serialize)]
pub struct ModelsListResponse {
    pub object: &'static str,
    pub data: Vec<ModelObject>,
}

// List all locally downloaded models
pub async fn list_models(State(state): State<AppState>) -> Response {
    tracing::debug!("Listing locally downloaded models");

    // Get list of locally downloaded models
    let models_output = match state.manager.list_models(false).await {
        Ok(output) => {
            tracing::debug!("Successfully retrieved model list");
            output
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to list models");
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };

    // Parse the output to extract model names
    let model_names: Vec<String> = models_output
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !trimmed.is_empty()
                && !trimmed.starts_with("Available")
                && !trimmed.starts_with("Downloaded")
                && !trimmed.starts_with("ALIAS")
        })
        .filter_map(|line| line.split_whitespace().next())
        .map(|s| s.to_string())
        .collect();

    // Create model objects
    let models: Vec<ModelObject> = model_names
        .into_iter()
        .map(|id| ModelObject {
            id,
            object: "model",
            created: 1700000000, // Static timestamp
            owned_by: "litert-lm",
        })
        .collect();

    let response = ModelsListResponse {
        object: "list",
        data: models,
    };

    Json(response).into_response()
}

// Get a specific model by ID
pub async fn get_model(
    State(state): State<AppState>,
    Path(model_id): Path<String>,
) -> Response {
    tracing::debug!(model_id = %model_id, "Looking up specific model");

    // Get list of locally downloaded models
    let models_output = match state.manager.list_models(false).await {
        Ok(output) => output,
        Err(e) => {
            tracing::error!(error = %e, model_id = %model_id, "Failed to list models");
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };

    // Check if the requested model exists
    let model_exists = models_output
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !trimmed.is_empty()
                && !trimmed.starts_with("Available")
                && !trimmed.starts_with("Downloaded")
                && !trimmed.starts_with("ALIAS")
        })
        .any(|line| line.trim() == model_id);

    if !model_exists {
        tracing::warn!(model_id = %model_id, "Model not found");
        return (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": {
                    "message": format!("Model '{}' not found", model_id),
                    "type": "invalid_request_error",
                    "code": "model_not_found"
                }
            })),
        )
            .into_response();
    }

    tracing::debug!(model_id = %model_id, "Model found");
    let model = ModelObject {
        id: model_id,
        object: "model",
        created: 1700000000,
        owned_by: "litert-lm",
    };

    Json(model).into_response()
}

pub fn create_router(state: AppState) -> Router {
    Router::new()
        .route("/v1/chat/completions", post(chat_completions))
        .route("/v1/models", get(list_models))
        .route("/v1/models/:model", get(get_model))
        .layer(TraceLayer::new_for_http())
        .with_state(state)
}