llama-gguf 0.14.0

A high-performance Rust implementation of llama.cpp - LLM inference engine with full GGUF support
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
//! HTTP request handlers

use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::sse::{Event, Sse};
use axum::response::{IntoResponse, Response};
use futures::stream::{self, Stream};
use tokio::sync::{Mutex, RwLock, Semaphore};

#[cfg(feature = "rag")]
use std::collections::HashMap;
#[cfg(feature = "rag")]
use axum::extract::Path;

use crate::engine::ChatTemplate;
use crate::model::ModelConfig;
use crate::model::embeddings::{EmbeddingConfig, EmbeddingExtractor};
use crate::sampling::{Sampler, SamplerConfig};
use crate::sampling::grammar::{Grammar, GrammarSampler};
use crate::tokenizer::Tokenizer;
use crate::{Backend, Model};

use super::types::*;

// =============================================================================
// Application State
// =============================================================================

/// Shared application state
pub struct AppState {
    /// Model behind RwLock for hot-swapping
    pub model: RwLock<Arc<dyn Model>>,
    pub tokenizer: RwLock<Arc<Tokenizer>>,
    pub config: RwLock<ModelConfig>,
    pub model_name: RwLock<String>,
    pub model_path: RwLock<String>,
    pub chat_template: RwLock<ChatTemplate>,
    pub backend: RwLock<Arc<dyn Backend>>,
    /// Semaphore for concurrency control (replaces inference_lock)
    pub inference_semaphore: Arc<Semaphore>,
    /// Request queue
    pub request_queue: RequestQueue,
}

/// FIFO request queue with configurable depth
pub struct RequestQueue {
    pub max_queue_depth: usize,
    pub max_concurrent: usize,
    active: Mutex<usize>,
    queue_depth: Mutex<usize>,
}

impl RequestQueue {
    pub fn new(max_queue_depth: usize, max_concurrent: usize) -> Self {
        Self {
            max_queue_depth,
            max_concurrent,
            active: Mutex::new(0),
            queue_depth: Mutex::new(0),
        }
    }

    /// Try to enqueue a request. Returns Err if queue is full.
    pub async fn try_enqueue(&self) -> Result<QueueGuard<'_>, ()> {
        let mut depth = self.queue_depth.lock().await;
        if *depth >= self.max_queue_depth {
            return Err(());
        }
        *depth += 1;
        Ok(QueueGuard {
            queue_depth: &self.queue_depth,
            active: &self.active,
            promoted: false,
        })
    }

    pub async fn active_count(&self) -> usize {
        *self.active.lock().await
    }

    pub async fn queued_count(&self) -> usize {
        *self.queue_depth.lock().await
    }
}

pub struct QueueGuard<'a> {
    queue_depth: &'a Mutex<usize>,
    active: &'a Mutex<usize>,
    promoted: bool,
}

impl<'a> QueueGuard<'a> {
    pub async fn promote(&mut self) {
        let mut active = self.active.lock().await;
        *active += 1;
        self.promoted = true;
    }
}

