swadhinbiswas WIP save-point: production hardening, H3 removal, fmt gate, and accumulated phase work · 7/15/2026
2080d40
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
//! OpenAI-compatible request/response protocol for JustAPI inference.
//!
//! Provides the data types and streaming/non-streaming drivers that make a
//! [`Engine`](crate::engine::Engine) speak the OpenAI Chat Completions,
//! Completions, Embeddings, and Models APIs. The hot path (token generation)
//! runs inside the engine on a dedicated OS thread; this module only formats
//! the I/O — it never touches the GIL.
//!
//! The HTTP-wiring (mounting these as routes) lives in `justapi-core`'s
//! `openai` module behind the `inference` feature, so this crate stays
//! dependency-light and testable on its own.
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::engine::Engine;
use crate::model::{FinishReason, MockModel, ModelError, SamplingParams};
use crate::scheduler_engine::SchedulerEngine;
// ---------------------------------------------------------------------------
// Request types
// ---------------------------------------------------------------------------
/// A single chat message.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChatMessage {
pub role: String,
pub content: String,
#[serde(default)]
pub name: Option<String>,
}
fn default_max_tokens() -> usize {
256
}
/// `POST /v1/chat/completions` request.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChatCompletionRequest {
/// Model registry name (the name the model was registered under).
pub model: String,
pub messages: Vec<ChatMessage>,
#[serde(default)]
pub temperature: Option<f32>,
#[serde(default = "default_max_tokens")]
pub max_tokens: usize,
/// Newer OpenAI clients send this instead of `max_tokens`.
#[serde(default)]
pub max_completion_tokens: Option<usize>,
#[serde(default)]
pub top_p: Option<f32>,
/// Stream tokens as Server-Sent Events.
#[serde(default)]
pub stream: bool,
/// Stop strings (ignored by the mock model; honored by real models).
#[serde(default)]
pub stop: Option<Vec<String>>,
#[serde(default)]
pub user: Option<String>,
}
impl ChatCompletionRequest {
/// Resolve the effective max-token count across both fields.
pub fn effective_max_tokens(&self) -> usize {
self.max_completion_tokens.unwrap_or(self.max_tokens)
}
}
/// `POST /v1/completions` request.
#[derive(Debug, Clone, Deserialize)]
pub struct CompletionRequest {
pub model: String,
pub prompt: String,
#[serde(default)]
pub temperature: Option<f32>,
#[serde(default = "default_max_tokens")]
pub max_tokens: usize,
#[serde(default)]
pub top_p: Option<f32>,
#[serde(default)]
pub stream: bool,
#[serde(default)]
pub stop: Option<Vec<String>>,
}
/// `POST /v1/embeddings` request.
#[derive(Debug, Clone, Deserialize)]
pub struct EmbeddingRequest {
pub model: String,
#[serde(default)]
pub input: EmbeddingInput,
#[serde(default)]
pub encoding_format: Option<String>,
}
/// Embedding input: a single string or a list of strings.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum EmbeddingInput {
Single(String),
Many(Vec<String>),
}
impl Default for EmbeddingInput {
fn default() -> Self {
EmbeddingInput::Single(String::new())
}
}
impl EmbeddingInput {
fn into_texts(self) -> Vec<String> {
match self {
EmbeddingInput::Single(s) => vec![s],
EmbeddingInput::Many(v) => v,
}
}
}
// ---------------------------------------------------------------------------
// Response types
// ---------------------------------------------------------------------------
/// An OpenAI `model` object.
#[derive(Debug, Clone, Serialize, Default)]
pub struct ModelObject {
pub id: String,
pub object: &'static str,
pub created: u64,
pub owned_by: String,
#[serde(default)]
pub permission: Vec<ModelPermission>,
#[serde(default)]
pub root: Option<String>,
#[serde(default)]
pub parent: Option<String>,
}
/// OpenAI model permission entry (placeholder).
#[derive(Debug, Clone, Serialize, Default)]
pub struct ModelPermission {
#[serde(default)]
pub id: String,
#[serde(default)]
pub object: &'static str,
#[serde(default)]
pub created: u64,
#[serde(default)]
pub allow_create_engine: bool,
#[serde(default)]
pub allow_sampling: bool,
#[serde(default)]
pub allow_logprobs: bool,
#[serde(default)]
pub allow_search_indices: bool,
#[serde(default)]
pub allow_view: bool,
#[serde(default)]
pub organization: String,
#[serde(default)]
pub group: Option<String>,
#[serde(default)]
pub is_blocking: bool,
}
/// `GET /v1/models` response.
#[derive(Debug, Clone, Serialize)]
pub struct ModelList {
pub object: &'static str,
pub data: Vec<ModelObject>,
}
/// Token usage accounting.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct Usage {
pub prompt_tokens: usize,
pub completion_tokens: usize,
pub total_tokens: usize,
}
/// `POST /v1/chat/completions` (non-streaming) response.
#[derive(Debug, Clone, Serialize)]
pub struct ChatCompletionResponse {
pub id: String,
pub object: &'static str,
pub created: u64,
pub model: String,
pub choices: Vec<ChatCompletionChoice>,
pub usage: Usage,
}
/// A single chat completion choice.
#[derive(Debug, Clone, Serialize)]
pub struct ChatCompletionChoice {
pub index: usize,
pub message: ChatMessageOut,
pub finish_reason: String,
}
/// An assistant message in a completion response.
#[derive(Debug, Clone, Serialize)]
pub struct ChatMessageOut {
pub role: String,
pub content: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub finish_reason: Option<String>,
}
/// A streaming chat-completion chunk.
#[derive(Debug, Clone, Serialize)]
pub struct ChatCompletionChunk {
pub id: String,
pub object: &'static str,
pub created: u64,
pub model: String,
pub choices: Vec<ChunkChoice>,
}
/// A single choice delta within a streaming chunk.
#[derive(Debug, Clone, Serialize)]
pub struct ChunkChoice {
pub index: usize,
pub delta: Delta,
#[serde(skip_serializing_if = "Option::is_none")]
pub finish_reason: Option<String>,
}
/// The incremental content of a streaming chunk.
#[derive(Debug, Clone, Serialize, Default)]
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>,
}
/// `POST /v1/completions` (non-streaming) response.
#[derive(Debug, Clone, Serialize)]
pub struct CompletionResponse {
pub id: String,
pub object: &'static str,
pub created: u64,
pub model: String,
pub choices: Vec<CompletionChoice>,
pub usage: Usage,
}
/// A single text-completion choice.
#[derive(Debug, Clone, Serialize)]
pub struct CompletionChoice {
pub text: String,
pub index: usize,
pub finish_reason: String,
}
/// A single embedding vector entry.
#[derive(Debug, Clone, Serialize)]
pub struct EmbeddingObject {
pub object: &'static str,
pub index: usize,
pub embedding: Vec<f32>,
}
/// `POST /v1/embeddings` response.
#[derive(Debug, Clone, Serialize)]
pub struct EmbeddingResponse {
pub object: &'static str,
pub data: Vec<EmbeddingObject>,
pub model: String,
pub usage: Usage,
}
/// OpenAI-style error envelope.
#[derive(Debug, Clone, Serialize)]
pub struct ErrorResponse {
pub error: ApiError,
}
/// OpenAI-style error body.
#[derive(Debug, Clone, Serialize)]
pub struct ApiError {
pub message: String,
#[serde(rename = "type")]
pub error_type: String,
#[serde(default)]
pub param: Option<String>,
#[serde(default)]
pub code: Option<String>,
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const SSE_DONE: &str = "data: [DONE]\n\n";
/// Map a finish reason to its OpenAI string.
pub fn finish_reason_str(r: FinishReason) -> &'static str {
match r {
FinishReason::Length => "length",
FinishReason::Stop => "stop",
FinishReason::Cancelled => "stop",
}
}
/// Flatten chat messages into a single prompt string.
pub fn prompt_from_messages(messages: &[ChatMessage]) -> String {
let mut s = String::new();
for m in messages {
s.push_str(&m.role);
s.push_str(": ");
s.push_str(&m.content);
s.push('\n');
}
s
}
fn now_secs() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
fn short_id() -> String {
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
format!("{:x}", nanos % 0xfffffffffffffff)
}
/// Format a chunk as an SSE `data:` event.
pub fn sse_event(chunk: &ChatCompletionChunk) -> String {
let json = serde_json::to_string(chunk).expect("chunk serializes");
format!("data: {json}\n\n")
}
/// Build an error SSE event from an API error.
pub fn sse_error(err: &ApiError) -> String {
let env = ErrorResponse { error: err.clone() };
let json = serde_json::to_string(&env).expect("error serializes");
format!("data: {json}\n\n")
}
/// Build a JSON error response string.
pub fn error_json(message: &str, error_type: &str, status: u16) -> (u16, String) {
let env = ErrorResponse {
error: ApiError {
message: message.to_string(),
error_type: error_type.to_string(),
param: None,
code: None,
},
};
(status, serde_json::to_string(&env).unwrap_or_default())
}
// ---------------------------------------------------------------------------
// Drivers
// ---------------------------------------------------------------------------
/// Stream chat-completion tokens as OpenAI SSE events.
///
/// The returned stream is `'static` (it owns an `Arc<Engine>`), so it can be
/// handed straight to a streaming HTTP response body.
pub fn chat_completion_stream(
engine: Arc<Engine>,
req: ChatCompletionRequest,
) -> impl futures::Stream<Item = Result<bytes::Bytes, anyhow::Error>> + 'static {
let model = req.model.clone();
let prompt = prompt_from_messages(&req.messages);
let tokens = MockModel::tokenize(&prompt);
let params = SamplingParams {
max_tokens: req.effective_max_tokens(),
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let id = format!("chatcmpl-{}", short_id());
let created = now_secs();
async_stream::stream! {
// First event carries the assistant role.
let role_chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: Some("assistant".into()), content: None },
finish_reason: None,
}],
};
yield Ok(bytes::Bytes::from(sse_event(&role_chunk)));
let mut rx = match engine.generate(&model, &tokens, params) {
Ok(rx) => rx,
Err(e) => {
let err = ApiError {
message: e.to_string(),
error_type: "server_error".into(),
param: None,
code: None,
};
yield Ok(bytes::Bytes::from(sse_error(&err)));
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
return;
}
};
let mut finished = false;
while let Some(tok) = rx.recv().await {
let finish_reason = tok.finish_reason.map(finish_reason_str).map(String::from);
finished = finish_reason.is_some();
let chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: Some(tok.text) },
finish_reason,
}],
};
yield Ok(bytes::Bytes::from(sse_event(&chunk)));
}
// Final event signals completion. If a stop token already ended the
// stream, no extra finish chunk is needed.
if !finished {
let done_chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: None },
finish_reason: Some("length".into()),
}],
};
yield Ok(bytes::Bytes::from(sse_event(&done_chunk)));
}
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
}
}
/// Produce a full (non-streaming) chat completion.
pub async fn chat_completion(
engine: Arc<Engine>,
req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, ModelError> {
let model = req.model.clone();
let prompt = prompt_from_messages(&req.messages);
let tokens = MockModel::tokenize(&prompt);
let prompt_tokens = tokens.len();
let params = SamplingParams {
max_tokens: req.effective_max_tokens(),
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let mut rx = engine.generate(&model, &tokens, params)?;
let mut content = String::new();
let mut finish = "length";
let mut completion_tokens = 0usize;
while let Some(tok) = rx.recv().await {
content.push_str(&tok.text);
completion_tokens += 1;
if let Some(r) = tok.finish_reason {
finish = finish_reason_str(r);
}
}
Ok(ChatCompletionResponse {
id: format!("chatcmpl-{}", short_id()),
object: "chat.completion",
created: now_secs(),
model,
choices: vec![ChatCompletionChoice {
index: 0,
message: ChatMessageOut { role: "assistant".into(), content, finish_reason: None },
finish_reason: finish.into(),
}],
usage: Usage {
prompt_tokens,
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
},
})
}
/// Stream text-completion tokens as OpenAI SSE events.
pub fn completion_stream(
engine: Arc<Engine>,
req: CompletionRequest,
) -> impl futures::Stream<Item = Result<bytes::Bytes, anyhow::Error>> + 'static {
let model = req.model.clone();
let tokens = MockModel::tokenize(&req.prompt);
let params = SamplingParams {
max_tokens: req.max_tokens,
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let id = format!("cmpl-{}", short_id());
let created = now_secs();
async_stream::stream! {
let mut rx = match engine.generate(&model, &tokens, params) {
Ok(rx) => rx,
Err(e) => {
let err = ApiError {
message: e.to_string(),
error_type: "server_error".into(),
param: None,
code: None,
};
yield Ok(bytes::Bytes::from(sse_error(&err)));
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
return;
}
};
let mut finished = false;
while let Some(tok) = rx.recv().await {
let finish_reason = tok.finish_reason.map(finish_reason_str).map(String::from);
finished = finish_reason.is_some();
let chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: Some(tok.text) },
finish_reason,
}],
};
yield Ok(bytes::Bytes::from(sse_event(&chunk)));
}
if !finished {
let done_chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: None },
finish_reason: Some("length".into()),
}],
};
yield Ok(bytes::Bytes::from(sse_event(&done_chunk)));
}
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
}
}
/// Produce a full (non-streaming) text completion.
pub async fn completion(
engine: Arc<Engine>,
req: CompletionRequest,
) -> Result<CompletionResponse, ModelError> {
let model = req.model.clone();
let tokens = MockModel::tokenize(&req.prompt);
let prompt_tokens = tokens.len();
let params = SamplingParams {
max_tokens: req.max_tokens,
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let mut rx = engine.generate(&model, &tokens, params)?;
let mut text = String::new();
let mut finish = "length";
let mut completion_tokens = 0usize;
while let Some(tok) = rx.recv().await {
text.push_str(&tok.text);
completion_tokens += 1;
if let Some(r) = tok.finish_reason {
finish = finish_reason_str(r);
}
}
Ok(CompletionResponse {
id: format!("cmpl-{}", short_id()),
object: "text_completion",
created: now_secs(),
model,
choices: vec![CompletionChoice { text, index: 0, finish_reason: finish.into() }],
usage: Usage {
prompt_tokens,
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
},
})
}
/// Produce embeddings for the request inputs (mock: deterministic from tokens).
pub fn embeddings(engine: &Engine, req: EmbeddingRequest) -> Result<EmbeddingResponse, ModelError> {
let _ = engine; // embeddings are model-independent in the mock path
let texts = req.input.into_texts();
let mut total_tokens = 0usize;
let data = texts
.into_iter()
.enumerate()
.map(|(i, text)| {
let tokens = MockModel::tokenize(&text);
total_tokens += tokens.len();
// Deterministic pseudo-embedding: normalize token ids.
let embedding: Vec<f32> = tokens.iter().map(|&t| (t as f32) / 1000.0 - 0.5).collect();
EmbeddingObject { object: "embedding", index: i, embedding }
})
.collect();
Ok(EmbeddingResponse {
object: "list",
data,
model: req.model,
usage: Usage { prompt_tokens: total_tokens, completion_tokens: 0, total_tokens },
})
}
// ---------------------------------------------------------------------------
// Scheduler-backed drivers
// ---------------------------------------------------------------------------
/// Produce a full (non-streaming) chat completion via the scheduler.
pub async fn scheduled_chat_completion(
engine: Arc<SchedulerEngine>,
req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, ModelError> {
let model = req.model.clone();
let prompt = prompt_from_messages(&req.messages);
let tokens = MockModel::tokenize(&prompt);
let prompt_tokens = tokens.len();
let params = SamplingParams {
max_tokens: req.effective_max_tokens(),
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let mut rx = engine.generate(&model, &tokens, params)?;
let mut content = String::new();
let mut finish = "length";
let mut completion_tokens = 0usize;
while let Some(tok) = rx.recv().await {
content.push_str(&tok.text);
completion_tokens += 1;
if let Some(r) = tok.finish_reason {
finish = finish_reason_str(r);
}
}
Ok(ChatCompletionResponse {
id: format!("chatcmpl-{}", short_id()),
object: "chat.completion",
created: now_secs(),
model,
choices: vec![ChatCompletionChoice {
index: 0,
message: ChatMessageOut { role: "assistant".into(), content, finish_reason: None },
finish_reason: finish.into(),
}],
usage: Usage {
prompt_tokens,
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
},
})
}
/// Stream chat-completion tokens as OpenAI SSE events via the scheduler.
pub fn scheduled_chat_completion_stream(
engine: Arc<SchedulerEngine>,
req: ChatCompletionRequest,
) -> impl futures::Stream<Item = Result<bytes::Bytes, anyhow::Error>> + 'static {
let model = req.model.clone();
let prompt = prompt_from_messages(&req.messages);
let tokens = MockModel::tokenize(&prompt);
let params = SamplingParams {
max_tokens: req.effective_max_tokens(),
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let id = format!("chatcmpl-{}", short_id());
let created = now_secs();
async_stream::stream! {
let role_chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: Some("assistant".into()), content: None },
finish_reason: None,
}],
};
yield Ok(bytes::Bytes::from(sse_event(&role_chunk)));
let mut rx = match engine.generate(&model, &tokens, params) {
Ok(rx) => rx,
Err(e) => {
let err = ApiError {
message: e.to_string(),
error_type: "server_error".into(),
param: None,
code: None,
};
yield Ok(bytes::Bytes::from(sse_error(&err)));
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
return;
}
};
let mut finished = false;
while let Some(tok) = rx.recv().await {
let finish_reason = tok.finish_reason.map(finish_reason_str).map(String::from);
if finish_reason.is_some() {
finished = true;
}
let chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: Some(tok.text) },
finish_reason,
}],
};
yield Ok(bytes::Bytes::from(sse_event(&chunk)));
}
if !finished {
let done_chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: None },
finish_reason: Some("length".into()),
}],
};
yield Ok(bytes::Bytes::from(sse_event(&done_chunk)));
}
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
}
}
/// Produce a full (non-streaming) text completion via the scheduler.
pub async fn scheduled_completion(
engine: Arc<SchedulerEngine>,
req: CompletionRequest,
) -> Result<CompletionResponse, ModelError> {
let model = req.model.clone();
let tokens = MockModel::tokenize(&req.prompt);
let prompt_tokens = tokens.len();
let params = SamplingParams {
max_tokens: req.max_tokens,
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let mut rx = engine.generate(&model, &tokens, params)?;
let mut text = String::new();
let mut finish = "length";
let mut completion_tokens = 0usize;
while let Some(tok) = rx.recv().await {
text.push_str(&tok.text);
completion_tokens += 1;
if let Some(r) = tok.finish_reason {
finish = finish_reason_str(r);
}
}
Ok(CompletionResponse {
id: format!("cmpl-{}", short_id()),
object: "text_completion",
created: now_secs(),
model,
choices: vec![CompletionChoice { text, index: 0, finish_reason: finish.into() }],
usage: Usage {
prompt_tokens,
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
},
})
}
/// Stream text-completion tokens as OpenAI SSE events via the scheduler.
pub fn scheduled_completion_stream(
engine: Arc<SchedulerEngine>,
req: CompletionRequest,
) -> impl futures::Stream<Item = Result<bytes::Bytes, anyhow::Error>> + 'static {
let model = req.model.clone();
let tokens = MockModel::tokenize(&req.prompt);
let params = SamplingParams {
max_tokens: req.max_tokens,
temperature: req.temperature.unwrap_or(1.0),
top_p: req.top_p.unwrap_or(1.0),
..Default::default()
};
let id = format!("cmpl-{}", short_id());
let created = now_secs();
async_stream::stream! {
let mut rx = match engine.generate(&model, &tokens, params) {
Ok(rx) => rx,
Err(e) => {
let err = ApiError {
message: e.to_string(),
error_type: "server_error".into(),
param: None,
code: None,
};
yield Ok(bytes::Bytes::from(sse_error(&err)));
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
return;
}
};
let mut finished = false;
while let Some(tok) = rx.recv().await {
let finish_reason = tok.finish_reason.map(finish_reason_str).map(String::from);
if finish_reason.is_some() {
finished = true;
}
let chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: Some(tok.text) },
finish_reason,
}],
};
yield Ok(bytes::Bytes::from(sse_event(&chunk)));
}
if !finished {
let done_chunk = ChatCompletionChunk {
id: id.clone(),
object: "chat.completion.chunk",
created,
model: model.clone(),
choices: vec![ChunkChoice {
index: 0,
delta: Delta { role: None, content: None },
finish_reason: Some("length".into()),
}],
};
yield Ok(bytes::Bytes::from(sse_event(&done_chunk)));
}
yield Ok(bytes::Bytes::from_static(SSE_DONE.as_bytes()));
}
}
/// List models registered in the engine.
pub fn model_list(engine: &Engine) -> ModelList {
let data = engine
.list_models()
.into_iter()
.map(|id| ModelObject {
id,
object: "model",
created: now_secs(),
owned_by: "justapi".into(),
permission: vec![ModelPermission::default()],
root: None,
parent: None,
})
.collect();
ModelList { object: "list", data }
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::EngineDevice;
use crate::model::FinishReason;
use futures::StreamExt;
fn test_engine() -> Arc<Engine> {
let engine = Arc::new(Engine::new(EngineDevice::Cpu).unwrap());
engine.register_mock("mock");
engine
}
fn chat_req(stream: bool) -> ChatCompletionRequest {
ChatCompletionRequest {
model: "mock".into(),
messages: vec![ChatMessage {
role: "user".into(),
content: "hello world".into(),
name: None,
}],
temperature: Some(0.0),
max_tokens: 10,
max_completion_tokens: None,
top_p: None,
stream,
stop: None,
user: None,
}
}
#[test]
fn protocol_types_roundtrip() {
let req = chat_req(false);
let json = serde_json::to_string(&req).unwrap();
let back: ChatCompletionRequest = serde_json::from_str(&json).unwrap();
assert_eq!(back.model, "mock");
assert_eq!(back.messages.len(), 1);
}
#[tokio::test]
async fn chat_completion_non_streaming() {
let engine = test_engine();
let resp = chat_completion(engine, chat_req(false)).await.unwrap();
assert_eq!(resp.object, "chat.completion");
assert_eq!(resp.choices.len(), 1);
assert_eq!(resp.choices[0].message.role, "assistant");
assert!(!resp.choices[0].message.content.is_empty());
assert_eq!(resp.choices[0].finish_reason, "length");
assert!(resp.usage.total_tokens > 0);
}
#[tokio::test]
async fn chat_completion_streaming_format() {
let engine = test_engine();
let mut stream = Box::pin(chat_completion_stream(engine, chat_req(true)));
// First event: role.
let first = stream.next().await.unwrap().unwrap();
let first = String::from_utf8(first.to_vec()).unwrap();
assert!(first.starts_with("data: "));
assert!(first.contains("\"role\":\"assistant\""));
// Subsequent events: content deltas, then finish, then [DONE].
let mut saw_content = false;
let mut saw_done = false;
while let Some(item) = stream.next().await {
let s = String::from_utf8(item.unwrap().to_vec()).unwrap();
if s.contains("\"content\"") {
saw_content = true;
}
if s == SSE_DONE {
saw_done = true;
}
}
assert!(saw_content);
assert!(saw_done);
}
#[tokio::test]
async fn text_completion_works() {
let engine = test_engine();
let req = CompletionRequest {
model: "mock".into(),
prompt: "hi".into(),
temperature: Some(0.0),
max_tokens: 8,
top_p: None,
stream: false,
stop: None,
};
let resp = completion(engine, req).await.unwrap();
assert_eq!(resp.object, "text_completion");
assert!(!resp.choices[0].text.is_empty());
}
#[test]
fn embeddings_work() {
let engine = test_engine();
let req = EmbeddingRequest {
model: "mock".into(),
input: EmbeddingInput::Many(vec!["a".into(), "bb".into()]),
encoding_format: None,
};
let resp = embeddings(&engine, req).unwrap();
assert_eq!(resp.data.len(), 2);
assert_eq!(resp.data[0].embedding.len(), 1);
assert_eq!(resp.data[1].embedding.len(), 2);
}
#[test]
fn model_list_reflects_registry() {
let engine = test_engine();
let list = model_list(&engine);
assert_eq!(list.object, "list");
assert!(list.data.iter().any(|m| m.id == "mock"));
}
#[test]
fn finish_reason_mapping() {
assert_eq!(finish_reason_str(FinishReason::Stop), "stop");
assert_eq!(finish_reason_str(FinishReason::Length), "length");
assert_eq!(finish_reason_str(FinishReason::Cancelled), "stop");
}
#[test]
fn prompt_from_messages_flattened() {
let prompt = prompt_from_messages(&[
ChatMessage { role: "system".into(), content: "be nice".into(), name: None },
ChatMessage { role: "user".into(), content: "hi".into(), name: None },
]);
assert!(prompt.contains("system: be nice"));
assert!(prompt.contains("user: hi"));
}
}