impl<'a> Drop for QueueGuard<'a> {
    fn drop(&mut self) {
        let queue_depth = self.queue_depth;
        let active = self.active;
        let promoted = self.promoted;
        // We need to use try_lock since Drop can't be async
        if let Ok(mut depth) = queue_depth.try_lock() {
            if *depth > 0 {
                *depth -= 1;
            }
        }
        if promoted {
            if let Ok(mut act) = active.try_lock() {
                if *act > 0 {
                    *act -= 1;
                }
            }
        }
    }
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Acquire a queue slot, returning 429 if full, then acquire the inference semaphore.
async fn acquire_inference_slot(
    state: &AppState,
) -> Result<(tokio::sync::OwnedSemaphorePermit, QueueGuard<'_>), Response> {
    let mut guard = state.request_queue.try_enqueue().await.map_err(|_| {
        let error = ErrorResponse::new(
            "Server overloaded: request queue is full",
            "rate_limit_exceeded",
        );
        (StatusCode::TOO_MANY_REQUESTS, Json(error)).into_response()
    })?;

    // Wait for a semaphore permit (FIFO by tokio Semaphore fairness)
    let permit = state
        .inference_semaphore
        .clone()
        .acquire_owned()
        .await
        .map_err(|_| {
            let error = ErrorResponse::new("Server shutting down", "server_error");
            (StatusCode::SERVICE_UNAVAILABLE, Json(error)).into_response()
        })?;

    guard.promote().await;
    Ok((permit, guard))
}

// =============================================================================
// Health & Models
// =============================================================================

pub async fn health(State(state): State<Arc<AppState>>) -> Json<HealthResponse> {
    let config = state.config.read().await;
    let model_name = state.model_name.read().await;
    Json(HealthResponse {
        status: "ok".to_string(),
        model: model_name.clone(),
        context_size: config.max_seq_len,
    })
}

pub async fn list_models(State(state): State<Arc<AppState>>) -> Json<ModelsResponse> {
    let model_name = state.model_name.read().await;
    Json(ModelsResponse {
        object: "list".to_string(),
        data: vec![ModelInfo {
            id: model_name.clone(),
            object: "model".to_string(),
            created: now_secs(),
            owned_by: "llama-gguf".to_string(),
        }],
    })
}

// =============================================================================
// Queue Status
// =============================================================================

pub async fn queue_status(State(state): State<Arc<AppState>>) -> Json<QueueStatusResponse> {
    Json(QueueStatusResponse {
        active_requests: state.request_queue.active_count().await,
        queued_requests: state.request_queue.queued_count().await,
        max_queue_depth: state.request_queue.max_queue_depth,
        max_concurrent: state.request_queue.max_concurrent,
    })
}

// =============================================================================
// Embeddings
// =============================================================================

pub async fn embeddings(
    State(state): State<Arc<AppState>>,
    Json(request): Json<EmbeddingRequest>,
) -> Response {
    let (_permit, _guard) = match acquire_inference_slot(&state).await {
        Ok(v) => v,
        Err(r) => return r,
    };

    let texts = match request.input {
        EmbeddingInput::Single(ref s) => vec![s.as_str()],
        EmbeddingInput::Batch(ref v) => v.iter().map(|s| s.as_str()).collect(),
    };

    let model = state.model.read().await;
    let tokenizer = state.tokenizer.read().await;
    let config = state.config.read().await;
    let backend = state.backend.read().await;
    let model_name = state.model_name.read().await;

    let embed_config = EmbeddingConfig::default();
    let extractor = EmbeddingExtractor::new(embed_config, &config);

    let mut results = Vec::with_capacity(texts.len());
    let mut total_prompt_tokens = 0usize;

    for (i, text) in texts.iter().enumerate() {
        let tokens = match tokenizer.encode(text, true) {
            Ok(t) => t,
            Err(e) => {
                let error = ErrorResponse::new(
                    format!("Tokenization failed: {}", e),
                    "invalid_request_error",
                );
                return (StatusCode::BAD_REQUEST, Json(error)).into_response();
            }
        };
        total_prompt_tokens += tokens.len();

        let mut ctx = model.create_context(backend.clone());
        match extractor.embed_text(model.as_ref(), &tokenizer, &mut ctx, text) {
            Ok(embedding) => {
                results.push(EmbeddingData {
                    object: "embedding".to_string(),
                    embedding,
                    index: i,
                });
            }
            Err(e) => {
                let error =
                    ErrorResponse::new(format!("Embedding failed: {}", e), "server_error");
                return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
            }
        }
    }

    Json(EmbeddingResponse {
        object: "list".to_string(),
        data: results,
        model: model_name.clone(),
        usage: EmbeddingUsage {
            prompt_tokens: total_prompt_tokens,
            total_tokens: total_prompt_tokens,
        },
    })
    .into_response()
}

// =============================================================================
// Chat Completions (with function calling)
// =============================================================================

pub async fn chat_completions(
    State(state): State<Arc<AppState>>,
    Json(request): Json<ChatCompletionRequest>,
) -> Response {
    let (_permit, _guard) = match acquire_inference_slot(&state).await {
        Ok(v) => v,
        Err(r) => return r,
    };

    let created = now_secs();
    let request_id = format!("chatcmpl-{}", created);

    let chat_template = state.chat_template.read().await;
    let model_name = state.model_name.read().await;

    let prompt = format_chat_messages(&request.messages, &chat_template, request.tools.as_deref());

    let sampler_config = SamplerConfig {
        temperature: request.temperature,
        top_p: request.top_p,
        frequency_penalty: request.frequency_penalty,
        presence_penalty: request.presence_penalty,
        ..Default::default()
    };

    let has_tools = request.tools.is_some();
    let forced_function = match &request.tool_choice {
        Some(ToolChoice::Specific { function, .. }) => Some(function.name.clone()),
        _ => None,
    };

    match generate_response(
        &state,
        &prompt,
        request.max_tokens,
        sampler_config,
        request.stop.as_deref(),
        has_tools,
    )
    .await
    {
        Ok((response_text, prompt_tokens, completion_tokens)) => {
            let (message, finish_reason) =
                if has_tools {
                    match parse_tool_calls(&response_text, forced_function.as_deref()) {
                        Some(tool_calls) => (
                            ChatMessage {
                                role: Role::Assistant,
                                content: String::new(),
                                tool_calls: Some(tool_calls),
                                tool_call_id: None,
                            },
                            "tool_calls".to_string(),
                        ),
                        None => (
                            ChatMessage {
                                role: Role::Assistant,
                                content: response_text.clone(),
                                tool_calls: None,
                                tool_call_id: None,
                            },
                            "stop".to_string(),
                        ),
                    }
                } else {
                    (
                        ChatMessage {
                            role: Role::Assistant,
                            content: response_text.clone(),
                            tool_calls: None,
                            tool_call_id: None,
                        },
                        "stop".to_string(),
                    )
                };

            if request.stream {
                let stream = create_chat_stream(
                    request_id,
                    model_name.clone(),
                    created,
                    response_text,
                    prompt_tokens,
                    completion_tokens,
                );
                Sse::new(stream).into_response()
            } else {
                let response = ChatCompletionResponse {
                    id: request_id,
                    object: "chat.completion".to_string(),
                    created,
                    model: model_name.clone(),
                    choices: vec![ChatCompletionChoice {
                        index: 0,
                        message,
                        finish_reason,
                    }],
                    usage: Usage {
                        prompt_tokens,
                        completion_tokens,
                        total_tokens: prompt_tokens + completion_tokens,
                    },
                };
                Json(response).into_response()
            }
        }
        Err(e) => {
            let error = ErrorResponse::new(e.to_string(), "server_error");
            (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response()
        }
    }
}

// =============================================================================
// Text Completions
// =============================================================================

pub async fn completions(
    State(state): State<Arc<AppState>>,
    Json(request): Json<CompletionRequest>,
) -> Response {
    let (_permit, _guard) = match acquire_inference_slot(&state).await {
        Ok(v) => v,
        Err(r) => return r,
    };

    let created = now_secs();
    let request_id = format!("cmpl-{}", created);
    let model_name = state.model_name.read().await;

    let sampler_config = SamplerConfig {
        temperature: request.temperature,
        top_p: request.top_p,
        ..Default::default()
    };

    match generate_response(
        &state,
        &request.prompt,
        request.max_tokens,
        sampler_config,
        request.stop.as_deref(),
        false,
    )
    .await
    {
        Ok((response_text, prompt_tokens, completion_tokens)) => {
            let response = CompletionResponse {
                id: request_id,
                object: "text_completion".to_string(),
                created,
                model: model_name.clone(),
                choices: vec![CompletionChoice {
                    text: response_text,
                    index: 0,
                    finish_reason: "stop".to_string(),
                }],
                usage: Usage {
                    prompt_tokens,
                    completion_tokens,
                    total_tokens: prompt_tokens + completion_tokens,
                },
            };
            Json(response).into_response()
        }
        Err(e) => {
            let error = ErrorResponse::new(e.to_string(), "server_error");
            (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response()
        }
    }
}

// =============================================================================
// Model Hot-Swap
// =============================================================================

pub async fn load_model(
    State(state): State<Arc<AppState>>,
    Json(request): Json<LoadModelRequest>,
) -> Response {
    tracing::info!("Hot-swap: loading model from {}", request.model_path);

    match reload_model_from_path(&state, &request.model_path).await {
        Ok((name, ctx_size)) => {
            Json(LoadModelResponse {
                status: "loaded".to_string(),
                model: name,
                context_size: ctx_size,
            })
            .into_response()
        }
        Err(e) => {
            let error = ErrorResponse::new(format!("Model load failed: {}", e), "server_error");
            (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response()
        }
    }
}

/// Reload model, swapping all state atomically.
pub async fn reload_model_from_path(
    state: &AppState,
    model_path: &str,
) -> Result<(String, usize), Box<dyn std::error::Error + Send + Sync>> {
    use crate::engine::ChatTemplate;
    use crate::gguf::GgufFile;
    use crate::model::ModelLoader;

    let gguf = GgufFile::open(model_path)?;
    let tokenizer = Tokenizer::from_gguf(&gguf)?;
    let chat_template = ChatTemplate::detect(&gguf);
    let loader = ModelLoader::load(model_path)?;
    let model_config = loader.config().clone();
    let model = loader.build_model()?;

    let (gpu_model, backend) = super::api::select_model_and_backend(model, &model_config);

    let name = std::path::Path::new(model_path)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("llama")
        .to_string();
    let ctx_size = model_config.max_seq_len;

    // Swap atomically
    *state.model.write().await = gpu_model;
    *state.tokenizer.write().await = Arc::new(tokenizer);
    *state.config.write().await = model_config;
    *state.model_name.write().await = name.clone();
    *state.model_path.write().await = model_path.to_string();
    *state.chat_template.write().await = chat_template;
    *state.backend.write().await = backend;

    tracing::info!("Hot-swap complete: {} (ctx={})", name, ctx_size);
    Ok((name, ctx_size))
}

// =============================================================================
// Internal helpers
// =============================================================================

/// Format chat messages into a prompt string, optionally injecting tool definitions
fn format_chat_messages(
    messages: &[ChatMessage],
    template: &ChatTemplate,
    tools: Option<&[ToolDefinition]>,
) -> String {
    let mut system_prompt = String::new();
    let mut conversation: Vec<&ChatMessage> = Vec::new();

    for msg in messages {
        match msg.role {
            Role::System => system_prompt = msg.content.clone(),
            _ => conversation.push(msg),
        }
    }

    // Inject tool definitions into the system prompt
    if let Some(tools) = tools {
        if !tools.is_empty() {
            let tools_section = format_tools_for_prompt(tools);
            if system_prompt.is_empty() {
                system_prompt = tools_section;
            } else {
                system_prompt = format!("{}\n\n{}", system_prompt, tools_section);
            }
        }
    }

    let mut prompt = String::new();
    let mut is_first_user = true;

    for msg in &conversation {
        match msg.role {
            Role::User => {
                if is_first_user && !system_prompt.is_empty() {
                    prompt.push_str(&template.format_first_turn(&system_prompt, &msg.content));
                    is_first_user = false;
                } else {
                    prompt.push_str(&template.format_continuation(&msg.content));
                    is_first_user = false;
                }
            }
            Role::Assistant => {
                prompt.push_str(&msg.content);
            }
            Role::Tool => {
                let tool_result = if let Some(ref id) = msg.tool_call_id {
                    format!("[Tool Result (call_id={})]:\n{}", id, msg.content)
                } else {
                    format!("[Tool Result]:\n{}", msg.content)
                };
                prompt.push_str(&template.format_continuation(&tool_result));
            }
            Role::System => {}
        }
    }

    if is_first_user && !system_prompt.is_empty() {
        prompt.push_str(&template.format_first_turn(&system_prompt, ""));
    }

    prompt
}

/// Format tool definitions into a prompt-injectable string
fn format_tools_for_prompt(tools: &[ToolDefinition]) -> String {
    let mut section = String::from(
        "You have access to the following tools. To call a tool, respond with a JSON object in this exact format:\n\
         {\"tool_calls\": [{\"name\": \"function_name\", \"arguments\": {\"arg\": \"value\"}}]}\n\n\
         Available tools:\n",
    );

    for tool in tools {
        section.push_str(&format!("- {}", tool.function.name));
        if let Some(ref desc) = tool.function.description {
            section.push_str(&format!(": {}", desc));
        }
        section.push('\n');
        if let Some(ref params) = tool.function.parameters {
            if let Ok(pretty) = serde_json::to_string_pretty(params) {
                section.push_str(&format!("  Parameters: {}\n", pretty));
            }
        }
    }

    section
}

/// Try to parse tool calls from the model's output.
/// Looks for JSON with a "tool_calls" array, or a single function call object.
fn parse_tool_calls(text: &str, forced_name: Option<&str>) -> Option<Vec<ToolCall>> {
    let trimmed = text.trim();

    // Try to find JSON in the response
    let json_str = extract_json_from_text(trimmed)?;
    let value: serde_json::Value = serde_json::from_str(&json_str).ok()?;

    let mut calls = Vec::new();

    if let Some(arr) = value.get("tool_calls").and_then(|v| v.as_array()) {
        for (i, item) in arr.iter().enumerate() {
            let name = forced_name
                .map(String::from)
                .or_else(|| item.get("name").and_then(|v| v.as_str()).map(String::from))?;
            let args = item
                .get("arguments")
                .map(|v| serde_json::to_string(v).unwrap_or_default())
                .unwrap_or_else(|| "{}".to_string());
            calls.push(ToolCall {
                id: format!("call_{}", i),
                call_type: "function".to_string(),
                function: FunctionCall {
                    name,
                    arguments: args,
                },
            });
        }
    } else if value.get("name").is_some() || forced_name.is_some() {
        let name = forced_name
            .map(String::from)
            .or_else(|| value.get("name").and_then(|v| v.as_str()).map(String::from))?;
        let args = value
            .get("arguments")
            .map(|v| serde_json::to_string(v).unwrap_or_default())
            .unwrap_or_else(|| "{}".to_string());
        calls.push(ToolCall {
            id: "call_0".to_string(),
            call_type: "function".to_string(),
            function: FunctionCall {
                name,
                arguments: args,
            },
        });
    }

    if calls.is_empty() {
        None
    } else {
        Some(calls)
    }
}

/// Extract the first JSON object from text (handles markdown code blocks, etc.)
fn extract_json_from_text(text: &str) -> Option<String> {
    // Try the whole text first
    if text.starts_with('{') {
        if let Ok(_) = serde_json::from_str::<serde_json::Value>(text) {
            return Some(text.to_string());
        }
    }

    // Look for JSON inside code blocks
    if let Some(start) = text.find("```json") {
        let after = &text[start + 7..];
        if let Some(end) = after.find("```") {
            let candidate = after[..end].trim();
            if serde_json::from_str::<serde_json::Value>(candidate).is_ok() {
                return Some(candidate.to_string());
            }
        }
    }

    // Find first { and matching }
    let mut depth = 0i32;
    let mut start_idx = None;
    for (i, ch) in text.char_indices() {
        match ch {
            '{' => {
                if depth == 0 {
                    start_idx = Some(i);
                }
                depth += 1;
            }
            '}' => {
                depth -= 1;
                if depth == 0 {
                    if let Some(s) = start_idx {
                        let candidate = &text[s..=i];
                        if serde_json::from_str::<serde_json::Value>(candidate).is_ok() {
                            return Some(candidate.to_string());
                        }
                    }
                }
            }
            _ => {}
        }
    }

    None
}

/// Generate text response using the model
async fn generate_response(
    state: &AppState,
    prompt: &str,
    max_tokens: usize,
    sampler_config: SamplerConfig,
    _stop_sequences: Option<&[String]>,
    use_json_grammar: bool,
) -> Result<(String, usize, usize), Box<dyn std::error::Error + Send + Sync>> {
    let model = state.model.read().await;
    let tokenizer = state.tokenizer.read().await;
    let config = state.config.read().await;
    let backend = state.backend.read().await;
    let chat_template = state.chat_template.read().await;

    let mut ctx = model.create_context(backend.clone());
    let mut sampler = Sampler::new(sampler_config, config.vocab_size);

    // Optional grammar sampler for structured JSON output
    let mut grammar_sampler = if use_json_grammar {
        let vocab: Vec<String> = (0..config.vocab_size as u32)
            .map(|id| {
                tokenizer
                    .get_token(id)
                    .unwrap_or("")
                    .to_string()
            })
            .collect();
        Some(GrammarSampler::new(
            Grammar::Json(crate::sampling::grammar::JsonGrammar {
                allow_any: true,
                ..Default::default()
            }),
            vocab,
        ))
    } else {
        None
    };

    let prompt_tokens = tokenizer.encode(prompt, true)?;
    let prompt_len = prompt_tokens.len();
    let mut all_tokens = prompt_tokens.clone();

    // Prefill
    if prompt_tokens.len() > 1 {
        for (i, &token) in prompt_tokens[..prompt_tokens.len() - 1].iter().enumerate() {
            if i < config.max_seq_len {
                let _ = model.forward(&[token], &mut ctx);
            }
        }
    }

    let stop_patterns = chat_template.stop_patterns();
    let mut response_text = String::new();
    let mut completion_tokens = 0;

    for _ in 0..max_tokens {
        let last_token = *all_tokens
            .last()
            .unwrap_or(&tokenizer.special_tokens.bos_token_id);

        let logits = model.forward(&[last_token], &mut ctx)?;

        // Apply grammar constraint if active
        if let Some(ref gs) = grammar_sampler {
            let mut logit_data = logits.as_f32()?.to_vec();
            gs.apply_mask(&mut logit_data);
            // Sample from masked logits via the tensor
            let masked_logits =
                crate::tensor::Tensor::from_f32(&logit_data, logits.shape().to_vec())
                    .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
            let next_token = sampler.sample(&masked_logits, &all_tokens);

            if next_token == tokenizer.special_tokens.eos_token_id {
                break;
            }

            if let Ok(text) = tokenizer.decode(&[next_token]) {
                if let Some(ref mut gs) = grammar_sampler {
                    gs.record_token(&text);
                }
                let combined = format!("{}{}", response_text, text);
                let should_stop = stop_patterns.iter().any(|p| combined.contains(p));
                if should_stop {
                    for pattern in stop_patterns {
                        if let Some(idx) = combined.find(pattern) {
                            response_text = combined[..idx].to_string();
                            return Ok((
                                response_text.trim().to_string(),
                                prompt_len,
                                completion_tokens,
                            ));
                        }
                    }
                    break;
                }
                response_text.push_str(&text);
            }

            all_tokens.push(next_token);
            completion_tokens += 1;

            if grammar_sampler.as_ref().map_or(false, |gs| gs.is_complete()) {
                break;
            }
        } else {
            let next_token = sampler.sample(&logits, &all_tokens);

            if next_token == tokenizer.special_tokens.eos_token_id {
                break;
            }

            if let Ok(text) = tokenizer.decode(&[next_token]) {
                let combined = format!("{}{}", response_text, text);
                let should_stop = stop_patterns.iter().any(|p| combined.contains(p));
                if should_stop {
                    for pattern in stop_patterns {
                        if let Some(idx) = combined.find(pattern) {
                            response_text = combined[..idx].to_string();
                            return Ok((
                                response_text.trim().to_string(),
                                prompt_len,
                                completion_tokens,
                            ));
                        }
                    }
                    break;
                }
                response_text.push_str(&text);
            }

            all_tokens.push(next_token);
            completion_tokens += 1;
        }
    }

    Ok((
        response_text.trim().to_string(),
        prompt_len,
        completion_tokens,
    ))
}

/// Create streaming response for chat completions with usage in the final chunk
fn create_chat_stream(
    request_id: String,
    model: String,
    created: u64,
    response_text: String,
    prompt_tokens: usize,
    completion_tokens: usize,
) -> impl Stream<Item = Result<Event, std::convert::Infallible>> {
    let chunks = vec![
        // Role chunk
        ChatCompletionChunk {
            id: request_id.clone(),
            object: "chat.completion.chunk".to_string(),
            created,
            model: model.clone(),
            choices: vec![ChatCompletionChunkChoice {
                index: 0,
                delta: ChatCompletionDelta {
                    role: Some(Role::Assistant),
                    content: None,
                    tool_calls: None,
                },
                finish_reason: None,
            }],
            usage: None,
        },
        // Content chunk
        ChatCompletionChunk {
            id: request_id.clone(),
            object: "chat.completion.chunk".to_string(),
            created,
            model: model.clone(),
            choices: vec![ChatCompletionChunkChoice {
                index: 0,
                delta: ChatCompletionDelta {
                    role: None,
                    content: Some(response_text),
                    tool_calls: None,
                },
                finish_reason: None,
            }],
            usage: None,
        },
        // Final chunk with finish reason and usage
        ChatCompletionChunk {
            id: request_id,
            object: "chat.completion.chunk".to_string(),
            created,
            model,
            choices: vec![ChatCompletionChunkChoice {
                index: 0,
                delta: ChatCompletionDelta {
                    role: None,
                    content: None,
                    tool_calls: None,
                },
                finish_reason: Some("stop".to_string()),
            }],
            usage: Some(Usage {
                prompt_tokens,
                completion_tokens,
                total_tokens: prompt_tokens + completion_tokens,
            }),
        },
    ];

    stream::iter(chunks.into_iter().map(|chunk| {
        let data = serde_json::to_string(&chunk).unwrap_or_default();
        Ok(Event::default().data(data))
    }))
}

// =============================================================================
// RAG / Knowledge Base Handlers
// =============================================================================

#[cfg(feature = "rag")]
pub struct RagState {
    pub knowledge_bases: tokio::sync::RwLock<HashMap<String, crate::rag::KnowledgeBaseConfig>>,
    pub rag_config: crate::rag::RagConfig,
}

#[cfg(feature = "rag")]
impl RagState {
    pub fn new(rag_config: crate::rag::RagConfig) -> Self {
        Self {
            knowledge_bases: tokio::sync::RwLock::new(HashMap::new()),
            rag_config,
        }
    }
}

#[cfg(feature = "rag")]
pub async fn retrieve(
    State(rag_state): State<Arc<RagState>>,
    Json(request): Json<RetrieveRequest>,
) -> Response {
    use crate::rag::{KnowledgeBase, KnowledgeBaseConfig, RetrievalConfig};

    let kb_config = {
        let kbs = rag_state.knowledge_bases.read().await;
        kbs.get(&request.knowledge_base_id)
            .cloned()
            .unwrap_or_else(|| KnowledgeBaseConfig {
                name: request.knowledge_base_id.clone(),
                storage: rag_state.rag_config.clone(),
                ..Default::default()
            })
    };

    let kb = match KnowledgeBase::connect(kb_config).await {
        Ok(kb) => kb,
        Err(e) => {
            let error = ErrorResponse::new(
                format!("Failed to connect to knowledge base: {}", e),
                "knowledge_base_error",
            );
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    let mut retrieval_config = RetrievalConfig::default();

    if let Some(ref config) = request.retrieval_configuration
        && let Some(ref vs_config) = config.vector_search_configuration
    {
        retrieval_config.max_results = vs_config.number_of_results;

        if let Some(ref filter) = vs_config.filter {
            retrieval_config.filter = convert_filter(filter);
        }
    }

    match kb.retrieve(&request.query, Some(retrieval_config)).await {
        Ok(response) => {
            let results: Vec<RetrievalResult> = response
                .chunks
                .into_iter()
                .map(|chunk| RetrievalResult {
                    content: RetrievalResultContent {
                        text: chunk.content,
                    },
                    location: RetrievalResultLocation {
                        location_type: "CUSTOM".to_string(),
                        s3_location: None,
                        custom_location: Some(CustomLocation {
                            uri: chunk.source.uri,
                        }),
                    },
                    score: chunk.score,
                    metadata: chunk.metadata,
                })
                .collect();

            Json(RetrieveResponse {
                retrieval_results: results,
                next_token: None,
            })
            .into_response()
        }
        Err(e) => {
            let error = ErrorResponse::new(format!("Retrieval failed: {}", e), "retrieval_error");
            (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response()
        }
    }
}

#[cfg(feature = "rag")]
pub async fn retrieve_and_generate(
    State((app_state, rag_state)): State<(Arc<AppState>, Arc<RagState>)>,
    Json(request): Json<RetrieveAndGenerateRequest>,
) -> Response {
    use crate::rag::{KnowledgeBase, KnowledgeBaseConfig, RetrievalConfig};

    let kb_id = &request
        .retrieve_and_generate_configuration
        .knowledge_base_configuration
        .knowledge_base_id;

    let kb_config = {
        let kbs = rag_state.knowledge_bases.read().await;
        kbs.get(kb_id)
            .cloned()
            .unwrap_or_else(|| KnowledgeBaseConfig {
                name: kb_id.clone(),
                storage: rag_state.rag_config.clone(),
                ..Default::default()
            })
    };

    let kb = match KnowledgeBase::connect(kb_config).await {
        Ok(kb) => kb,
        Err(e) => {
            let error = ErrorResponse::new(
                format!("Failed to connect to knowledge base: {}", e),
                "knowledge_base_error",
            );
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    let mut retrieval_config = RetrievalConfig::default();

    if let Some(ref config) = request
        .retrieve_and_generate_configuration
        .knowledge_base_configuration
        .retrieval_configuration
        && let Some(ref vs_config) = config.vector_search_configuration
    {
        retrieval_config.max_results = vs_config.number_of_results;
    }

    if let Some(ref gen_config) = request
        .retrieve_and_generate_configuration
        .knowledge_base_configuration
        .generation_configuration
        && let Some(ref template) = gen_config.prompt_template
    {
        let converted = template
            .text_prompt_template
            .replace("$query$", "{query}")
            .replace("$search_results$", "{context}");
        retrieval_config.prompt_template = Some(converted);
    }

    let rag_response = match kb
        .retrieve_and_generate(&request.input.text, Some(retrieval_config))
        .await
    {
        Ok(resp) => resp,
        Err(e) => {
            let error = ErrorResponse::new(format!("RAG failed: {}", e), "rag_error");
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    let (temperature, top_p, max_tokens) = if let Some(ref gen_config) = request
        .retrieve_and_generate_configuration
        .knowledge_base_configuration
        .generation_configuration
    {
        if let Some(ref inf_config) = gen_config.inference_config {
            if let Some(ref text_config) = inf_config.text_inference_config {
                (
                    text_config.temperature,
                    text_config.top_p,
                    text_config.max_tokens,
                )
            } else {
                (0.7, 0.9, 256)
            }
        } else {
            (0.7, 0.9, 256)
        }
    } else {
        (0.7, 0.9, 256)
    };

    let (_permit, _guard) = match acquire_inference_slot(&app_state).await {
        Ok(v) => v,
        Err(r) => return r,
    };

    let sampler_config = SamplerConfig {
        temperature,
        top_p,
        ..Default::default()
    };

    let generated_text = match generate_response(
        &app_state,
        &rag_response.output,
        max_tokens,
        sampler_config,
        None,
        false,
    )
    .await
    {
        Ok((text, _, _)) => text,
        Err(e) => {
            let error = ErrorResponse::new(format!("Generation failed: {}", e), "generation_error");
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    let citations: Vec<Citation> = rag_response
        .citations
        .into_iter()
        .map(|c| Citation {
            generated_response_part: None,
            retrieved_references: vec![RetrievedReference {
                content: RetrievalResultContent { text: c.content },
                location: RetrievalResultLocation {
                    location_type: "CUSTOM".to_string(),
                    s3_location: None,
                    custom_location: Some(CustomLocation { uri: c.source.uri }),
                },
                metadata: None,
            }],
        })
        .collect();

    Json(RetrieveAndGenerateResponse {
        output: RetrieveAndGenerateOutput {
            text: generated_text,
        },
        citations,
        session_id: request.session_id,
    })
    .into_response()
}

#[cfg(feature = "rag")]
pub async fn ingest(
    State(rag_state): State<Arc<RagState>>,
    Json(request): Json<IngestRequest>,
) -> Response {
    use crate::rag::{DataSource, KnowledgeBase, KnowledgeBaseConfig};

    let kb_config = {
        let kbs = rag_state.knowledge_bases.read().await;
        kbs.get(&request.knowledge_base_id)
            .cloned()
            .unwrap_or_else(|| KnowledgeBaseConfig {
                name: request.knowledge_base_id.clone(),
                storage: rag_state.rag_config.clone(),
                ..Default::default()
            })
    };

    let kb = match KnowledgeBase::connect(kb_config).await {
        Ok(kb) => kb,
        Err(e) => {
            let error = ErrorResponse::new(
                format!("Failed to connect to knowledge base: {}", e),
                "knowledge_base_error",
            );
            return (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response();
        }
    };

    let mut total_docs = 0;
    let mut total_chunks = 0;
    let mut failures = Vec::new();

    for doc in request.documents {
        let source = DataSource::Text {
            content: doc.content.text,
            source_id: doc.document_id.clone(),
            metadata: doc.metadata,
        };

        match kb.ingest(source).await {
            Ok(result) => {
                total_docs += result.documents_processed;
                total_chunks += result.chunks_created;
                for (id, err) in result.failures {
                    failures.push(IngestFailure {
                        document_id: id,
                        error_message: err,
                    });
                }
            }
            Err(e) => {
                failures.push(IngestFailure {
                    document_id: doc.document_id,
                    error_message: e.to_string(),
                });
            }
        }
    }

    Json(IngestResponse {
        documents_ingested: total_docs,
        chunks_created: total_chunks,
        failures,
    })
    .into_response()
}

#[cfg(feature = "rag")]
pub async fn list_knowledge_bases(
    State(rag_state): State<Arc<RagState>>,
    Json(_request): Json<ListKnowledgeBasesRequest>,
) -> Response {
    let kbs = rag_state.knowledge_bases.read().await;

    let summaries: Vec<KnowledgeBaseSummary> = kbs
        .iter()
        .map(|(id, config)| KnowledgeBaseSummary {
            knowledge_base_id: id.clone(),
            name: config.name.clone(),
            description: config.description.clone(),
            status: "ACTIVE".to_string(),
            updated_at: current_timestamp(),
        })
        .collect();

    Json(ListKnowledgeBasesResponse {
        knowledge_base_summaries: summaries,
        next_token: None,
    })
    .into_response()
}

#[cfg(feature = "rag")]
pub async fn get_knowledge_base(
    State(rag_state): State<Arc<RagState>>,
    Path(kb_id): Path<String>,
) -> Response {
    use crate::rag::{KnowledgeBase, KnowledgeBaseConfig};

    let kb_config = {
        let kbs = rag_state.knowledge_bases.read().await;
        kbs.get(&kb_id)
            .cloned()
            .unwrap_or_else(|| KnowledgeBaseConfig {
                name: kb_id.clone(),
                storage: rag_state.rag_config.clone(),
                ..Default::default()
            })
    };

    match KnowledgeBase::connect(kb_config.clone()).await {
        Ok(kb) => match kb.stats().await {
            Ok(stats) => Json(GetKnowledgeBaseResponse {
                knowledge_base: KnowledgeBaseDetail {
                    knowledge_base_id: kb_id,
                    name: stats.name,
                    description: kb_config.description,
                    status: "ACTIVE".to_string(),
                    storage_configuration: StorageConfigurationResponse {
                        storage_type: "PGVECTOR".to_string(),
                        vector_dimension: stats.embedding_dimension,
                    },
                    updated_at: current_timestamp(),
                },
            })
            .into_response(),
            Err(e) => {
                let error = ErrorResponse::new(
                    format!("Failed to get stats: {}", e),
                    "knowledge_base_error",
                );
                (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response()
            }
        },
        Err(e) => {
            let error = ErrorResponse::new(format!("Knowledge base not found: {}", e), "not_found");
            (StatusCode::NOT_FOUND, Json(error)).into_response()
        }
    }
}

#[cfg(feature = "rag")]
pub async fn delete_knowledge_base(
    State(rag_state): State<Arc<RagState>>,
    Path(kb_id): Path<String>,
) -> Response {
    use crate::rag::{KnowledgeBase, KnowledgeBaseConfig};

    let kb_config = {
        let mut kbs = rag_state.knowledge_bases.write().await;
        kbs.remove(&kb_id).unwrap_or_else(|| KnowledgeBaseConfig {
            name: kb_id.clone(),
            storage: rag_state.rag_config.clone(),
            ..Default::default()
        })
    };

    match KnowledgeBase::connect(kb_config).await {
        Ok(kb) => match kb.delete().await {
            Ok(_) => Json(serde_json::json!({
                "knowledgeBaseId": kb_id,
                "status": "DELETING"
            }))
            .into_response(),
            Err(e) => {
                let error = ErrorResponse::new(format!("Failed to delete: {}", e), "delete_error");
                (StatusCode::INTERNAL_SERVER_ERROR, Json(error)).into_response()
            }
        },
        Err(e) => {
            let error = ErrorResponse::new(format!("Knowledge base not found: {}", e), "not_found");
            (StatusCode::NOT_FOUND, Json(error)).into_response()
        }
    }
}

#[cfg(feature = "rag")]
fn convert_filter(filter: &RetrievalFilter) -> Option<crate::rag::MetadataFilter> {
    use crate::rag::MetadataFilter;

    if let Some(ref and_filters) = filter.and_all {
        let converted: Vec<_> = and_filters.iter().filter_map(convert_filter).collect();
        if !converted.is_empty() {
            return Some(MetadataFilter::and(converted));
        }
    }

    if let Some(ref or_filters) = filter.or_all {
        let converted: Vec<_> = or_filters.iter().filter_map(convert_filter).collect();
        if !converted.is_empty() {
            return Some(MetadataFilter::or(converted));
        }
    }

    if let Some(ref cond) = filter.equals {
        return Some(MetadataFilter::eq(&cond.key, cond.value.clone()));
    }

    if let Some(ref cond) = filter.not_equals {
        return Some(MetadataFilter::ne(&cond.key, cond.value.clone()));
    }

    if let Some(ref cond) = filter.greater_than {
        return Some(MetadataFilter::gt(&cond.key, cond.value.clone()));
    }

    if let Some(ref cond) = filter.less_than {
        return Some(MetadataFilter::lt(&cond.key, cond.value.clone()));
    }

    if let Some(ref cond) = filter.string_contains
        && let Some(s) = cond.value.as_str()
    {
        return Some(MetadataFilter::contains(&cond.key, s));
    }

    if let Some(ref cond) = filter.starts_with
        && let Some(s) = cond.value.as_str()
    {
        return Some(MetadataFilter::starts_with(&cond.key, s));
    }

    None
}

#[cfg(feature = "rag")]
fn current_timestamp() -> String {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    format!("{}Z", now)
}