1use std::{
27 convert::Infallible,
28 net::SocketAddr,
29 sync::{
30 atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
31 Arc,
32 },
33 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
34};
35
36use axum::{
37 extract::{rejection::JsonRejection, DefaultBodyLimit, Request, State},
38 http::{HeaderMap, StatusCode},
39 middleware::{self, Next},
40 response::{
41 sse::{Event, KeepAlive, Sse},
42 IntoResponse, Response,
43 },
44 routing::{get, post},
45 Json, Router,
46};
47use infr_core::config::Config;
48use infr_engine::{ChatMessage, Delta, ToolCall};
49use serde::{Deserialize, Serialize};
50use subtle::ConstantTimeEq;
51use tokio::sync::Semaphore;
52
53mod completions;
54mod host;
55mod logprobs;
56mod metrics;
57mod status;
58
59pub use logprobs::{ChatLogprobs, ChatTokenLogprob, ChatTokenLogprobAlt, LogprobStops, TokenText};
60pub use status::{DeviceMemory, GeneratorStatus};
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum Finish {
66 Stop,
68 Length,
70 ToolCalls,
72}
73
74impl Finish {
75 pub fn as_str(self) -> &'static str {
76 match self {
77 Finish::Stop => "stop",
78 Finish::Length => "length",
79 Finish::ToolCalls => "tool_calls",
80 }
81 }
82}
83
84pub trait ChatGenerator: Send + Sync {
101 fn chat(
119 &self,
120 messages: &[ChatMessage],
121 tools: Option<&serde_json::Value>,
122 tool_choice: Option<&str>,
123 params: &GenParams,
124 cancel: &Arc<AtomicBool>,
125 on_delta: &mut dyn FnMut(Delta),
126 ) -> anyhow::Result<ChatOutcome>;
127
128 fn complete(
137 &self,
138 _prompt: &str,
139 _params: &GenParams,
140 _cancel: &Arc<AtomicBool>,
141 _on_text: &mut dyn FnMut(&str),
142 ) -> anyhow::Result<ChatOutcome> {
143 Err(ParamError {
144 param: "model",
145 message: "this model does not support text completions".into(),
146 }
147 .into())
148 }
149
150 fn prepare_completion(&self, _prompt: &str) -> anyhow::Result<Option<(u32, Option<u32>)>> {
155 Ok(None)
156 }
157
158 fn complete_with_logprobs(
162 &self,
163 prompt: &str,
164 params: &GenParams,
165 cancel: &Arc<AtomicBool>,
166 on_text: &mut dyn FnMut(&str),
167 _on_logprob: &mut dyn FnMut(infr_engine::TokenLogprob),
168 ) -> anyhow::Result<ChatOutcome> {
169 if params.logprobs {
170 return Err(ParamError {
171 param: "logprobs",
172 message: "logprobs: returning log probabilities is not supported by this backend"
173 .into(),
174 }
175 .into());
176 }
177 self.complete(prompt, params, cancel, on_text)
178 }
179
180 fn status(&self) -> GeneratorStatus;
185
186 fn supports_logprobs(&self) -> bool {
189 false
190 }
191
192 fn vocab_size(&self) -> usize;
199
200 fn prepare(
215 &self,
216 _messages: &[ChatMessage],
217 _tools: Option<&serde_json::Value>,
218 _tool_choice: Option<&str>,
219 _params: &GenParams,
220 ) -> anyhow::Result<Option<PreparedRequest>> {
221 Ok(None)
222 }
223
224 #[allow(clippy::too_many_arguments)]
228 fn chat_prepared(
229 &self,
230 prepared: PreparedRequest,
231 messages: &[ChatMessage],
232 tools: Option<&serde_json::Value>,
233 tool_choice: Option<&str>,
234 params: &GenParams,
235 cancel: &Arc<AtomicBool>,
236 on_delta: &mut dyn FnMut(Delta),
237 ) -> anyhow::Result<ChatOutcome> {
238 drop(prepared);
239 self.chat(messages, tools, tool_choice, params, cancel, on_delta)
240 }
241}
242
243pub struct PreparedRequest {
247 pub prompt_tokens: u32,
249 pub context_length: Option<u32>,
252 state: Box<dyn std::any::Any + Send>,
253}
254
255impl PreparedRequest {
256 pub fn new(
258 prompt_tokens: u32,
259 context_length: Option<u32>,
260 state: impl std::any::Any + Send,
261 ) -> Self {
262 Self {
263 prompt_tokens,
264 context_length,
265 state: Box::new(state),
266 }
267 }
268
269 pub fn into_state<T: std::any::Any>(self) -> Option<T> {
272 self.state.downcast::<T>().ok().map(|b| *b)
273 }
274}
275
276impl std::fmt::Debug for PreparedRequest {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 f.debug_struct("PreparedRequest")
279 .field("prompt_tokens", &self.prompt_tokens)
280 .field("context_length", &self.context_length)
281 .finish_non_exhaustive()
282 }
283}
284
285#[allow(clippy::too_many_arguments)]
288fn generate(
289 engine: &dyn ChatGenerator,
290 prepared: Option<PreparedRequest>,
291 messages: &[ChatMessage],
292 tools: Option<&serde_json::Value>,
293 tool_choice: Option<&str>,
294 params: &GenParams,
295 cancel: &Arc<AtomicBool>,
296 on_delta: &mut dyn FnMut(Delta),
297) -> anyhow::Result<ChatOutcome> {
298 match prepared {
299 Some(p) => engine.chat_prepared(p, messages, tools, tool_choice, params, cancel, on_delta),
300 None => engine.chat(messages, tools, tool_choice, params, cancel, on_delta),
301 }
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct ChatOutcome {
309 pub finish: Finish,
310 pub prompt_tokens: u32,
313 pub completion_tokens: u32,
314 pub cached_tokens: u32,
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
324pub struct ContextLengthExceeded {
325 pub message: String,
327}
328
329impl ContextLengthExceeded {
330 pub fn prompt_too_long(input: &str, context_length: usize, prompt_tokens: usize) -> Self {
334 Self {
335 message: format!(
336 "This model's maximum context length is {context_length} tokens. However, your \
337 {input} resulted in {prompt_tokens} tokens. Please reduce the length of the \
338 {input}."
339 ),
340 }
341 }
342
343 pub fn reply_too_long(
348 input: &str,
349 context_length: usize,
350 prompt_tokens: usize,
351 reply_tokens: usize,
352 can_lower_reply: bool,
353 ) -> Self {
354 let advice = if can_lower_reply {
355 format!("Please reduce the length of the {input} or completion.")
356 } else {
357 format!("Please reduce the length of the {input}.")
358 };
359 Self {
360 message: format!(
361 "This model's maximum context length is {context_length} tokens. However, you \
362 requested {} tokens ({prompt_tokens} in the {input}, {reply_tokens} in the \
363 completion). {advice}",
364 prompt_tokens + reply_tokens
365 ),
366 }
367 }
368}
369
370impl std::fmt::Display for ContextLengthExceeded {
371 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 f.write_str(&self.message)
373 }
374}
375
376impl std::error::Error for ContextLengthExceeded {}
377
378#[derive(Debug, Deserialize)]
389pub struct ChatRequest {
390 pub model: String,
391 pub messages: Vec<ChatMessageDto>,
392 #[serde(default)]
393 pub stream: bool,
394 #[serde(default)]
395 pub tools: Option<serde_json::Value>,
396 #[serde(default)]
399 pub tool_choice: Option<serde_json::Value>,
400 #[serde(default, deserialize_with = "minus_one_is_unset")]
404 pub max_tokens: Option<u32>,
405 #[serde(default, deserialize_with = "minus_one_is_unset")]
407 pub max_completion_tokens: Option<u32>,
408 #[serde(default)]
409 pub temperature: Option<f32>,
410 #[serde(default)]
411 pub top_p: Option<f32>,
412 #[serde(default)]
414 pub top_k: Option<i64>,
415 #[serde(default, deserialize_with = "minus_one_is_unset")]
416 pub seed: Option<u64>,
417 #[serde(default)]
419 pub stop: Option<serde_json::Value>,
420 #[serde(default)]
421 pub presence_penalty: Option<f32>,
422 #[serde(default)]
423 pub frequency_penalty: Option<f32>,
424 #[serde(default)]
426 pub repeat_penalty: Option<f32>,
427 #[serde(default)]
429 pub min_p: Option<f32>,
430 #[serde(default)]
433 pub logit_bias: Option<LogitBiasArg>,
434 #[serde(default)]
437 pub n: Option<serde_json::Value>,
438 #[serde(default)]
440 pub logprobs: Option<bool>,
441 #[serde(default)]
444 pub top_logprobs: Option<serde_json::Value>,
445 #[serde(default)]
447 pub stream_options: Option<StreamOptions>,
448 #[serde(default)]
451 pub response_format: Option<serde_json::Value>,
452}
453
454#[derive(Debug, Clone, PartialEq)]
482pub enum ResponseFormat {
483 JsonObject,
485 JsonSchema(serde_json::Value),
490}
491
492impl ResponseFormat {
493 pub fn schema(&self) -> serde_json::Value {
495 match self {
496 ResponseFormat::JsonObject => serde_json::json!({"type": "object"}),
497 ResponseFormat::JsonSchema(schema) => schema.clone(),
498 }
499 }
500
501 fn from_request(v: Option<&serde_json::Value>) -> Result<Option<Self>, ParamError> {
504 let bad = |message: String| ParamError {
505 param: "response_format",
506 message,
507 };
508 let Some(v) = v.filter(|v| !v.is_null()) else {
509 return Ok(None);
510 };
511 let kind = v
512 .get("type")
513 .and_then(serde_json::Value::as_str)
514 .ok_or_else(|| bad("response_format must be an object with a string `type`".into()))?;
515 let schema_at = |v: Option<&serde_json::Value>, path: &str| match v {
517 None | Some(serde_json::Value::Null) => Ok(None),
518 Some(s) if s.is_object() => Ok(Some(s.clone())),
519 _ => Err(bad(format!("{path} must be a JSON schema object"))),
520 };
521 match kind {
522 "text" => Ok(None),
523 "json_object" => Ok(Some(
524 match schema_at(v.get("schema"), "response_format.schema")? {
525 Some(s) => Self::JsonSchema(s),
526 None => Self::JsonObject,
527 },
528 )),
529 "json_schema" => {
530 let wrapper = v.get("json_schema").filter(|j| !j.is_null());
531 if wrapper.is_some_and(|j| !j.is_object()) {
532 return Err(bad("response_format.json_schema must be an object".into()));
533 }
534 let schema = schema_at(
535 wrapper.and_then(|j| j.get("schema")),
536 "response_format.json_schema.schema",
537 )?;
538 Ok(Some(Self::JsonSchema(
539 schema.unwrap_or_else(|| serde_json::json!({})),
540 )))
541 }
542 other => Err(bad(format!(
543 "response_format type must be \"text\", \"json_object\" or \"json_schema\", \
544 got {other:?}"
545 ))),
546 }
547 }
548}
549
550#[derive(Debug, Clone)]
554pub enum LogitBiasArg {
555 Entries(Vec<(String, serde_json::Value)>),
556 NotAnObject(&'static str),
558}
559
560impl<'de> Deserialize<'de> for LogitBiasArg {
561 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
562 struct V;
563 impl<'de> serde::de::Visitor<'de> for V {
564 type Value = LogitBiasArg;
565
566 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
567 f.write_str("a JSON value")
568 }
569
570 fn visit_map<A: serde::de::MapAccess<'de>>(
571 self,
572 mut m: A,
573 ) -> Result<Self::Value, A::Error> {
574 let mut entries = Vec::new();
575 while let Some(entry) = m.next_entry::<String, serde_json::Value>()? {
576 entries.push(entry);
577 }
578 Ok(LogitBiasArg::Entries(entries))
579 }
580
581 fn visit_seq<A: serde::de::SeqAccess<'de>>(
582 self,
583 mut s: A,
584 ) -> Result<Self::Value, A::Error> {
585 while s.next_element::<serde::de::IgnoredAny>()?.is_some() {}
586 Ok(LogitBiasArg::NotAnObject("array"))
587 }
588
589 fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {
590 Ok(LogitBiasArg::NotAnObject("boolean"))
591 }
592
593 fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {
594 Ok(LogitBiasArg::NotAnObject("number"))
595 }
596
597 fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {
598 Ok(LogitBiasArg::NotAnObject("number"))
599 }
600
601 fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {
602 Ok(LogitBiasArg::NotAnObject("number"))
603 }
604
605 fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {
606 Ok(LogitBiasArg::NotAnObject("string"))
607 }
608 }
609 d.deserialize_any(V)
610 }
611}
612
613#[derive(Debug, Default, Deserialize)]
616pub struct StreamOptions {
617 #[serde(default)]
618 pub include_usage: bool,
619}
620
621fn minus_one_is_unset<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
625where
626 D: serde::Deserializer<'de>,
627 T: TryFrom<u64>,
628{
629 use serde::de::Error;
630 match Option::<i128>::deserialize(d)? {
631 None | Some(-1) => Ok(None),
632 Some(v) => u64::try_from(v)
633 .ok()
634 .and_then(|v| T::try_from(v).ok())
635 .map(Some)
636 .ok_or_else(|| D::Error::custom(format!("{v} is out of range (use -1 for unset)"))),
637 }
638}
639
640#[derive(Debug, Clone, Default, PartialEq)]
644pub struct GenParams {
645 pub max_tokens: Option<u32>,
646 pub temperature: Option<f32>,
647 pub top_p: Option<f32>,
648 pub top_k: Option<usize>,
649 pub seed: Option<u64>,
650 pub presence_penalty: Option<f32>,
651 pub frequency_penalty: Option<f32>,
652 pub repeat_penalty: Option<f32>,
653 pub min_p: Option<f32>,
654 pub logit_bias: Vec<(u32, f32)>,
657 pub logprobs: bool,
659 pub top_logprobs: usize,
663 pub stop: Vec<String>,
665 pub response_format: Option<ResponseFormat>,
668}
669
670#[derive(Debug, Clone, PartialEq)]
676pub struct ParamError {
677 pub param: &'static str,
678 pub message: String,
679}
680
681impl std::fmt::Display for ParamError {
682 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683 f.write_str(&self.message)
684 }
685}
686
687impl std::error::Error for ParamError {}
688
689impl ParamError {
690 pub fn empty_prompt() -> Self {
693 Self {
694 param: "prompt",
695 message: "prompt is empty; send at least one token of text".into(),
696 }
697 }
698}
699
700const MAX_TOP_LOGPROBS: usize = 20;
702
703impl GenParams {
704 pub fn from_request(req: &ChatRequest) -> Result<Self, ParamError> {
710 let unsupported = |param: &'static str, what: &str| ParamError {
711 param,
712 message: format!("{param}: {what} is not supported by this server"),
713 };
714 match whole_number("n", req.n.as_ref())? {
715 None | Some(1) => {}
716 Some(n) if n < 1 => {
717 return Err(ParamError {
718 param: "n",
719 message: format!("n must be >= 1, got {n}"),
720 })
721 }
722 Some(n) => return Err(unsupported("n", &format!("returning {n} choices"))),
723 }
724 let logprobs = req.logprobs.unwrap_or(false);
725 let top_logprobs = match whole_number("top_logprobs", req.top_logprobs.as_ref())? {
728 None if logprobs => MAX_TOP_LOGPROBS,
729 None | Some(0) => 0,
730 Some(k) if k < 0 => {
731 return Err(ParamError {
732 param: "top_logprobs",
733 message: format!("top_logprobs must be >= 0, got {k}"),
734 })
735 }
736 Some(k) if k > MAX_TOP_LOGPROBS as i64 => {
737 return Err(ParamError {
738 param: "top_logprobs",
739 message: format!("top_logprobs must be at most {MAX_TOP_LOGPROBS}, got {k}"),
740 })
741 }
742 Some(k) => k as usize,
743 };
744 if top_logprobs > 0 && !logprobs {
745 return Err(ParamError {
746 param: "top_logprobs",
747 message: "top_logprobs requires logprobs to be set to true".into(),
748 });
749 }
750
751 let rng = |param: &'static str,
752 v: Option<f32>,
753 lo: f32,
754 hi: f32|
755 -> Result<Option<f32>, ParamError> {
756 match v {
757 Some(x) if !x.is_finite() || x < lo || x > hi => Err(ParamError {
758 param,
759 message: format!("{param} must be between {lo} and {hi}, got {x}"),
760 }),
761 other => Ok(other),
762 }
763 };
764
765 let top_k = match req.top_k {
766 Some(k) if k < 0 => {
768 return Err(ParamError {
769 param: "top_k",
770 message: format!("top_k must be >= 0, got {k}"),
771 })
772 }
773 Some(k) => Some(k as usize),
774 None => None,
775 };
776
777 let stop = match &req.stop {
778 None | Some(serde_json::Value::Null) => Vec::new(),
779 Some(serde_json::Value::String(s)) => vec![s.clone()],
780 Some(serde_json::Value::Array(a)) => {
781 let mut v = Vec::with_capacity(a.len());
782 for item in a {
783 match item.as_str() {
784 Some(s) => v.push(s.to_string()),
785 None => {
786 return Err(ParamError {
787 param: "stop",
788 message: "stop must be a string or an array of strings".into(),
789 })
790 }
791 }
792 }
793 v
794 }
795 Some(_) => {
796 return Err(ParamError {
797 param: "stop",
798 message: "stop must be a string or an array of strings".into(),
799 })
800 }
801 };
802 if stop.len() > 4 {
803 return Err(ParamError {
804 param: "stop",
805 message: format!("at most 4 stop sequences are supported, got {}", stop.len()),
806 });
807 }
808 let stop: Vec<String> = stop.into_iter().filter(|s| !s.is_empty()).collect();
810
811 if let Some(p) = req.repeat_penalty {
812 if !p.is_finite() || p <= 0.0 {
813 return Err(ParamError {
814 param: "repeat_penalty",
815 message: format!("repeat_penalty must be > 0, got {p}"),
816 });
817 }
818 }
819
820 let logit_bias = parse_logit_bias(req.logit_bias.as_ref())?;
821
822 Ok(Self {
823 max_tokens: req.max_completion_tokens.or(req.max_tokens),
825 temperature: rng("temperature", req.temperature, 0.0, 2.0)?,
826 top_p: rng("top_p", req.top_p, 0.0, 1.0)?,
827 top_k,
828 seed: req.seed,
829 presence_penalty: rng("presence_penalty", req.presence_penalty, -2.0, 2.0)?,
830 frequency_penalty: rng("frequency_penalty", req.frequency_penalty, -2.0, 2.0)?,
831 repeat_penalty: req.repeat_penalty,
832 min_p: rng("min_p", req.min_p, 0.0, 1.0)?,
833 logit_bias,
834 logprobs,
835 top_logprobs,
836 stop,
837 response_format: ResponseFormat::from_request(req.response_format.as_ref())?,
838 })
839 }
840
841 pub fn check_vocab(&self, vocab: usize) -> Result<(), ParamError> {
844 match self.logit_bias.iter().find(|&&(t, _)| t as usize >= vocab) {
845 Some(&(t, _)) => Err(ParamError {
846 param: "logit_bias",
847 message: format!(
848 "logit_bias names token {t}, but the model's vocabulary has {vocab} tokens"
849 ),
850 }),
851 None => Ok(()),
852 }
853 }
854}
855
856fn whole_number(
861 param: &'static str,
862 v: Option<&serde_json::Value>,
863) -> Result<Option<i64>, ParamError> {
864 let Some(v) = v.filter(|v| !v.is_null()) else {
865 return Ok(None);
866 };
867 if let Some(i) = v.as_i64() {
868 return Ok(Some(i));
869 }
870 if let Some(u) = v.as_u64() {
871 return Ok(Some(i64::try_from(u).unwrap_or(i64::MAX)));
873 }
874 match v.as_f64() {
875 Some(f) if f.fract() == 0.0 && (i64::MIN as f64..=i64::MAX as f64).contains(&f) => {
876 Ok(Some(f as i64))
877 }
878 _ => Err(ParamError {
879 param,
880 message: format!("{param} must be an integer, got {v}"),
881 }),
882 }
883}
884
885const LOGIT_BIAS_LIMIT: f64 = 100.0;
887
888fn parse_logit_bias(v: Option<&LogitBiasArg>) -> Result<Vec<(u32, f32)>, ParamError> {
895 let err = |message: String| ParamError {
896 param: "logit_bias",
897 message,
898 };
899 let entries = match v {
900 None => return Ok(Vec::new()),
901 Some(LogitBiasArg::Entries(e)) => e,
902 Some(LogitBiasArg::NotAnObject(t)) => {
903 return Err(err(format!(
904 "logit_bias must be an object mapping token ids to biases, got a {t}"
905 )))
906 }
907 };
908 let mut out = Vec::with_capacity(entries.len());
909 for (key, val) in entries {
910 let canonical = key.bytes().all(|b| b.is_ascii_digit())
911 && (key == "0" || (!key.is_empty() && !key.starts_with('0')));
912 let id: u32 = canonical
913 .then(|| key.parse().ok())
914 .flatten()
915 .ok_or_else(|| {
916 err(format!(
917 "logit_bias key {key:?} is not a token id (a non-negative integer written \
918 without sign or leading zeros)"
919 ))
920 })?;
921 let bias = val
922 .as_f64()
923 .ok_or_else(|| err(format!("logit_bias for token {id} must be a number")))?;
924 if !(-LOGIT_BIAS_LIMIT..=LOGIT_BIAS_LIMIT).contains(&bias) {
925 return Err(err(format!(
926 "logit_bias for token {id} must be between -{LOGIT_BIAS_LIMIT} and \
927 {LOGIT_BIAS_LIMIT}, got {bias}"
928 )));
929 }
930 out.push((id, bias as f32));
931 }
932 out.sort_by_key(|&(id, _)| id);
933 if let Some(w) = out.windows(2).find(|w| w[0].0 == w[1].0) {
934 return Err(err(format!("logit_bias names token {} twice", w[0].0)));
935 }
936 Ok(out)
937}
938
939#[derive(Debug, Default)]
957pub struct StopMatcher {
958 stops: Vec<String>,
959 held: String,
961 hit: bool,
962}
963
964impl StopMatcher {
965 pub fn new(stops: Vec<String>) -> Self {
966 Self {
967 stops: stops.into_iter().filter(|s| !s.is_empty()).collect(),
968 held: String::new(),
969 hit: false,
970 }
971 }
972
973 pub fn is_active(&self) -> bool {
974 !self.stops.is_empty()
975 }
976
977 pub fn hit(&self) -> bool {
979 self.hit
980 }
981
982 pub fn push(&mut self, piece: &str) -> String {
984 if self.hit {
985 return String::new();
986 }
987 if self.stops.is_empty() {
988 return piece.to_string();
989 }
990 self.held.push_str(piece);
991
992 if let Some(cut) = self
994 .stops
995 .iter()
996 .filter_map(|s| self.held.find(s.as_str()))
997 .min()
998 {
999 self.hit = true;
1000 let out = self.held[..cut].to_string();
1001 self.held.clear();
1002 return out;
1003 }
1004
1005 let hold = self.longest_partial_suffix();
1007 let split = self.held.len() - hold;
1008 let out = self.held[..split].to_string();
1009 self.held.drain(..split);
1010 out
1011 }
1012
1013 pub fn flush(&mut self) -> String {
1015 if self.hit {
1016 return String::new();
1017 }
1018 std::mem::take(&mut self.held)
1019 }
1020
1021 fn longest_partial_suffix(&self) -> usize {
1025 let max = self
1026 .stops
1027 .iter()
1028 .map(|s| s.len())
1029 .max()
1030 .unwrap_or(0)
1031 .saturating_sub(1)
1032 .min(self.held.len());
1033 for n in (1..=max).rev() {
1034 let start = self.held.len() - n;
1035 if !self.held.is_char_boundary(start) {
1036 continue;
1037 }
1038 let tail = &self.held[start..];
1039 if self
1040 .stops
1041 .iter()
1042 .any(|s| s.as_bytes().starts_with(tail.as_bytes()))
1043 {
1044 return n;
1045 }
1046 }
1047 0
1048 }
1049}
1050
1051fn tool_choice_str(v: &serde_json::Value) -> Result<Option<String>, ParamError> {
1059 match v {
1060 serde_json::Value::String(s) => Ok(Some(s.clone())),
1061 serde_json::Value::Object(_) => v
1062 .get("function")
1063 .and_then(|f| f.get("name"))
1064 .and_then(|n| n.as_str())
1065 .map(|s| Some(s.to_owned()))
1066 .ok_or_else(|| ParamError {
1067 param: "tool_choice",
1068 message: "tool_choice object must have a string `function.name`".into(),
1069 }),
1070 _ => Err(ParamError {
1071 param: "tool_choice",
1072 message: "tool_choice must be \"auto\"/\"required\"/\"none\" or a function object"
1073 .into(),
1074 }),
1075 }
1076}
1077
1078const TOOL_CHOICE_POLICIES: [&str; 3] = ["auto", "none", "required"];
1080
1081fn validate_tools(tools: Option<&serde_json::Value>) -> Result<(), ParamError> {
1085 let bad = |message: String| ParamError {
1086 param: "tools",
1087 message,
1088 };
1089 let tools = match tools {
1090 None | Some(serde_json::Value::Null) => return Ok(()),
1091 Some(serde_json::Value::Array(a)) => a,
1092 Some(_) => return Err(bad("tools must be an array".into())),
1093 };
1094 for (i, t) in tools.iter().enumerate() {
1095 if t.get("function")
1096 .and_then(|f| f.get("name"))
1097 .and_then(serde_json::Value::as_str)
1098 .is_none()
1099 {
1100 return Err(bad(format!("tools[{i}] has no string `function.name`")));
1101 }
1102 }
1103 Ok(())
1104}
1105
1106fn validate_tool_choice(
1126 tool_choice: Option<&str>,
1127 tools: Option<&serde_json::Value>,
1128) -> Result<(), ParamError> {
1129 let Some(choice) = tool_choice else {
1130 return Ok(());
1131 };
1132 if TOOL_CHOICE_POLICIES.contains(&choice) && choice != "required" {
1133 return Ok(());
1134 }
1135 let names: Vec<&str> = tools
1137 .and_then(|t| t.as_array())
1138 .map(|a| {
1139 a.iter()
1140 .filter_map(|t| t.get("function")?.get("name")?.as_str())
1141 .collect()
1142 })
1143 .unwrap_or_default();
1144 if names.is_empty() {
1145 return Err(ParamError {
1146 param: "tool_choice",
1147 message: format!(
1148 "tool_choice {choice:?} requires a non-empty `tools` array; none was supplied"
1149 ),
1150 });
1151 }
1152 if choice == "required" || names.contains(&choice) {
1153 return Ok(());
1154 }
1155 Err(ParamError {
1156 param: "tool_choice",
1157 message: format!(
1158 "tool_choice {choice:?} names no tool in `tools` (have: {})",
1159 names.join(", ")
1160 ),
1161 })
1162}
1163
1164#[derive(Debug, Deserialize, Serialize)]
1166pub struct ChatMessageDto {
1167 pub role: String,
1168 #[serde(default)]
1169 pub content: Option<serde_json::Value>,
1170 #[serde(default)]
1173 pub tool_calls: Option<serde_json::Value>,
1174 #[serde(default)]
1175 pub tool_call_id: Option<String>,
1176 #[serde(default)]
1177 pub name: Option<String>,
1178}
1179
1180#[derive(Debug, Serialize)]
1185pub struct ModelsResponse {
1186 pub object: &'static str,
1187 pub data: Vec<ModelCard>,
1188}
1189
1190#[derive(Debug, Serialize)]
1191pub struct ModelCard {
1192 pub id: String,
1193 pub object: &'static str,
1194 pub owned_by: &'static str,
1195}
1196
1197#[derive(Debug, Serialize)]
1202pub struct ChatCompletionResponse {
1203 pub id: String,
1204 pub object: &'static str,
1205 pub created: i64,
1206 pub model: String,
1207 pub choices: Vec<CompletionChoice>,
1208 pub usage: UsageInfo,
1209}
1210
1211#[derive(Debug, Serialize)]
1212pub struct CompletionChoice {
1213 pub index: u32,
1214 pub message: AssistantMessage,
1215 #[serde(skip_serializing_if = "Option::is_none")]
1216 pub logprobs: Option<ChatLogprobs>,
1217 pub finish_reason: String,
1218}
1219
1220#[derive(Debug, Serialize)]
1221pub struct AssistantMessage {
1222 pub role: &'static str,
1223 pub content: Option<String>,
1224 #[serde(skip_serializing_if = "Option::is_none")]
1225 pub reasoning_content: Option<String>,
1226 #[serde(skip_serializing_if = "Option::is_none")]
1227 pub tool_calls: Option<Vec<OAIToolCall>>,
1228}
1229
1230#[derive(Debug, Clone, Serialize)]
1232pub struct OAIToolCall {
1233 pub index: usize,
1234 pub id: String,
1235 #[serde(rename = "type")]
1236 pub kind: &'static str,
1237 pub function: OAIFunction,
1238}
1239
1240#[derive(Debug, Clone, Serialize)]
1241pub struct OAIFunction {
1242 pub name: String,
1243 pub arguments: String,
1244}
1245
1246#[derive(Debug, Serialize)]
1247pub struct UsageInfo {
1248 pub prompt_tokens: u32,
1249 pub completion_tokens: u32,
1250 pub total_tokens: u32,
1251 pub prompt_tokens_details: PromptTokensDetails,
1252}
1253
1254#[derive(Debug, Serialize)]
1255pub struct PromptTokensDetails {
1256 pub cached_tokens: u32,
1257}
1258
1259impl UsageInfo {
1260 pub fn from_outcome(outcome: &ChatOutcome) -> Self {
1263 Self {
1264 prompt_tokens: outcome.prompt_tokens,
1265 completion_tokens: outcome.completion_tokens,
1266 total_tokens: outcome
1267 .prompt_tokens
1268 .saturating_add(outcome.completion_tokens),
1269 prompt_tokens_details: PromptTokensDetails {
1270 cached_tokens: outcome.cached_tokens,
1271 },
1272 }
1273 }
1274}
1275
1276#[derive(Debug, Serialize)]
1281pub struct ChatCompletionChunk {
1282 pub id: String,
1283 pub object: &'static str,
1284 pub created: i64,
1285 pub model: String,
1286 pub choices: Vec<ChunkChoice>,
1287 #[serde(skip_serializing_if = "Option::is_none")]
1289 pub usage: Option<UsageInfo>,
1290}
1291
1292#[derive(Debug, Serialize)]
1293pub struct ChunkChoice {
1294 pub index: u32,
1295 pub delta: DeltaPayload,
1296 #[serde(skip_serializing_if = "Option::is_none")]
1297 pub logprobs: Option<ChatLogprobs>,
1298 pub finish_reason: Option<String>,
1299}
1300
1301#[derive(Debug, Default, Serialize)]
1303pub struct DeltaPayload {
1304 #[serde(skip_serializing_if = "Option::is_none")]
1305 pub role: Option<String>,
1306 #[serde(skip_serializing_if = "Option::is_none")]
1307 pub content: Option<String>,
1308 #[serde(skip_serializing_if = "Option::is_none")]
1309 pub reasoning_content: Option<String>,
1310 #[serde(skip_serializing_if = "Option::is_none")]
1311 pub tool_calls: Option<Vec<OAIToolCall>>,
1312}
1313
1314static REQ_SEQ: AtomicU64 = AtomicU64::new(1);
1327
1328fn next_req_id() -> u64 {
1329 REQ_SEQ.fetch_add(1, Ordering::Relaxed)
1330}
1331
1332#[derive(Debug, Default)]
1346struct ServeStats {
1347 interval_prompt_tokens: AtomicU64,
1350 interval_gen_tokens: AtomicI64,
1356 interval_completed: AtomicU64,
1358 interval_failed: AtomicU64,
1360 active: AtomicU64,
1362 queued: AtomicU64,
1364 window: AtomicU64,
1371 lifetime: metrics::Lifetime,
1373}
1374
1375impl ServeStats {
1376 fn bump_gen(&self, n: i64) {
1378 self.interval_gen_tokens.fetch_add(n, Ordering::Relaxed);
1379 }
1380
1381 fn window(&self) -> u64 {
1383 self.window.load(Ordering::Relaxed)
1384 }
1385
1386 fn fold_completion(&self, rec: &ReqRecord) {
1402 self.interval_prompt_tokens
1403 .fetch_add(u64::from(rec.prompt_tokens), Ordering::Relaxed);
1404 let correction = i64::from(rec.gen_tokens) - rec.deltas as i64;
1405 if correction > 0 {
1406 self.bump_gen(correction);
1407 } else if correction < 0 && rec.window == self.window() {
1408 let retractable = rec.deltas_in_window.min(i64::MAX as u64) as i64;
1410 self.bump_gen(-correction.abs().min(retractable));
1411 }
1412 self.interval_completed.fetch_add(1, Ordering::Relaxed);
1413 self.lifetime.fold_completion(rec);
1414 }
1415
1416 fn fold_failure(&self) {
1419 self.interval_completed.fetch_add(1, Ordering::Relaxed);
1420 self.interval_failed.fetch_add(1, Ordering::Relaxed);
1421 self.lifetime.fold_failure();
1422 }
1423
1424 fn drain(&self, elapsed: Duration) -> StatsWindow {
1428 self.window.fetch_add(1, Ordering::Relaxed);
1431 StatsWindow {
1432 elapsed,
1433 prompt_tokens: self.interval_prompt_tokens.swap(0, Ordering::Relaxed),
1434 gen_tokens: self.interval_gen_tokens.swap(0, Ordering::Relaxed).max(0) as u64,
1435 completed: self.interval_completed.swap(0, Ordering::Relaxed),
1436 failed: self.interval_failed.swap(0, Ordering::Relaxed),
1437 active: self.active.load(Ordering::Relaxed),
1438 queued: self.queued.load(Ordering::Relaxed),
1439 busy_slots: 0,
1440 total_slots: 0,
1441 }
1442 }
1443}
1444
1445#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1447struct StatsWindow {
1448 elapsed: Duration,
1449 prompt_tokens: u64,
1450 gen_tokens: u64,
1451 completed: u64,
1452 failed: u64,
1453 active: u64,
1454 queued: u64,
1455 busy_slots: u64,
1457 total_slots: u64,
1459}
1460
1461impl StatsWindow {
1462 fn has_activity(&self) -> bool {
1468 self.prompt_tokens > 0
1469 || self.gen_tokens > 0
1470 || self.completed > 0
1471 || self.active > 0
1472 || self.queued > 0
1473 }
1474
1475 fn prefill_tps(&self) -> f64 {
1483 per_second(self.prompt_tokens, self.elapsed)
1484 }
1485
1486 fn decode_tps(&self) -> f64 {
1489 per_second(self.gen_tokens, self.elapsed)
1490 }
1491}
1492
1493fn per_second(n: u64, d: Duration) -> f64 {
1496 let secs = d.as_secs_f64();
1497 if secs > 0.0 {
1498 n as f64 / secs
1499 } else {
1500 0.0
1501 }
1502}
1503
1504struct QueuedGuard(Arc<ServeStats>);
1511
1512impl QueuedGuard {
1513 fn new(stats: Arc<ServeStats>) -> Self {
1514 stats.queued.fetch_add(1, Ordering::Relaxed);
1515 Self(stats)
1516 }
1517}
1518
1519impl Drop for QueuedGuard {
1520 fn drop(&mut self) {
1521 self.0.queued.fetch_sub(1, Ordering::Relaxed);
1522 }
1523}
1524
1525struct ActiveGuard(Arc<ServeStats>);
1529
1530impl ActiveGuard {
1531 fn new(stats: Arc<ServeStats>) -> Self {
1532 stats.active.fetch_add(1, Ordering::Relaxed);
1533 Self(stats)
1534 }
1535}
1536
1537impl Drop for ActiveGuard {
1538 fn drop(&mut self) {
1539 self.0.active.fetch_sub(1, Ordering::Relaxed);
1540 }
1541}
1542
1543#[derive(Debug)]
1547struct ReqTally {
1548 started: Instant,
1549 first_delta: Option<Instant>,
1552 deltas: u64,
1554 window: u64,
1556 deltas_in_window: u64,
1559}
1560
1561impl ReqTally {
1562 fn new() -> Self {
1563 Self {
1564 started: Instant::now(),
1565 first_delta: None,
1566 deltas: 0,
1567 window: 0,
1568 deltas_in_window: 0,
1569 }
1570 }
1571
1572 fn on_text_delta(&mut self, stats: &ServeStats) {
1582 if self.first_delta.is_none() {
1583 self.first_delta = Some(Instant::now());
1584 }
1585 let w = stats.window();
1586 if w != self.window {
1587 self.window = w;
1588 self.deltas_in_window = 0;
1589 }
1590 self.deltas += 1;
1591 self.deltas_in_window += 1;
1592 stats.bump_gen(1);
1593 }
1594
1595 fn finish(&self, outcome: ChatOutcome, finish: Finish) -> ReqRecord {
1597 let total = self.started.elapsed();
1598 let prefill = self
1601 .first_delta
1602 .map_or(total, |t| t.saturating_duration_since(self.started));
1603 ReqRecord {
1604 prompt_tokens: outcome.prompt_tokens.saturating_sub(outcome.cached_tokens),
1607 gen_tokens: outcome.completion_tokens,
1608 deltas: self.deltas,
1609 window: self.window,
1610 deltas_in_window: self.deltas_in_window,
1611 prefill,
1612 decode: total.saturating_sub(prefill),
1613 total,
1614 finish,
1615 }
1616 }
1617}
1618
1619#[derive(Debug, Clone, Copy)]
1621struct ReqRecord {
1622 prompt_tokens: u32,
1623 gen_tokens: u32,
1624 deltas: u64,
1625 window: u64,
1627 deltas_in_window: u64,
1629 prefill: Duration,
1631 decode: Duration,
1633 total: Duration,
1634 finish: Finish,
1635}
1636
1637impl ReqRecord {
1638 fn prefill_tps(&self) -> f64 {
1641 per_second(u64::from(self.prompt_tokens), self.prefill)
1642 }
1643
1644 fn decode_tps(&self) -> f64 {
1646 per_second(u64::from(self.gen_tokens), self.decode)
1647 }
1648}
1649
1650fn log_request_done(req_id: u64, model: &str, stream: bool, rec: &ReqRecord) {
1653 tracing::info!(
1654 req = req_id,
1655 model,
1656 stream,
1657 prompt_tokens = rec.prompt_tokens,
1658 gen_tokens = rec.gen_tokens,
1659 prefill_tps = format_args!("{:.1}", rec.prefill_tps()),
1660 decode_tps = format_args!("{:.1}", rec.decode_tps()),
1661 total_ms = format_args!("{:.0}", rec.total.as_secs_f64() * 1000.0),
1662 finish = rec.finish.as_str(),
1663 "request done"
1664 );
1665}
1666
1667struct RequestStart<'a> {
1669 route: &'a str,
1671 model: &'a str,
1672 messages: usize,
1673 prompt_chars: usize,
1674 prompt_tokens: Option<u32>,
1675 max_tokens: Option<u32>,
1676 stream: bool,
1677}
1678
1679fn log_request_start(req_id: u64, start: RequestStart<'_>) {
1690 let RequestStart {
1691 route,
1692 model,
1693 messages,
1694 prompt_chars,
1695 prompt_tokens,
1696 max_tokens,
1697 stream,
1698 } = start;
1699 tracing::info!(
1700 req = req_id,
1701 route,
1702 model,
1703 messages,
1704 prompt_chars,
1705 prompt_tokens,
1707 max_tokens = ?max_tokens,
1708 stream,
1709 "request start"
1710 );
1711}
1712
1713fn stats_interval(cfg: &Config) -> Option<Duration> {
1720 let secs = cfg.serve.stats_interval_secs;
1721 (secs > 0).then(|| Duration::from_secs(secs))
1722}
1723
1724async fn stats_reporter(state: AppState, period: Duration) {
1733 const POLL: Duration = Duration::from_millis(50);
1734 let mut last = Instant::now();
1735 loop {
1736 tokio::time::sleep(POLL).await;
1737 let shutting_down = infr_core::shutdown::shutdown_requested();
1738 if !shutting_down && last.elapsed() < period {
1739 continue;
1740 }
1741 let mut window = state.stats.drain(last.elapsed());
1742 (window.busy_slots, window.total_slots) = state.slot_occupancy();
1743 last = Instant::now();
1744 if window.has_activity() {
1745 tracing::info!(
1746 interval_s = format_args!("{:.1}", window.elapsed.as_secs_f64()),
1747 prefill_tps = format_args!("{:.1}", window.prefill_tps()),
1748 decode_tps = format_args!("{:.1}", window.decode_tps()),
1749 gen_tokens = window.gen_tokens,
1750 prompt_tokens = window.prompt_tokens,
1751 completed = window.completed,
1752 failed = window.failed,
1753 active = window.active,
1754 queued = window.queued,
1755 kv_slots = format_args!("{}/{}", window.busy_slots, window.total_slots),
1756 "serve stats"
1757 );
1758 }
1759 if shutting_down {
1760 return;
1761 }
1762 }
1763}
1764
1765#[derive(Clone)]
1782struct ModelEntry {
1783 id: Arc<str>,
1784 engine: Option<Arc<dyn ChatGenerator>>,
1785 slots: Arc<Semaphore>,
1786 capacity: usize,
1790 prepares: Arc<Semaphore>,
1796}
1797
1798impl ModelEntry {
1799 fn new(id: &str, engine: Option<Arc<dyn ChatGenerator>>, n_parallel: usize) -> Self {
1800 let capacity = n_parallel.max(1);
1801 Self {
1802 id: Arc::from(id),
1803 engine,
1804 slots: Arc::new(Semaphore::new(capacity)),
1805 capacity,
1806 prepares: Arc::new(Semaphore::new(capacity)),
1807 }
1808 }
1809
1810 fn busy(&self) -> usize {
1813 self.capacity - self.slots.available_permits().min(self.capacity)
1814 }
1815}
1816
1817#[derive(Clone)]
1822pub struct AppState {
1823 models: Arc<Vec<ModelEntry>>,
1825 cfg: Arc<Config>,
1830 stats: Arc<ServeStats>,
1834 started: Instant,
1836 bind: Option<SocketAddr>,
1840}
1841
1842impl AppState {
1843 pub fn new(
1847 generator: Arc<dyn ChatGenerator>,
1848 model_id: impl Into<String>,
1849 n_parallel: usize,
1850 cfg: Arc<Config>,
1851 ) -> Self {
1852 Self {
1853 models: Arc::new(vec![ModelEntry::new(
1854 &model_id.into(),
1855 Some(generator),
1856 n_parallel,
1857 )]),
1858 cfg,
1859 stats: Arc::default(),
1860 started: Instant::now(),
1861 bind: None,
1862 }
1863 }
1864
1865 pub fn multi(entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>, cfg: Arc<Config>) -> Self {
1873 assert!(
1874 !entries.is_empty(),
1875 "AppState::multi needs at least one model"
1876 );
1877 let models = entries
1878 .into_iter()
1879 .map(|(id, gen, n)| ModelEntry::new(&id, Some(gen), n))
1880 .collect();
1881 Self {
1882 models: Arc::new(models),
1883 cfg,
1884 stats: Arc::default(),
1885 started: Instant::now(),
1886 bind: None,
1887 }
1888 }
1889
1890 pub fn headless(model_id: impl Into<String>, cfg: Arc<Config>) -> Self {
1894 Self {
1895 models: Arc::new(vec![ModelEntry::new(&model_id.into(), None, 1)]),
1896 cfg,
1897 stats: Arc::default(),
1898 started: Instant::now(),
1899 bind: None,
1900 }
1901 }
1902
1903 fn slot_occupancy(&self) -> (u64, u64) {
1905 self.models.iter().fold((0, 0), |(busy, total), m| {
1906 (busy + m.busy() as u64, total + m.capacity as u64)
1907 })
1908 }
1909
1910 fn route(&self, requested: &str) -> ModelEntry {
1914 self.models
1915 .iter()
1916 .find(|m| &*m.id == requested)
1917 .unwrap_or(&self.models[0])
1918 .clone()
1919 }
1920}
1921
1922pub fn build_router(state: AppState) -> Router {
1931 let body_limit = max_body_bytes(&state.cfg);
1932 Router::new()
1933 .route("/v1/models", get(models_handler))
1934 .route("/metrics", get(metrics::metrics_handler))
1935 .route("/status", get(status::status_handler))
1936 .route(
1937 "/v1/chat/completions",
1938 post(chat_completions_handler)
1939 .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
1940 )
1941 .route(
1942 "/v1/completions",
1943 post(completions::completions_handler)
1944 .route_layer(middleware::from_fn_with_state(state.clone(), require_auth)),
1945 )
1946 .layer(middleware::from_fn_with_state(
1947 state.clone(),
1948 host::host_gate,
1949 ))
1950 .route("/health", get(health_handler))
1951 .layer(DefaultBodyLimit::max(body_limit))
1952 .with_state(state)
1953}
1954
1955async fn require_auth(State(state): State<AppState>, req: Request, next: Next) -> Response {
1961 if let Some(denied) = auth_gate(&state.cfg, req.headers()) {
1962 return denied;
1963 }
1964 next.run(req).await
1965}
1966
1967pub async fn serve(
1974 generator: Arc<dyn ChatGenerator>,
1975 model_id: String,
1976 addr: SocketAddr,
1977 n_parallel: usize,
1978 cfg: Arc<Config>,
1979) -> anyhow::Result<()> {
1980 serve_state(AppState::new(generator, model_id, n_parallel, cfg), addr).await
1981}
1982
1983pub async fn serve_multi(
1991 entries: Vec<(String, Arc<dyn ChatGenerator>, usize)>,
1992 addr: SocketAddr,
1993 cfg: Arc<Config>,
1994) -> anyhow::Result<()> {
1995 serve_state(AppState::multi(entries, cfg), addr).await
1996}
1997
1998async fn serve_state(mut state: AppState, addr: SocketAddr) -> anyhow::Result<()> {
2001 host::check_allowed_hosts(&state.cfg)?;
2002 let n_models = state.models.len();
2003 let listener = tokio::net::TcpListener::bind(addr).await?;
2004 state.bind = Some(listener.local_addr()?);
2007 let reporter = stats_interval(&state.cfg)
2011 .map(|period| tokio::spawn(stats_reporter(state.clone(), period)));
2012 let router = build_router(state);
2013 tracing::info!(%addr, %n_models, "infr-server listening");
2014 let served = axum::serve(listener, router)
2015 .with_graceful_shutdown(shutdown_latched())
2016 .await;
2017 if let Some(h) = reporter {
2018 h.abort();
2019 }
2020 served?;
2021 Ok(())
2022}
2023
2024async fn shutdown_latched() {
2037 while !infr_core::shutdown::shutdown_requested() {
2038 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2039 }
2040 tracing::info!("shutdown requested — draining in-flight requests");
2041}
2042
2043async fn health_handler() -> StatusCode {
2053 StatusCode::OK
2054}
2055
2056async fn models_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
2068 if let Some(denied) = auth_gate(&state.cfg, &headers) {
2069 return denied;
2070 }
2071 Json(ModelsResponse {
2072 object: "list",
2073 data: state
2074 .models
2075 .iter()
2076 .map(|m| ModelCard {
2077 id: m.id.to_string(),
2078 object: "model",
2079 owned_by: "local",
2080 })
2081 .collect(),
2082 })
2083 .into_response()
2084}
2085
2086async fn chat_completions_handler(
2088 State(state): State<AppState>,
2089 body: Result<Json<ChatRequest>, JsonRejection>,
2090) -> Response {
2091 let Json(req) = match body {
2092 Ok(j) => j,
2093 Err(e) => return body_rejection(e),
2094 };
2095 let mut params = match GenParams::from_request(&req) {
2096 Ok(p) => p,
2097 Err(e) => return param_error(Some(e.param), e.message),
2098 };
2099 params.max_tokens = clamp_max_tokens(params.max_tokens, max_tokens_cap(&state.cfg));
2101 let messages: Vec<ChatMessage> = req.messages.iter().map(dto_to_engine).collect();
2102 let tools: Option<serde_json::Value> = req.tools.clone();
2105 let tool_choice: Option<String> = match req.tool_choice.as_ref() {
2107 None | Some(serde_json::Value::Null) => None,
2108 Some(v) => match tool_choice_str(v) {
2109 Ok(tc) => tc,
2110 Err(e) => return param_error(Some(e.param), e.message),
2111 },
2112 };
2113 if let Err(e) = validate_tools(tools.as_ref())
2117 .and_then(|()| validate_tool_choice(tool_choice.as_deref(), tools.as_ref()))
2118 {
2119 return param_error(Some(e.param), e.message);
2120 }
2121
2122 let entry = state.route(&req.model);
2126 if params.logprobs {
2127 if let Some(engine) = &entry.engine {
2128 if !engine.supports_logprobs() {
2129 return param_error(
2130 Some("logprobs"),
2131 "logprobs: returning log probabilities is not supported by this backend".into(),
2132 );
2133 }
2134 }
2135 }
2136 if let (false, Some(engine)) = (params.logit_bias.is_empty(), &entry.engine) {
2139 if let Err(e) = params.check_vocab(engine.vocab_size()) {
2140 return param_error(Some(e.param), e.message);
2141 }
2142 }
2143 let model_id = entry.id.to_string();
2144 let ctx = ReqCtx {
2145 id: next_req_id(),
2146 cid: make_id(),
2147 model_id,
2148 created: unix_ts(),
2149 deadline: request_timeout(&state.cfg),
2152 keep_alive: sse_keep_alive(&state.cfg),
2153 stream: req.stream,
2154 include_usage: req.stream_options.as_ref().is_some_and(|o| o.include_usage),
2155 stats: state.stats.clone(),
2156 };
2157 let prompt_chars = messages.iter().map(|m| m.content.len()).sum();
2158 let n_messages = messages.len();
2159
2160 let (messages, tools, tool_choice, params, prepared) = match entry.engine.clone() {
2164 None => (messages, tools, tool_choice, params, Ok(None)),
2165 Some(engine) => {
2166 let joined = prepare_bounded(&entry, &ctx, move || {
2167 let prepared =
2168 engine.prepare(&messages, tools.as_ref(), tool_choice.as_deref(), ¶ms);
2169 (messages, tools, tool_choice, params, prepared)
2170 })
2171 .await;
2172 match joined {
2173 Ok(parts) => parts,
2174 Err(resp) => return *resp,
2175 }
2176 }
2177 };
2178 let prompt_tokens = prepared
2179 .as_ref()
2180 .ok()
2181 .and_then(|p| p.as_ref().map(|p| p.prompt_tokens));
2182 let (prepared, refused) = match prepared {
2183 Err(e) => (None, Some(e)),
2184 Ok(Some(PreparedRequest {
2185 prompt_tokens,
2186 context_length: Some(max),
2187 ..
2188 })) if prompt_tokens > max => (
2189 None,
2190 Some(
2191 ContextLengthExceeded::prompt_too_long(
2192 CHAT_INPUT,
2193 max as usize,
2194 prompt_tokens as usize,
2195 )
2196 .into(),
2197 ),
2198 ),
2199 Ok(p) => (p, None),
2200 };
2201 log_request_start(
2202 ctx.id,
2203 RequestStart {
2204 route: "/v1/chat/completions",
2205 model: &ctx.model_id,
2206 messages: n_messages,
2207 prompt_chars,
2208 prompt_tokens,
2209 max_tokens: params.max_tokens,
2210 stream: ctx.stream,
2211 },
2212 );
2213 if let Some(e) = refused {
2214 ctx.stats.fold_failure();
2215 tracing::warn!(req = ctx.id, error = %e, "request refused before generation");
2216 return error_response(&e, CHAT_INPUT);
2217 }
2218
2219 if ctx.stream {
2220 streaming(entry, prepared, messages, tools, tool_choice, params, ctx).await
2221 } else {
2222 non_streaming(entry, prepared, messages, tools, tool_choice, params, ctx).await
2223 }
2224}
2225
2226#[derive(Clone)]
2233struct ReqCtx {
2234 id: u64,
2236 cid: String,
2238 model_id: String,
2240 created: i64,
2241 deadline: Option<Duration>,
2242 keep_alive: Option<Duration>,
2244 stream: bool,
2245 include_usage: bool,
2247 stats: Arc<ServeStats>,
2248}
2249
2250const CHAT_INPUT: &str = "messages";
2256
2257async fn prepare_bounded<T: Send + 'static>(
2262 entry: &ModelEntry,
2263 ctx: &ReqCtx,
2264 f: impl FnOnce() -> T + Send + 'static,
2265) -> Result<T, Box<Response>> {
2266 let Ok(permit) = entry.prepares.clone().acquire_owned().await else {
2269 ctx.stats.fold_failure();
2270 return Err(Box::new(json_error(
2271 StatusCode::SERVICE_UNAVAILABLE,
2272 "server shutting down".into(),
2273 )));
2274 };
2275 tokio::task::spawn_blocking(move || {
2276 let _permit = permit;
2277 f()
2278 })
2279 .await
2280 .map_err(|e| {
2281 ctx.stats.fold_failure();
2282 tracing::warn!(req = ctx.id, error = %e, "request preparation failed");
2283 Box::new(json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
2284 })
2285}
2286
2287struct Slot {
2293 _permit: tokio::sync::OwnedSemaphorePermit,
2294 _active: ActiveGuard,
2295}
2296
2297async fn acquire_slot(entry: &ModelEntry, ctx: &ReqCtx) -> Result<Slot, Box<Response>> {
2302 let stats = &ctx.stats;
2303 let queued = QueuedGuard::new(stats.clone());
2304 let Ok(permit) = entry.slots.clone().acquire_owned().await else {
2305 stats.fold_failure();
2306 tracing::warn!(req = ctx.id, "rejected — server shutting down");
2307 return Err(Box::new(json_error(
2308 StatusCode::SERVICE_UNAVAILABLE,
2309 "server shutting down".into(),
2310 )));
2311 };
2312 drop(queued);
2313 Ok(Slot {
2314 _permit: permit,
2315 _active: ActiveGuard::new(stats.clone()),
2316 })
2317}
2318
2319async fn run_unary<T: Send + 'static>(
2325 entry: &ModelEntry,
2326 ctx: &ReqCtx,
2327 input: &'static str,
2328 job: impl FnOnce(&dyn ChatGenerator, &Arc<AtomicBool>) -> anyhow::Result<T> + Send + 'static,
2329) -> Result<(T, bool), Box<Response>> {
2330 let req_id = ctx.id;
2331 let slot = acquire_slot(entry, ctx).await?;
2332 let engine_arc = entry.engine.clone();
2333
2334 let cancel = Arc::new(AtomicBool::new(false));
2338 let cancel_blk = cancel.clone();
2339 let _hangup = CancelOnDrop(cancel.clone());
2344
2345 let mut handle = tokio::task::spawn_blocking(move || -> anyhow::Result<T> {
2346 let _slot = slot;
2347 let Some(engine) = engine_arc else {
2348 anyhow::bail!("no engine loaded");
2349 };
2350 job(&*engine, &cancel_blk)
2351 });
2352
2353 let mut deadline_hit = false;
2368 let joined = match ctx.deadline {
2369 None => handle.await,
2370 Some(d) => match tokio::time::timeout(d, &mut handle).await {
2371 Ok(joined) => joined,
2372 Err(_elapsed) => {
2373 deadline_hit = true;
2374 cancel.store(true, Ordering::Relaxed);
2375 tracing::warn!(
2376 req = req_id,
2377 timeout_s = d.as_secs(),
2378 "request deadline hit — returning the partial completion"
2379 );
2380 handle.await
2381 }
2382 },
2383 };
2384 match joined.map_err(anyhow::Error::from).and_then(|r| r) {
2385 Ok(out) => Ok((out, deadline_hit)),
2386 Err(e) => {
2387 ctx.stats.fold_failure();
2388 tracing::warn!(req = req_id, error = %e, "request failed");
2389 Err(Box::new(error_response(&e, input)))
2390 }
2391 }
2392}
2393
2394struct StreamJob {
2397 tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
2398 cancel: Arc<AtomicBool>,
2400 deadline_hit: Arc<AtomicBool>,
2403 done: DoneGuard,
2405 engine: Option<Arc<dyn ChatGenerator>>,
2407}
2408
2409impl StreamJob {
2410 fn send(&self, ev: Event) {
2413 if self.tx.send(Ok(ev)).is_err() {
2414 self.cancel.store(true, Ordering::Relaxed);
2415 }
2416 }
2417
2418 fn finish(&self, finish: Finish) -> Finish {
2422 if self.deadline_hit.load(Ordering::Relaxed) {
2423 Finish::Length
2424 } else {
2425 finish
2426 }
2427 }
2428
2429 fn fail(&mut self, e: &anyhow::Error, input: &'static str) {
2435 match request_error_body(e, input) {
2436 Some(body) => self.done.fail_with(body, &e.to_string()),
2437 None => self.done.fail(&e.to_string()),
2438 }
2439 }
2440}
2441
2442async fn run_streamed(
2445 entry: &ModelEntry,
2446 ctx: &ReqCtx,
2447 job: impl FnOnce(StreamJob) + Send + 'static,
2448) -> Response {
2449 let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
2457
2458 let slot = match acquire_slot(entry, ctx).await {
2462 Ok(slot) => slot,
2463 Err(resp) => return *resp,
2464 };
2465
2466 let cancel = Arc::new(AtomicBool::new(false));
2472 let hangup_done = cancel_on_hangup(&tx, cancel.clone());
2473
2474 let deadline_hit = Arc::new(AtomicBool::new(false));
2480 let done_tx = ctx
2481 .deadline
2482 .map(|d| arm_deadline(d, cancel.clone(), deadline_hit.clone()));
2483
2484 let engine = entry.engine.clone();
2485 let (req_id, stats) = (ctx.id, ctx.stats.clone());
2486 tokio::task::spawn_blocking(move || {
2487 let _slot = slot;
2490 let _done_tx = done_tx;
2493 let _hangup_done = hangup_done;
2496 let done = DoneGuard {
2501 tx: tx.clone(),
2502 req_id,
2503 stats,
2504 settled: false,
2505 };
2506 job(StreamJob {
2507 tx,
2508 cancel,
2509 deadline_hit,
2510 done,
2511 engine,
2512 });
2513 });
2514
2515 let stream = futures_util::stream::unfold(rx, |mut rx| async move {
2517 rx.recv().await.map(|item| (item, rx))
2518 });
2519
2520 let sse = Sse::new(stream);
2521 match ctx.keep_alive {
2522 Some(d) => sse.keep_alive(KeepAlive::new().interval(d)).into_response(),
2523 None => sse.into_response(),
2524 }
2525}
2526
2527async fn non_streaming(
2532 entry: ModelEntry,
2533 prepared: Option<PreparedRequest>,
2534 messages: Vec<ChatMessage>,
2535 tools: Option<serde_json::Value>,
2536 tool_choice: Option<String>,
2537 params: GenParams,
2538 ctx: ReqCtx,
2539) -> Response {
2540 let cid_blk = ctx.cid.clone();
2541 let stats_blk = ctx.stats.clone();
2542 let want_logprobs = params.logprobs;
2543
2544 let ran = run_unary(&entry, &ctx, CHAT_INPUT, move |engine, cancel| {
2545 let mut reasoning = String::new();
2546 let mut content = String::new();
2547 let mut tool_calls: Vec<OAIToolCall> = Vec::new();
2548 let mut logprobs: Vec<infr_engine::TokenLogprob> = Vec::new();
2549 let mut tally = ReqTally::new();
2551
2552 let outcome = generate(
2553 engine,
2554 prepared,
2555 &messages,
2556 tools.as_ref(),
2557 tool_choice.as_deref(),
2558 ¶ms,
2559 cancel,
2560 &mut |delta| match delta {
2561 Delta::Reasoning(t) => {
2562 tally.on_text_delta(&stats_blk);
2563 reasoning.push_str(&t);
2564 }
2565 Delta::Content(t) => {
2566 tally.on_text_delta(&stats_blk);
2567 content.push_str(&t);
2568 }
2569 Delta::ToolCall { name, arguments } => {
2570 let idx = tool_calls.len();
2571 tool_calls.push(OAIToolCall {
2572 index: idx,
2573 id: tool_call_id(&cid_blk, idx),
2574 kind: "function",
2575 function: OAIFunction { name, arguments },
2576 });
2577 }
2578 Delta::Logprob(t) => logprobs.push(t),
2579 },
2580 )?;
2581
2582 Ok((reasoning, content, tool_calls, logprobs, outcome, tally))
2583 })
2584 .await;
2585 let ((reasoning, content, tool_calls, logprobs, outcome, tally), deadline_hit) = match ran {
2586 Ok(ran) => ran,
2587 Err(resp) => return *resp,
2588 };
2589 let ReqCtx {
2590 id: req_id,
2591 cid,
2592 model_id,
2593 created,
2594 stream,
2595 stats,
2596 ..
2597 } = ctx;
2598
2599 let finish = if !tool_calls.is_empty() {
2611 Finish::ToolCalls
2612 } else if deadline_hit {
2613 Finish::Length
2614 } else {
2615 outcome.finish
2616 };
2617 let rec = tally.finish(outcome, finish);
2619 stats.fold_completion(&rec);
2620 log_request_done(req_id, &model_id, stream, &rec);
2621 Json(ChatCompletionResponse {
2622 id: cid,
2623 object: "chat.completion",
2624 created,
2625 model: model_id,
2626 choices: vec![CompletionChoice {
2627 index: 0,
2628 message: AssistantMessage {
2629 role: "assistant",
2630 content: if content.is_empty() {
2631 None
2632 } else {
2633 Some(content.clone())
2634 },
2635 reasoning_content: if reasoning.is_empty() {
2636 None
2637 } else {
2638 Some(reasoning)
2639 },
2640 tool_calls: if tool_calls.is_empty() {
2641 None
2642 } else {
2643 Some(tool_calls)
2644 },
2645 },
2646 logprobs: want_logprobs.then(|| ChatLogprobs::from_tokens(&logprobs)),
2647 finish_reason: finish.as_str().into(),
2648 }],
2649 usage: UsageInfo::from_outcome(&outcome),
2650 })
2651 .into_response()
2652}
2653
2654async fn streaming(
2659 entry: ModelEntry,
2660 prepared: Option<PreparedRequest>,
2661 messages: Vec<ChatMessage>,
2662 tools: Option<serde_json::Value>,
2663 tool_choice: Option<String>,
2664 params: GenParams,
2665 ctx: ReqCtx,
2666) -> Response {
2667 let ReqCtx {
2669 id: req_id,
2670 cid,
2671 model_id,
2672 created,
2673 stream,
2674 include_usage,
2675 stats,
2676 ..
2677 } = ctx.clone();
2678
2679 run_streamed(&entry, &ctx, move |mut job| {
2680 job.send(sse_chunk(
2682 &cid,
2683 &model_id,
2684 created,
2685 DeltaPayload {
2686 role: Some("assistant".into()),
2687 ..Default::default()
2688 },
2689 None,
2690 None,
2691 ));
2692
2693 let Some(engine) = job.engine.clone() else {
2694 job.done.fail("no engine loaded");
2697 return;
2698 };
2699
2700 let mut tc_index = 0usize;
2701 let mut saw_tool_call = false;
2702 let mut pending_logprobs: Vec<infr_engine::TokenLogprob> = Vec::new();
2706 let mut tally = ReqTally::new();
2708
2709 let res = generate(
2710 &*engine,
2711 prepared,
2712 &messages,
2713 tools.as_ref(),
2714 tool_choice.as_deref(),
2715 ¶ms,
2716 &job.cancel,
2717 &mut |delta| {
2718 let payload = match delta {
2719 Delta::Logprob(t) => {
2720 pending_logprobs.push(t);
2721 return;
2722 }
2723 Delta::Reasoning(t) => {
2724 tally.on_text_delta(&stats);
2725 DeltaPayload {
2726 reasoning_content: Some(t),
2727 ..Default::default()
2728 }
2729 }
2730 Delta::Content(t) => {
2731 tally.on_text_delta(&stats);
2732 DeltaPayload {
2733 content: Some(t),
2734 ..Default::default()
2735 }
2736 }
2737 Delta::ToolCall { name, arguments } => {
2738 let tc = OAIToolCall {
2739 index: tc_index,
2740 id: tool_call_id(&cid, tc_index),
2741 kind: "function",
2742 function: OAIFunction { name, arguments },
2743 };
2744 tc_index += 1;
2745 saw_tool_call = true;
2746 DeltaPayload {
2747 tool_calls: Some(vec![tc]),
2748 ..Default::default()
2749 }
2750 }
2751 };
2752 let logprobs = if pending_logprobs.is_empty() {
2753 None
2754 } else {
2755 Some(ChatLogprobs::from_tokens(&std::mem::take(
2756 &mut pending_logprobs,
2757 )))
2758 };
2759 job.send(sse_chunk(&cid, &model_id, created, payload, logprobs, None));
2760 },
2761 );
2762
2763 match res {
2764 Ok(outcome) => {
2765 let finish = if saw_tool_call {
2768 Finish::ToolCalls
2769 } else {
2770 job.finish(outcome.finish)
2771 };
2772 let last_logprobs = if pending_logprobs.is_empty() {
2775 None
2776 } else {
2777 Some(ChatLogprobs::from_tokens(&pending_logprobs))
2778 };
2779 job.send(sse_chunk(
2780 &cid,
2781 &model_id,
2782 created,
2783 DeltaPayload::default(),
2784 last_logprobs,
2785 Some(finish.as_str().into()),
2786 ));
2787 if include_usage {
2788 job.send(sse_usage_chunk(&cid, &model_id, created, &outcome));
2789 }
2790 let rec = tally.finish(outcome, finish);
2794 stats.fold_completion(&rec);
2795 log_request_done(req_id, &model_id, stream, &rec);
2796 job.done.settled();
2797 }
2798 Err(e) => job.fail(&e, CHAT_INPUT),
2799 }
2800 })
2803 .await
2804}
2805
2806struct DoneGuard {
2832 tx: tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
2833 req_id: u64,
2835 stats: Arc<ServeStats>,
2836 settled: bool,
2838}
2839
2840impl DoneGuard {
2841 fn settled(&mut self) {
2844 self.settled = true;
2845 }
2846
2847 fn fail(&mut self, msg: &str) {
2853 self.fail_with(error_body(msg, "server_error"), msg);
2854 }
2855
2856 fn fail_with(&mut self, body: serde_json::Value, msg: &str) {
2859 if self.settled {
2860 return;
2861 }
2862 self.settled = true;
2863 let _ = self.tx.send(Ok(sse_error_event(&body)));
2866 self.stats.fold_failure();
2867 tracing::warn!(req = self.req_id, error = msg, "request failed");
2868 }
2869}
2870
2871impl Drop for DoneGuard {
2872 fn drop(&mut self) {
2873 self.fail("internal error: generation ended without a terminal frame");
2874 let _ = self.tx.send(Ok(Event::default().data("[DONE]")));
2875 }
2876}
2877
2878fn error_body(msg: &str, ty: &str) -> serde_json::Value {
2887 serde_json::json!({"error": {"message": msg, "type": ty}})
2888}
2889
2890fn sse_error_event(body: &serde_json::Value) -> Event {
2894 Event::default().data(body.to_string())
2895}
2896
2897fn sse_chunk(
2899 cid: &str,
2900 model: &str,
2901 created: i64,
2902 delta: DeltaPayload,
2903 logprobs: Option<ChatLogprobs>,
2904 finish_reason: Option<String>,
2905) -> Event {
2906 let chunk = ChatCompletionChunk {
2907 id: cid.to_owned(),
2908 object: "chat.completion.chunk",
2909 created,
2910 model: model.to_owned(),
2911 choices: vec![ChunkChoice {
2912 index: 0,
2913 delta,
2914 logprobs,
2915 finish_reason,
2916 }],
2917 usage: None,
2918 };
2919 Event::default()
2920 .json_data(chunk)
2921 .expect("ChatCompletionChunk always serializes")
2922}
2923
2924fn sse_usage_chunk(cid: &str, model: &str, created: i64, outcome: &ChatOutcome) -> Event {
2927 let chunk = ChatCompletionChunk {
2928 id: cid.to_owned(),
2929 object: "chat.completion.chunk",
2930 created,
2931 model: model.to_owned(),
2932 choices: Vec::new(),
2933 usage: Some(UsageInfo::from_outcome(outcome)),
2934 };
2935 Event::default()
2936 .json_data(chunk)
2937 .expect("ChatCompletionChunk always serializes")
2938}
2939
2940fn json_error(status: StatusCode, msg: String) -> Response {
2941 (status, Json(error_body(&msg, "server_error"))).into_response()
2942}
2943
2944fn invalid_request(
2955 status: StatusCode,
2956 param: Option<&str>,
2957 code: Option<&str>,
2958 msg: String,
2959) -> Response {
2960 (status, Json(invalid_request_body(param, code, &msg))).into_response()
2961}
2962
2963fn invalid_request_body(param: Option<&str>, code: Option<&str>, msg: &str) -> serde_json::Value {
2965 let mut body = error_body(msg, "invalid_request_error");
2966 body["error"]["param"] = serde_json::json!(param);
2967 body["error"]["code"] = serde_json::json!(code);
2968 body
2969}
2970
2971fn context_length_body(c: &ContextLengthExceeded, input: &str) -> serde_json::Value {
2974 invalid_request_body(Some(input), Some("context_length_exceeded"), &c.message)
2975}
2976
2977fn request_error_body(e: &anyhow::Error, input: &str) -> Option<serde_json::Value> {
2981 if let Some(c) = e.downcast_ref::<ContextLengthExceeded>() {
2982 return Some(context_length_body(c, input));
2983 }
2984 e.downcast_ref::<ParamError>()
2985 .map(|p| invalid_request_body(Some(p.param), None, &p.message))
2986}
2987
2988fn error_response(e: &anyhow::Error, input: &str) -> Response {
2990 match request_error_body(e, input) {
2991 Some(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
2992 None => json_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
2993 }
2994}
2995
2996fn body_rejection(e: JsonRejection) -> Response {
3000 let status = match e.status() {
3001 s @ (StatusCode::PAYLOAD_TOO_LARGE | StatusCode::UNSUPPORTED_MEDIA_TYPE) => s,
3002 _ => StatusCode::BAD_REQUEST,
3003 };
3004 invalid_request(status, None, None, e.body_text())
3005}
3006
3007fn param_error(param: Option<&str>, msg: String) -> Response {
3010 invalid_request(StatusCode::BAD_REQUEST, param, None, msg)
3011}
3012
3013static ID_COUNTER: AtomicU64 = AtomicU64::new(0);
3017
3018fn make_id() -> String {
3019 let ms = SystemTime::now()
3020 .duration_since(UNIX_EPOCH)
3021 .unwrap_or_default()
3022 .as_millis();
3023 let seq = ID_COUNTER.fetch_add(1, Ordering::Relaxed);
3024 format!("chatcmpl-{ms}-{seq}")
3025}
3026
3027const TOOL_CALL_ID_LEN: usize = 9;
3032const TOOL_CALL_ID_ALPHABET: &[u8] =
3033 b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
3034
3035fn tool_call_id(cid: &str, idx: usize) -> String {
3039 use std::hash::{DefaultHasher, Hash, Hasher};
3040 let mut h = DefaultHasher::new();
3041 (cid, idx).hash(&mut h);
3042 let mut n = h.finish();
3043 let base = TOOL_CALL_ID_ALPHABET.len() as u64;
3044 (0..TOOL_CALL_ID_LEN)
3045 .map(|_| {
3046 let c = TOOL_CALL_ID_ALPHABET[(n % base) as usize] as char;
3047 n /= base;
3048 c
3049 })
3050 .collect()
3051}
3052
3053const DEFAULT_MAX_TOKENS_CAP: u32 = 131_072;
3056
3057fn max_tokens_cap(cfg: &Config) -> u32 {
3065 let cap = cfg.serve.max_tokens_cap;
3066 if cap > 0 {
3067 cap
3068 } else {
3069 DEFAULT_MAX_TOKENS_CAP
3070 }
3071}
3072
3073fn clamp_max_tokens(requested: Option<u32>, cap: u32) -> Option<u32> {
3077 requested.map(|v| v.min(cap))
3078}
3079
3080fn max_body_bytes(cfg: &Config) -> usize {
3083 let n = match cfg.serve.max_body_bytes {
3084 0 => Config::default().serve.max_body_bytes,
3085 n => n,
3086 };
3087 usize::try_from(n).unwrap_or(usize::MAX)
3088}
3089
3090fn sse_keep_alive(cfg: &Config) -> Option<Duration> {
3092 let secs = cfg.serve.sse_keepalive_secs;
3093 (secs > 0).then(|| Duration::from_secs(secs).min(MAX_SSE_KEEPALIVE))
3094}
3095
3096const MAX_SSE_KEEPALIVE: Duration = Duration::from_secs(24 * 60 * 60);
3100
3101fn request_timeout(cfg: &Config) -> Option<Duration> {
3114 let secs = cfg.serve.request_timeout_secs;
3115 (secs > 0).then(|| Duration::from_secs(secs))
3116}
3117
3118fn arm_deadline(
3144 d: Duration,
3145 cancel: Arc<AtomicBool>,
3146 hit: Arc<AtomicBool>,
3147) -> tokio::sync::oneshot::Sender<()> {
3148 let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
3149 tokio::spawn(async move {
3150 tokio::select! {
3151 _ = tokio::time::sleep(d) => {
3152 hit.store(true, Ordering::Relaxed);
3153 cancel.store(true, Ordering::Relaxed);
3154 tracing::warn!(timeout_s = d.as_secs(), "request deadline hit — aborting generation");
3155 }
3156 _ = done_rx => {}
3157 }
3158 });
3159 done_tx
3160}
3161
3162fn cancel_on_hangup(
3170 tx: &tokio::sync::mpsc::UnboundedSender<Result<Event, Infallible>>,
3171 cancel: Arc<AtomicBool>,
3172) -> tokio::sync::oneshot::Sender<()> {
3173 let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
3174 let tx = tx.clone();
3175 tokio::spawn(async move {
3176 tokio::select! {
3177 _ = tx.closed() => cancel.store(true, Ordering::Relaxed),
3178 _ = done_rx => {}
3179 }
3180 });
3181 done_tx
3182}
3183
3184struct CancelOnDrop(Arc<AtomicBool>);
3186
3187impl Drop for CancelOnDrop {
3188 fn drop(&mut self) {
3189 self.0.store(true, Ordering::Relaxed);
3190 }
3191}
3192
3193fn authorize(expected: Option<&str>, auth_header: Option<&str>) -> bool {
3216 match expected {
3217 None => true,
3218 Some(key) => auth_header
3219 .and_then(|h| {
3220 h.strip_prefix("Bearer ")
3221 .or_else(|| h.strip_prefix("bearer "))
3222 })
3223 .map(str::trim)
3224 .is_some_and(|tok| bool::from(tok.as_bytes().ct_eq(key.as_bytes()))),
3225 }
3226}
3227
3228fn auth_gate(cfg: &Config, headers: &HeaderMap) -> Option<Response> {
3243 let key = configured_api_key(cfg)?;
3244 let auth = headers.get("authorization").and_then(|v| v.to_str().ok());
3245 (!authorize(Some(key), auth)).then(|| {
3247 invalid_request(
3248 StatusCode::UNAUTHORIZED,
3249 None,
3250 Some("invalid_api_key"),
3251 "missing or invalid Authorization bearer token".into(),
3252 )
3253 })
3254}
3255
3256fn configured_api_key(cfg: &Config) -> Option<&str> {
3265 cfg.serve
3266 .api_key
3267 .as_deref()
3268 .filter(|k: &&str| !k.is_empty())
3269}
3270
3271fn unix_ts() -> i64 {
3272 SystemTime::now()
3273 .duration_since(UNIX_EPOCH)
3274 .unwrap_or_default()
3275 .as_secs() as i64
3276}
3277
3278pub fn flatten_content(v: &Option<serde_json::Value>) -> String {
3282 match v {
3283 None | Some(serde_json::Value::Null) => String::new(),
3284 Some(serde_json::Value::String(s)) => s.clone(),
3285 Some(serde_json::Value::Array(parts)) => parts
3286 .iter()
3287 .filter_map(|p| {
3288 if p.get("type")?.as_str()? == "text" {
3289 p.get("text")?.as_str().map(str::to_owned)
3290 } else {
3291 None
3292 }
3293 })
3294 .collect::<Vec<_>>()
3295 .join(""),
3296 Some(other) => other.to_string(),
3297 }
3298}
3299
3300fn dto_to_engine(dto: &ChatMessageDto) -> ChatMessage {
3301 ChatMessage {
3302 role: dto.role.clone(),
3303 content: flatten_content(&dto.content),
3304 tool_calls: dto.tool_calls.as_ref().and_then(parse_oai_tool_calls),
3305 tool_call_id: dto.tool_call_id.clone(),
3306 name: dto.name.clone(),
3307 }
3308}
3309
3310fn parse_oai_tool_calls(v: &serde_json::Value) -> Option<Vec<ToolCall>> {
3314 let arr = v.as_array()?;
3315 let calls: Vec<ToolCall> = arr
3316 .iter()
3317 .filter_map(|c| {
3318 let f = c.get("function")?;
3319 let name = f.get("name")?.as_str()?.to_owned();
3320 let arguments = match f.get("arguments") {
3321 Some(serde_json::Value::String(s)) => {
3322 serde_json::from_str(s).unwrap_or(serde_json::Value::String(s.clone()))
3323 }
3324 Some(other) => other.clone(),
3325 None => serde_json::Value::Object(serde_json::Map::new()),
3326 };
3327 let id = c.get("id").and_then(|v| v.as_str()).map(str::to_owned);
3328 Some(ToolCall {
3329 name,
3330 arguments,
3331 id,
3332 })
3333 })
3334 .collect();
3335 (!calls.is_empty()).then_some(calls)
3336}
3337
3338#[cfg(test)]
3343mod tests {
3344 use super::*;
3345 use axum::{body::Body, http::Request};
3346 use http_body_util::BodyExt;
3347 use tower::ServiceExt;
3348
3349 fn test_router() -> Router {
3352 build_router(AppState::headless(
3353 "test-model",
3354 Arc::new(Config::default()),
3355 ))
3356 }
3357
3358 #[tokio::test]
3361 async fn test_health_returns_200() {
3362 let resp = test_router()
3363 .oneshot(
3364 Request::builder()
3365 .uri("/health")
3366 .body(Body::empty())
3367 .unwrap(),
3368 )
3369 .await
3370 .unwrap();
3371 assert_eq!(resp.status(), StatusCode::OK);
3372 }
3373
3374 #[tokio::test]
3375 async fn test_models_returns_200_with_expected_shape() {
3376 let resp = test_router()
3377 .oneshot(
3378 Request::builder()
3379 .uri("/v1/models")
3380 .body(Body::empty())
3381 .unwrap(),
3382 )
3383 .await
3384 .unwrap();
3385 assert_eq!(resp.status(), StatusCode::OK);
3386
3387 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3388 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3389
3390 assert_eq!(json["object"], "list");
3391 let card = &json["data"][0];
3392 assert_eq!(card["id"], "test-model");
3393 assert_eq!(card["object"], "model");
3394 assert_eq!(card["owned_by"], "local");
3395 }
3396
3397 const TEST_VOCAB: usize = 1000;
3399
3400 fn cpu_status() -> GeneratorStatus {
3402 GeneratorStatus {
3403 backend: "cpu",
3404 device: None,
3405 ctx_per_slot: None,
3406 memory: None,
3407 }
3408 }
3409
3410 pub(crate) struct EchoGen(pub(crate) &'static str);
3413 impl ChatGenerator for EchoGen {
3414 fn status(&self) -> GeneratorStatus {
3415 GeneratorStatus {
3416 backend: "vulkan",
3417 device: Some(format!("dev-{}", self.0)),
3418 ctx_per_slot: Some(4096),
3419 memory: Some(DeviceMemory {
3420 total_bytes: 8 << 30,
3421 available_bytes: 6 << 30,
3422 live: true,
3423 unified: false,
3424 }),
3425 }
3426 }
3427
3428 fn vocab_size(&self) -> usize {
3429 TEST_VOCAB
3430 }
3431
3432 fn chat(
3433 &self,
3434 _messages: &[ChatMessage],
3435 _tools: Option<&serde_json::Value>,
3436 _tool_choice: Option<&str>,
3437 _params: &GenParams,
3438 _cancel: &Arc<AtomicBool>,
3439 on_delta: &mut dyn FnMut(Delta),
3440 ) -> anyhow::Result<ChatOutcome> {
3441 on_delta(Delta::Content(format!("from:{}", self.0)));
3442 Ok(ChatOutcome {
3443 finish: Finish::Stop,
3444 prompt_tokens: 3,
3445 completion_tokens: 2,
3446 cached_tokens: 0,
3447 })
3448 }
3449 }
3450
3451 struct LogprobGen;
3453 impl ChatGenerator for LogprobGen {
3454 fn status(&self) -> GeneratorStatus {
3455 cpu_status()
3456 }
3457
3458 fn vocab_size(&self) -> usize {
3459 TEST_VOCAB
3460 }
3461
3462 fn supports_logprobs(&self) -> bool {
3463 true
3464 }
3465
3466 fn chat(
3467 &self,
3468 _messages: &[ChatMessage],
3469 _tools: Option<&serde_json::Value>,
3470 _tool_choice: Option<&str>,
3471 params: &GenParams,
3472 _cancel: &Arc<AtomicBool>,
3473 on_delta: &mut dyn FnMut(Delta),
3474 ) -> anyhow::Result<ChatOutcome> {
3475 assert!(params.logprobs, "the server only asks when requested");
3476 let mut top = vec![infr_engine::TokenLogprobAlt {
3477 token: 9,
3478 text: "ho".into(),
3479 bytes: b"ho".to_vec(),
3480 logprob: -1.5,
3481 }];
3482 top.truncate(params.top_logprobs);
3483 on_delta(Delta::Logprob(infr_engine::TokenLogprob {
3484 token: 7,
3485 text: "hi".into(),
3486 bytes: b"hi".to_vec(),
3487 logprob: -0.25,
3488 top,
3489 }));
3490 on_delta(Delta::Content("hi".into()));
3491 Ok(ChatOutcome {
3492 finish: Finish::Stop,
3493 prompt_tokens: 1,
3494 completion_tokens: 1,
3495 cached_tokens: 0,
3496 })
3497 }
3498 }
3499
3500 fn multi_router() -> Router {
3501 let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
3502 let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
3503 build_router(AppState::multi(
3504 vec![("alpha".into(), a, 2), ("beta".into(), b, 2)],
3505 Arc::new(Config::default()),
3506 ))
3507 }
3508
3509 #[tokio::test]
3510 async fn multi_models_are_all_listed() {
3511 let resp = multi_router()
3512 .oneshot(
3513 Request::builder()
3514 .uri("/v1/models")
3515 .body(Body::empty())
3516 .unwrap(),
3517 )
3518 .await
3519 .unwrap();
3520 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3521 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3522 let ids: Vec<&str> = json["data"]
3523 .as_array()
3524 .unwrap()
3525 .iter()
3526 .map(|c| c["id"].as_str().unwrap())
3527 .collect();
3528 assert_eq!(ids, vec!["alpha", "beta"]);
3529 }
3530
3531 async fn chat_model_field(router: Router, requested: &str) -> (String, String) {
3534 let body =
3535 format!(r#"{{"model":"{requested}","messages":[{{"role":"user","content":"hi"}}]}}"#);
3536 let resp = router
3537 .oneshot(
3538 Request::builder()
3539 .method("POST")
3540 .uri("/v1/chat/completions")
3541 .header("content-type", "application/json")
3542 .body(Body::from(body))
3543 .unwrap(),
3544 )
3545 .await
3546 .unwrap();
3547 assert_eq!(resp.status(), StatusCode::OK);
3548 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3549 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
3550 (
3551 json["model"].as_str().unwrap().to_string(),
3552 json["choices"][0]["message"]["content"]
3553 .as_str()
3554 .unwrap()
3555 .to_string(),
3556 )
3557 }
3558
3559 #[tokio::test]
3560 async fn request_routes_to_named_model() {
3561 let (model, content) = chat_model_field(multi_router(), "beta").await;
3562 assert_eq!(model, "beta");
3563 assert_eq!(content, "from:beta");
3564 }
3565
3566 #[tokio::test]
3567 async fn unknown_model_falls_to_default() {
3568 let (model, content) = chat_model_field(multi_router(), "does-not-exist").await;
3569 assert_eq!(model, "alpha");
3570 assert_eq!(content, "from:alpha");
3571 }
3572
3573 #[test]
3576 fn chat_request_string_content_deserializes() {
3577 let raw = r#"{"model":"m","messages":[{"role":"user","content":"hello"}]}"#;
3578 let req: ChatRequest = serde_json::from_str(raw).unwrap();
3579 assert_eq!(req.messages[0].role, "user");
3580 assert_eq!(flatten_content(&req.messages[0].content), "hello");
3581 assert!(!req.stream);
3582 assert!(req.tools.is_none());
3583 assert!(req.max_tokens.is_none());
3584 }
3585
3586 #[test]
3587 fn chat_request_array_content_deserializes_and_flattens() {
3588 let raw = r#"{
3589 "model": "m",
3590 "messages": [{
3591 "role": "user",
3592 "content": [
3593 {"type":"text","text":"hello"},
3594 {"type":"image_url","image_url":{"url":"data:..."}},
3595 {"type":"text","text":" world"}
3596 ]
3597 }]
3598 }"#;
3599 let req: ChatRequest = serde_json::from_str(raw).unwrap();
3600 assert_eq!(flatten_content(&req.messages[0].content), "hello world");
3602 }
3603
3604 #[test]
3605 fn chat_request_stream_flag() {
3606 let raw = r#"{"model":"m","messages":[],"stream":true}"#;
3607 let req: ChatRequest = serde_json::from_str(raw).unwrap();
3608 assert!(req.stream);
3609 }
3610
3611 #[test]
3612 fn chat_request_with_tools_and_max_tokens() {
3613 let raw = r#"{
3614 "model":"m","messages":[],
3615 "tools":[{"type":"function","function":{"name":"bash","description":"run bash"}}],
3616 "max_tokens":512
3617 }"#;
3618 let req: ChatRequest = serde_json::from_str(raw).unwrap();
3619 assert_eq!(
3622 req.tools,
3623 Some(serde_json::json!([
3624 {"type": "function", "function": {"name": "bash", "description": "run bash"}}
3625 ]))
3626 );
3627 assert_eq!(req.max_tokens, Some(512));
3628 assert_eq!(req.max_completion_tokens, None);
3629 assert_eq!(req.tool_choice, None);
3630 assert!(req.messages.is_empty());
3631 }
3632
3633 #[test]
3634 fn chat_message_dto_with_tool_call_id_and_name() {
3635 let raw = r#"{"role":"tool","content":"result","tool_call_id":"tc_1","name":"bash"}"#;
3636 let msg: ChatMessageDto = serde_json::from_str(raw).unwrap();
3637 assert_eq!(msg.tool_call_id.as_deref(), Some("tc_1"));
3638 assert_eq!(msg.name.as_deref(), Some("bash"));
3639 }
3640
3641 #[test]
3644 fn replayed_tool_call_keeps_its_id() {
3645 let raw = r#"{"role":"assistant","content":null,"tool_calls":[
3646 {"id":"a1B2c3D4e","type":"function",
3647 "function":{"name":"bash","arguments":"{\"cmd\":\"ls\"}"}},
3648 {"type":"function","function":{"name":"noid","arguments":"{}"}}]}"#;
3649 let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(raw).unwrap());
3650 let calls = msg.tool_calls.expect("two calls parse");
3651 assert_eq!(calls[0].id.as_deref(), Some("a1B2c3D4e"));
3652 assert_eq!(calls[0].arguments, serde_json::json!({"cmd": "ls"}));
3653 assert_eq!(calls[1].id, None);
3654 }
3655
3656 #[test]
3661 fn replayed_tool_call_floats_survive_exactly() {
3662 let floats = ["1e-25", "905046994.6356679", "2.5788702084023933e-304"];
3663 let args = format!(
3664 r#"{{"a":{},"b":{},"c":[{}]}}"#,
3665 floats[0], floats[1], floats[2]
3666 );
3667 for arguments in [serde_json::to_string(&args).unwrap(), args.clone()] {
3668 let raw = format!(
3669 r#"{{"role":"assistant","content":null,"tool_calls":[
3670 {{"type":"function","function":{{"name":"f","arguments":{arguments}}}}}]}}"#
3671 );
3672 let msg = dto_to_engine(&serde_json::from_str::<ChatMessageDto>(&raw).unwrap());
3673 let a = &msg.tool_calls.expect("one call")[0].arguments;
3674 let got = [&a["a"], &a["b"], &a["c"][0]].map(|v| v.as_f64().unwrap());
3675 let want = floats.map(|f| f.parse::<f64>().unwrap());
3676 assert_eq!(got.map(f64::to_bits), want.map(f64::to_bits), "{arguments}");
3677 const PRINT: &str = "{% set a = messages[0].tool_calls[0].function.arguments %}\
3679 {{ a.a }} {{ a.b }} {{ a.c[0] }}|{{ a | tojson }}";
3680 let msgs = vec![serde_json::json!({"role": "assistant", "content": "",
3681 "tool_calls": [{"type": "function",
3682 "function": {"name": "f", "arguments": a}}]})];
3683 let prompt = infr_chat::render_template(
3684 PRINT,
3685 msgs,
3686 serde_json::Value::Null,
3687 "",
3688 "",
3689 false,
3690 true,
3691 )
3692 .unwrap();
3693 assert_eq!(
3694 prompt,
3695 format!(
3696 r#"{0} {1} {2}|{{"a": {0}, "b": {1}, "c": [{2}]}}"#,
3697 floats[0], floats[1], floats[2]
3698 )
3699 );
3700 }
3701 }
3702
3703 #[test]
3707 fn minted_tool_call_ids_are_template_safe_and_distinct() {
3708 let mut seen = std::collections::HashSet::new();
3709 for _ in 0..1000 {
3710 let cid = make_id();
3711 for idx in 0..4 {
3712 let id = tool_call_id(&cid, idx);
3713 assert_eq!(id.len(), TOOL_CALL_ID_LEN, "{id}");
3714 assert!(id.bytes().all(|b| b.is_ascii_alphanumeric()), "{id}");
3715 assert!(seen.insert(id.clone()), "duplicate tool-call id {id}");
3716 assert_eq!(id, tool_call_id(&cid, idx));
3717 }
3718 }
3719 }
3720
3721 #[test]
3724 fn chat_completion_response_stop_serializes() {
3725 let resp = ChatCompletionResponse {
3726 id: "chatcmpl-test".into(),
3727 object: "chat.completion",
3728 created: 1000,
3729 model: "test-model".into(),
3730 choices: vec![CompletionChoice {
3731 index: 0,
3732 message: AssistantMessage {
3733 role: "assistant",
3734 content: Some("hello".into()),
3735 reasoning_content: None,
3736 tool_calls: None,
3737 },
3738 logprobs: None,
3739 finish_reason: "stop".into(),
3740 }],
3741 usage: UsageInfo {
3742 prompt_tokens: 10,
3743 completion_tokens: 5,
3744 total_tokens: 15,
3745 prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
3746 },
3747 };
3748 let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3749 assert_eq!(v["object"], "chat.completion");
3750 assert_eq!(v["choices"][0]["finish_reason"], "stop");
3751 assert_eq!(v["choices"][0]["message"]["role"], "assistant");
3752 assert_eq!(v["choices"][0]["message"]["content"], "hello");
3753 assert!(v["choices"][0]["message"]["reasoning_content"].is_null());
3755 assert!(v["choices"][0]["message"]["tool_calls"].is_null());
3756 }
3757
3758 #[test]
3759 fn chat_completion_response_with_reasoning_content() {
3760 let resp = ChatCompletionResponse {
3761 id: "id".into(),
3762 object: "chat.completion",
3763 created: 0,
3764 model: "m".into(),
3765 choices: vec![CompletionChoice {
3766 index: 0,
3767 message: AssistantMessage {
3768 role: "assistant",
3769 content: Some("answer".into()),
3770 reasoning_content: Some("I thought about it".into()),
3771 tool_calls: None,
3772 },
3773 logprobs: None,
3774 finish_reason: "stop".into(),
3775 }],
3776 usage: UsageInfo {
3777 prompt_tokens: 0,
3778 completion_tokens: 0,
3779 total_tokens: 0,
3780 prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
3781 },
3782 };
3783 let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3784 assert_eq!(
3785 v["choices"][0]["message"]["reasoning_content"],
3786 "I thought about it"
3787 );
3788 assert_eq!(v["choices"][0]["message"]["content"], "answer");
3789 }
3790
3791 #[test]
3792 fn chat_completion_response_tool_calls_finish_reason() {
3793 let resp = ChatCompletionResponse {
3794 id: "id".into(),
3795 object: "chat.completion",
3796 created: 0,
3797 model: "m".into(),
3798 choices: vec![CompletionChoice {
3799 index: 0,
3800 message: AssistantMessage {
3801 role: "assistant",
3802 content: None,
3803 reasoning_content: None,
3804 tool_calls: Some(vec![OAIToolCall {
3805 index: 0,
3806 id: "call_0".into(),
3807 kind: "function",
3808 function: OAIFunction {
3809 name: "bash".into(),
3810 arguments: r#"{"command":"ls"}"#.into(),
3811 },
3812 }]),
3813 },
3814 logprobs: None,
3815 finish_reason: "tool_calls".into(),
3816 }],
3817 usage: UsageInfo {
3818 prompt_tokens: 0,
3819 completion_tokens: 0,
3820 total_tokens: 0,
3821 prompt_tokens_details: PromptTokensDetails { cached_tokens: 0 },
3822 },
3823 };
3824 let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3825 assert_eq!(v["choices"][0]["finish_reason"], "tool_calls");
3826 let tc = &v["choices"][0]["message"]["tool_calls"][0];
3827 assert_eq!(tc["type"], "function");
3828 assert_eq!(tc["function"]["name"], "bash");
3829 assert_eq!(tc["function"]["arguments"], r#"{"command":"ls"}"#);
3830 assert_eq!(tc["index"], 0);
3831 assert!(v["choices"][0]["message"]["content"].is_null());
3833 }
3834
3835 #[test]
3838 fn streaming_chunk_role_delta() {
3839 let chunk = ChatCompletionChunk {
3840 id: "id".into(),
3841 object: "chat.completion.chunk",
3842 created: 0,
3843 model: "m".into(),
3844 choices: vec![ChunkChoice {
3845 index: 0,
3846 delta: DeltaPayload {
3847 role: Some("assistant".into()),
3848 ..Default::default()
3849 },
3850 logprobs: None,
3851 finish_reason: None,
3852 }],
3853 usage: None,
3854 };
3855 let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3856 assert_eq!(v["object"], "chat.completion.chunk");
3857 assert_eq!(v["choices"][0]["delta"]["role"], "assistant");
3858 assert!(v["choices"][0]["delta"]["content"].is_null());
3860 assert!(v["choices"][0]["delta"]["reasoning_content"].is_null());
3861 assert!(v["choices"][0]["delta"]["tool_calls"].is_null());
3862 assert!(v["choices"][0]["finish_reason"].is_null());
3863 }
3864
3865 #[test]
3866 fn streaming_chunk_content_delta() {
3867 let chunk = ChatCompletionChunk {
3868 id: "id".into(),
3869 object: "chat.completion.chunk",
3870 created: 0,
3871 model: "m".into(),
3872 choices: vec![ChunkChoice {
3873 index: 0,
3874 delta: DeltaPayload {
3875 content: Some("hello".into()),
3876 ..Default::default()
3877 },
3878 logprobs: None,
3879 finish_reason: None,
3880 }],
3881 usage: None,
3882 };
3883 let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3884 assert_eq!(v["choices"][0]["delta"]["content"], "hello");
3885 assert!(v["choices"][0]["delta"]["role"].is_null());
3886 }
3887
3888 #[test]
3889 fn streaming_chunk_reasoning_content_delta() {
3890 let chunk = ChatCompletionChunk {
3891 id: "id".into(),
3892 object: "chat.completion.chunk",
3893 created: 0,
3894 model: "m".into(),
3895 choices: vec![ChunkChoice {
3896 index: 0,
3897 delta: DeltaPayload {
3898 reasoning_content: Some("thinking...".into()),
3899 ..Default::default()
3900 },
3901 logprobs: None,
3902 finish_reason: None,
3903 }],
3904 usage: None,
3905 };
3906 let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3907 assert_eq!(v["choices"][0]["delta"]["reasoning_content"], "thinking...");
3908 assert!(v["choices"][0]["delta"]["content"].is_null());
3909 }
3910
3911 #[test]
3912 fn streaming_chunk_tool_call_delta() {
3913 let chunk = ChatCompletionChunk {
3914 id: "id".into(),
3915 object: "chat.completion.chunk",
3916 created: 0,
3917 model: "m".into(),
3918 choices: vec![ChunkChoice {
3919 index: 0,
3920 delta: DeltaPayload {
3921 tool_calls: Some(vec![OAIToolCall {
3922 index: 0,
3923 id: "call_0".into(),
3924 kind: "function",
3925 function: OAIFunction {
3926 name: "bash".into(),
3927 arguments: r#"{"cmd":"ls"}"#.into(),
3928 },
3929 }]),
3930 ..Default::default()
3931 },
3932 logprobs: None,
3933 finish_reason: None,
3934 }],
3935 usage: None,
3936 };
3937 let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3938 let tc = &v["choices"][0]["delta"]["tool_calls"][0];
3939 assert_eq!(tc["index"], 0);
3940 assert_eq!(tc["type"], "function");
3941 assert_eq!(tc["function"]["name"], "bash");
3942 }
3943
3944 #[test]
3945 fn streaming_chunk_finish_reason() {
3946 let chunk = ChatCompletionChunk {
3947 id: "id".into(),
3948 object: "chat.completion.chunk",
3949 created: 0,
3950 model: "m".into(),
3951 choices: vec![ChunkChoice {
3952 index: 0,
3953 delta: DeltaPayload::default(), logprobs: None,
3955 finish_reason: Some("stop".into()),
3956 }],
3957 usage: None,
3958 };
3959 let v: serde_json::Value = serde_json::to_value(&chunk).unwrap();
3960 assert_eq!(v["choices"][0]["finish_reason"], "stop");
3961 assert!(v["choices"][0]["delta"]["content"].is_null());
3963 assert!(v["choices"][0]["delta"]["role"].is_null());
3964 }
3965
3966 #[test]
3969 fn models_response_serializes() {
3970 let resp = ModelsResponse {
3971 object: "list",
3972 data: vec![ModelCard {
3973 id: "my-model".into(),
3974 object: "model",
3975 owned_by: "local",
3976 }],
3977 };
3978 let v: serde_json::Value = serde_json::to_value(&resp).unwrap();
3979 assert_eq!(v["object"], "list");
3980 assert_eq!(v["data"][0]["id"], "my-model");
3981 assert_eq!(v["data"][0]["object"], "model");
3982 assert_eq!(v["data"][0]["owned_by"], "local");
3983 }
3984
3985 fn req(raw: &str) -> ChatRequest {
3988 serde_json::from_str(raw).unwrap()
3989 }
3990
3991 #[test]
3992 fn absent_sampling_fields_stay_none() {
3993 let p = GenParams::from_request(&req(
3996 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
3997 ))
3998 .unwrap();
3999 assert_eq!(p, GenParams::default());
4000 }
4001
4002 #[test]
4003 fn sampling_fields_parse() {
4004 let p = GenParams::from_request(&req(
4005 r#"{"model":"m","messages":[],"temperature":0.0,"top_p":0.9,"top_k":40,"seed":42,
4006 "presence_penalty":0.5,"frequency_penalty":-0.25,"repeat_penalty":1.1,
4007 "stop":["\n\n","END"]}"#,
4008 ))
4009 .unwrap();
4010 assert_eq!(p.temperature, Some(0.0));
4011 assert_eq!(p.top_p, Some(0.9));
4012 assert_eq!(p.top_k, Some(40));
4013 assert_eq!(p.seed, Some(42));
4014 assert_eq!(p.presence_penalty, Some(0.5));
4015 assert_eq!(p.frequency_penalty, Some(-0.25));
4016 assert_eq!(p.repeat_penalty, Some(1.1));
4017 assert_eq!(p.stop, vec!["\n\n".to_string(), "END".to_string()]);
4018 }
4019
4020 #[test]
4021 fn unknown_fields_are_ignored_not_rejected() {
4022 let p = GenParams::from_request(&req(
4023 r#"{"model":"m","messages":[],"user":"bob","response_format":{"type":"text"}}"#,
4024 ))
4025 .unwrap();
4026 assert_eq!(p, GenParams::default());
4027 }
4028
4029 #[test]
4032 fn neutral_choice_and_logprob_fields_are_accepted() {
4033 for raw in [
4034 r#"{"model":"m","messages":[],"n":1,"logprobs":false,"top_logprobs":0,"logit_bias":{}}"#,
4035 r#"{"model":"m","messages":[],"n":null,"logprobs":null,"top_logprobs":null,
4036 "logit_bias":null,"min_p":null}"#,
4037 ] {
4038 let p = GenParams::from_request(&req(raw)).unwrap();
4039 assert_eq!(p, GenParams::default(), "{raw}");
4040 }
4041 }
4042
4043 #[test]
4044 fn min_p_and_logit_bias_parse() {
4045 let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"min_p":0.05,
4046 "logit_bias":{"50256":-100,"7":3.5,"12":100}}"#))
4047 .unwrap();
4048 assert_eq!(p.min_p, Some(0.05));
4049 assert_eq!(p.logit_bias, vec![(7, 3.5), (12, 100.0), (50256, -100.0)]);
4050 }
4051
4052 #[test]
4055 fn zero_ids_and_whole_number_counts_are_accepted() {
4056 let p = GenParams::from_request(&req(
4057 r#"{"model":"m","messages":[],"n":1.0,"top_logprobs":0.0,"logit_bias":{"0":-1}}"#,
4058 ))
4059 .unwrap();
4060 assert_eq!(p.logit_bias, vec![(0, -1.0)]);
4061 }
4062
4063 #[test]
4065 fn logit_bias_ids_are_checked_against_the_vocabulary() {
4066 let p = GenParams::from_request(&req(
4067 r#"{"model":"m","messages":[],"logit_bias":{"999":1,"3":-1}}"#,
4068 ))
4069 .unwrap();
4070 assert_eq!(p.check_vocab(1000), Ok(()));
4071 let e = p.check_vocab(999).unwrap_err();
4072 assert_eq!(e.param, "logit_bias");
4073 assert!(e.message.contains("999"), "{}", e.message);
4074 }
4075
4076 #[test]
4077 fn max_completion_tokens_is_preferred_alias() {
4078 let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"max_tokens":10}"#))
4079 .unwrap();
4080 assert_eq!(p.max_tokens, Some(10));
4081 let p = GenParams::from_request(&req(
4082 r#"{"model":"m","messages":[],"max_completion_tokens":20}"#,
4083 ))
4084 .unwrap();
4085 assert_eq!(p.max_tokens, Some(20));
4086 let p = GenParams::from_request(&req(
4088 r#"{"model":"m","messages":[],"max_tokens":10,"max_completion_tokens":20}"#,
4089 ))
4090 .unwrap();
4091 assert_eq!(p.max_tokens, Some(20));
4092 }
4093
4094 #[test]
4095 fn logprobs_are_accepted_and_bounded() {
4096 let p = GenParams::from_request(&req(
4097 r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":5}"#,
4098 ))
4099 .unwrap();
4100 assert!(p.logprobs);
4101 assert_eq!(p.top_logprobs, 5);
4102
4103 let p = GenParams::from_request(&req(r#"{"model":"m","messages":[],"logprobs":true}"#))
4105 .unwrap();
4106 assert!(p.logprobs);
4107 assert_eq!(p.top_logprobs, MAX_TOP_LOGPROBS);
4108
4109 let p = GenParams::from_request(&req(
4110 r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":0}"#,
4111 ))
4112 .unwrap();
4113 assert!(p.logprobs);
4114 assert_eq!(p.top_logprobs, 0);
4115 }
4116
4117 #[test]
4118 fn stop_accepts_a_bare_string() {
4119 let p =
4120 GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":"\n"}"#)).unwrap();
4121 assert_eq!(p.stop, vec!["\n".to_string()]);
4122 }
4123
4124 #[test]
4125 fn empty_stop_strings_are_dropped() {
4126 let p =
4128 GenParams::from_request(&req(r#"{"model":"m","messages":[],"stop":["",""]}"#)).unwrap();
4129 assert!(p.stop.is_empty());
4130 }
4131
4132 #[test]
4133 fn invalid_values_are_param_errors_not_clamps() {
4134 for (raw, param) in [
4135 (
4136 r#"{"model":"m","messages":[],"temperature":-1}"#,
4137 "temperature",
4138 ),
4139 (
4140 r#"{"model":"m","messages":[],"temperature":3}"#,
4141 "temperature",
4142 ),
4143 (r#"{"model":"m","messages":[],"top_p":5}"#, "top_p"),
4144 (r#"{"model":"m","messages":[],"top_k":-2}"#, "top_k"),
4145 (
4146 r#"{"model":"m","messages":[],"presence_penalty":-3}"#,
4147 "presence_penalty",
4148 ),
4149 (
4150 r#"{"model":"m","messages":[],"frequency_penalty":9}"#,
4151 "frequency_penalty",
4152 ),
4153 (
4154 r#"{"model":"m","messages":[],"repeat_penalty":0}"#,
4155 "repeat_penalty",
4156 ),
4157 (r#"{"model":"m","messages":[],"stop":[1,2]}"#, "stop"),
4158 (
4159 r#"{"model":"m","messages":[],"stop":["a","b","c","d","e"]}"#,
4160 "stop",
4161 ),
4162 (r#"{"model":"m","messages":[],"min_p":-0.1}"#, "min_p"),
4163 (r#"{"model":"m","messages":[],"min_p":1.5}"#, "min_p"),
4164 (
4165 r#"{"model":"m","messages":[],"logit_bias":[1]}"#,
4166 "logit_bias",
4167 ),
4168 (
4169 r#"{"model":"m","messages":[],"logit_bias":{"a":1}}"#,
4170 "logit_bias",
4171 ),
4172 (
4173 r#"{"model":"m","messages":[],"logit_bias":{"-1":1}}"#,
4174 "logit_bias",
4175 ),
4176 (
4177 r#"{"model":"m","messages":[],"logit_bias":{"5":"x"}}"#,
4178 "logit_bias",
4179 ),
4180 (
4181 r#"{"model":"m","messages":[],"logit_bias":{"5":100.5}}"#,
4182 "logit_bias",
4183 ),
4184 (
4185 r#"{"model":"m","messages":[],"logit_bias":{"5":-101}}"#,
4186 "logit_bias",
4187 ),
4188 (r#"{"model":"m","messages":[],"n":2}"#, "n"),
4189 (r#"{"model":"m","messages":[],"n":0}"#, "n"),
4190 (
4191 r#"{"model":"m","messages":[],"top_logprobs":3}"#,
4192 "top_logprobs",
4193 ),
4194 (
4195 r#"{"model":"m","messages":[],"top_logprobs":-1}"#,
4196 "top_logprobs",
4197 ),
4198 (
4201 r#"{"model":"m","messages":[],"logit_bias":{"+5":-100}}"#,
4202 "logit_bias",
4203 ),
4204 (
4205 r#"{"model":"m","messages":[],"logit_bias":{"05":-100}}"#,
4206 "logit_bias",
4207 ),
4208 (
4209 r#"{"model":"m","messages":[],"logit_bias":{" 5":-100}}"#,
4210 "logit_bias",
4211 ),
4212 (
4213 r#"{"model":"m","messages":[],"logit_bias":{"":-100}}"#,
4214 "logit_bias",
4215 ),
4216 (
4218 r#"{"model":"m","messages":[],"logit_bias":{"5":-100,"5":-100}}"#,
4219 "logit_bias",
4220 ),
4221 (r#"{"model":"m","messages":[],"n":1.5}"#, "n"),
4222 (r#"{"model":"m","messages":[],"n":"1"}"#, "n"),
4223 (
4224 r#"{"model":"m","messages":[],"top_logprobs":0.5}"#,
4225 "top_logprobs",
4226 ),
4227 (
4228 r#"{"model":"m","messages":[],"top_logprobs":[]}"#,
4229 "top_logprobs",
4230 ),
4231 (
4232 r#"{"model":"m","messages":[],"logprobs":true,"top_logprobs":21}"#,
4233 "top_logprobs",
4234 ),
4235 ] {
4236 let e = GenParams::from_request(&req(raw)).unwrap_err();
4237 assert_eq!(e.param, param, "{raw}");
4238 }
4239 }
4240
4241 #[tokio::test]
4242 async fn bad_temperature_returns_openai_shaped_400() {
4243 let resp = test_router()
4244 .oneshot(
4245 Request::builder()
4246 .method("POST")
4247 .uri("/v1/chat/completions")
4248 .header("content-type", "application/json")
4249 .body(Body::from(
4250 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":-1}"#,
4251 ))
4252 .unwrap(),
4253 )
4254 .await
4255 .unwrap();
4256 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4257 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4258 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4259 assert_eq!(v["error"]["type"], "invalid_request_error");
4260 assert_eq!(v["error"]["param"], "temperature");
4261 }
4262
4263 fn run_stops(stops: &[&str], pieces: &[&str]) -> (String, bool) {
4267 let mut m = StopMatcher::new(stops.iter().map(|s| s.to_string()).collect());
4268 let mut out = String::new();
4269 for p in pieces {
4270 out.push_str(&m.push(p));
4271 if m.hit() {
4272 break;
4273 }
4274 }
4275 if !m.hit() {
4276 out.push_str(&m.flush());
4277 }
4278 (out, m.hit())
4279 }
4280
4281 #[test]
4282 fn stop_within_one_token_fires_and_is_excluded() {
4283 let (out, hit) = run_stops(&["END"], &["hello ", "END", " more"]);
4284 assert!(hit);
4285 assert_eq!(out, "hello ");
4286 }
4287
4288 #[test]
4289 fn stop_split_across_two_tokens_still_fires() {
4290 let (out, hit) = run_stops(&["END"], &["hello ", "E", "ND", " more"]);
4293 assert!(hit, "a stop split across tokens must fire");
4294 assert_eq!(out, "hello ", "no partial stop prefix may leak");
4295 }
4296
4297 #[test]
4298 fn stop_split_across_three_tokens_still_fires() {
4299 let (out, hit) = run_stops(&["<|done|>"], &["a", "<|", "do", "ne", "|>", "b"]);
4300 assert!(hit);
4301 assert_eq!(out, "a");
4302 }
4303
4304 #[test]
4305 fn double_newline_stop_split_across_tokens() {
4306 let (out, hit) = run_stops(&["\n\n"], &["line", "\n", "\n", "next"]);
4307 assert!(hit);
4308 assert_eq!(out, "line");
4309 }
4310
4311 #[test]
4312 fn stop_prefix_that_does_not_complete_is_eventually_emitted() {
4313 let (out, hit) = run_stops(&["END"], &["E", "very", " day"]);
4316 assert!(!hit);
4317 assert_eq!(out, "Every day");
4318 }
4319
4320 #[test]
4321 fn held_prefix_is_flushed_at_end_of_generation() {
4322 let (out, hit) = run_stops(&["END"], &["done E"]);
4324 assert!(!hit);
4325 assert_eq!(out, "done E");
4326 }
4327
4328 #[test]
4329 fn multiple_stops_take_the_earliest_match() {
4330 let (out, hit) = run_stops(&["World", "lo"], &["hel", "lo World"]);
4331 assert!(hit);
4332 assert_eq!(out, "hel");
4333 }
4334
4335 #[test]
4336 fn no_stops_is_a_passthrough() {
4337 let (out, hit) = run_stops(&[], &["a", "b", "c"]);
4338 assert!(!hit);
4339 assert_eq!(out, "abc");
4340 assert!(!StopMatcher::new(vec![]).is_active());
4341 }
4342
4343 #[test]
4344 fn multibyte_stop_split_mid_codepoint_is_safe() {
4345 let (out, hit) = run_stops(&["→END"], &["x", "→", "END", "y"]);
4348 assert!(hit);
4349 assert_eq!(out, "x");
4350 }
4351
4352 #[test]
4353 fn nothing_is_emitted_after_a_hit() {
4354 let mut m = StopMatcher::new(vec!["END".into()]);
4355 assert_eq!(m.push("aEND"), "a");
4356 assert!(m.hit());
4357 assert_eq!(m.push("more"), "");
4358 assert_eq!(m.flush(), "");
4359 }
4360
4361 #[test]
4364 fn finish_reason_strings() {
4365 assert_eq!(Finish::Stop.as_str(), "stop");
4366 assert_eq!(Finish::Length.as_str(), "length");
4367 assert_eq!(Finish::ToolCalls.as_str(), "tool_calls");
4368 }
4369
4370 #[test]
4373 fn flatten_content_string_value() {
4374 let v = Some(serde_json::Value::String("hello world".into()));
4375 assert_eq!(flatten_content(&v), "hello world");
4376 }
4377
4378 #[test]
4379 fn flatten_content_array_skips_non_text_parts() {
4380 let v = Some(serde_json::json!([
4381 {"type": "text", "text": "hello"},
4382 {"type": "image_url", "image_url": {"url": "http://x"}},
4383 {"type": "text", "text": " world"}
4384 ]));
4385 assert_eq!(flatten_content(&v), "hello world");
4386 }
4387
4388 #[test]
4389 fn flatten_content_none_gives_empty_string() {
4390 assert_eq!(flatten_content(&None), "");
4391 }
4392
4393 #[test]
4394 fn flatten_content_null_json_gives_empty_string() {
4395 assert_eq!(flatten_content(&Some(serde_json::Value::Null)), "");
4398 }
4399
4400 #[test]
4417 fn flatten_content_non_string_renders_json_leniently() {
4418 use serde_json::json;
4419 assert_eq!(flatten_content(&Some(json!(42))), "42");
4420 assert_eq!(flatten_content(&Some(json!(-1.5))), "-1.5");
4421 assert_eq!(flatten_content(&Some(json!(true))), "true");
4422 assert_eq!(flatten_content(&Some(json!(false))), "false");
4423 assert_eq!(flatten_content(&Some(json!({"a": 1}))), r#"{"a":1}"#);
4424 assert_eq!(
4425 flatten_content(&Some(json!({"a": "b", "c": [1, 2]}))),
4426 r#"{"a":"b","c":[1,2]}"#
4427 );
4428 }
4429
4430 #[test]
4433 fn make_id_is_unique_across_rapid_calls() {
4434 let n = 10_000;
4437 let ids: std::collections::HashSet<String> = (0..n).map(|_| make_id()).collect();
4438 assert_eq!(ids.len(), n, "make_id produced a collision");
4439 }
4440
4441 #[test]
4444 fn usage_total_is_prompt_plus_completion() {
4445 let outcome = ChatOutcome {
4447 finish: Finish::Stop,
4448 prompt_tokens: 17,
4449 completion_tokens: 5,
4450 cached_tokens: 0,
4451 };
4452 let usage = UsageInfo::from_outcome(&outcome);
4453 assert_eq!(usage.total_tokens, 22);
4454 assert_eq!(
4455 usage.total_tokens,
4456 usage.prompt_tokens + usage.completion_tokens
4457 );
4458 }
4459
4460 #[tokio::test]
4463 async fn non_streaming_usage_comes_from_generator() {
4464 let resp = multi_router()
4465 .oneshot(
4466 Request::builder()
4467 .method("POST")
4468 .uri("/v1/chat/completions")
4469 .header("content-type", "application/json")
4470 .body(Body::from(
4471 r#"{"model":"alpha","messages":[{"role":"user","content":"hi"}]}"#,
4472 ))
4473 .unwrap(),
4474 )
4475 .await
4476 .unwrap();
4477 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4478 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4479 assert_eq!(v["usage"]["prompt_tokens"], 3);
4480 assert_eq!(v["usage"]["completion_tokens"], 2);
4481 assert_eq!(v["usage"]["total_tokens"], 5);
4482 }
4483
4484 #[test]
4487 fn tool_choice_string_passes_through() {
4488 assert_eq!(
4489 tool_choice_str(&serde_json::json!("required")).unwrap(),
4490 Some("required".to_string())
4491 );
4492 assert_eq!(
4493 tool_choice_str(&serde_json::json!("auto")).unwrap(),
4494 Some("auto".to_string())
4495 );
4496 }
4497
4498 #[test]
4505 fn a_forced_tool_choice_needs_tools_that_can_satisfy_it() {
4506 let tools = serde_json::json!([{"function": {"name": "bash"}}]);
4507
4508 for choice in ["required", "bash"] {
4510 assert!(
4511 validate_tool_choice(Some(choice), None).is_err(),
4512 "{choice:?} with no tools must 400"
4513 );
4514 assert!(
4515 validate_tool_choice(Some(choice), Some(&serde_json::json!([]))).is_err(),
4516 "{choice:?} with an empty tools array must 400"
4517 );
4518 }
4519 assert!(validate_tool_choice(Some("bogus"), Some(&tools)).is_err());
4521
4522 assert!(validate_tool_choice(Some("auto"), None).is_ok());
4524 assert!(
4525 validate_tool_choice(Some("none"), None).is_ok(),
4526 "`none` asks for no tool call, which needs no tools"
4527 );
4528 assert!(validate_tool_choice(None, None).is_ok());
4529 assert!(validate_tool_choice(Some("required"), Some(&tools)).is_ok());
4530 assert!(validate_tool_choice(Some("bash"), Some(&tools)).is_ok());
4531 }
4532
4533 #[tokio::test]
4535 async fn forced_tool_choice_without_tools_is_a_400() {
4536 let resp = multi_router()
4537 .oneshot(
4538 Request::builder()
4539 .method("POST")
4540 .uri("/v1/chat/completions")
4541 .header("content-type", "application/json")
4542 .body(Body::from(
4543 r#"{"model":"a","messages":[{"role":"user","content":"hi"}],"tool_choice":"required"}"#,
4544 ))
4545 .unwrap(),
4546 )
4547 .await
4548 .unwrap();
4549 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4550 let v = body_json(resp).await;
4551 assert_eq!(v["error"]["param"], "tool_choice");
4552 assert_eq!(v["error"]["type"], "invalid_request_error");
4553 }
4554
4555 #[test]
4556 fn tool_choice_named_function_forces_that_tool() {
4557 let v = serde_json::json!({"type":"function","function":{"name":"bash"}});
4558 assert_eq!(tool_choice_str(&v).unwrap(), Some("bash".to_string()));
4559 }
4560
4561 #[test]
4562 fn tool_choice_object_without_name_is_an_error_not_auto() {
4563 let v = serde_json::json!({"type":"function","function":{}});
4566 let e = tool_choice_str(&v).unwrap_err();
4567 assert_eq!(e.param, "tool_choice");
4568 let v = serde_json::json!({"type":"function"});
4569 assert!(tool_choice_str(&v).is_err());
4570 }
4571
4572 #[test]
4573 fn tool_choice_wrong_shape_is_an_error() {
4574 assert!(tool_choice_str(&serde_json::json!(42)).is_err());
4575 assert!(tool_choice_str(&serde_json::json!(["auto"])).is_err());
4576 }
4577
4578 #[test]
4581 fn max_tokens_clamps_absurd_values_but_passes_unset_and_normal() {
4582 assert_eq!(clamp_max_tokens(None, 1000), None);
4585 assert_eq!(clamp_max_tokens(Some(512), 1000), Some(512));
4587 assert_eq!(clamp_max_tokens(Some(10_000_000), 1000), Some(1000));
4589 assert_eq!(clamp_max_tokens(Some(1000), 1000), Some(1000));
4591 }
4592
4593 #[test]
4596 fn auth_disabled_allows_everything() {
4597 assert!(authorize(None, None));
4599 assert!(authorize(None, Some("Bearer whatever")));
4600 assert!(authorize(None, Some("garbage")));
4601 }
4602
4603 #[test]
4604 fn auth_enabled_requires_matching_bearer() {
4605 let key = Some("s3cret");
4606 assert!(authorize(key, Some("Bearer s3cret")));
4608 assert!(authorize(key, Some("bearer s3cret")));
4609 assert!(!authorize(key, Some("Bearer wrong")));
4611 assert!(!authorize(key, None));
4612 assert!(!authorize(key, Some("s3cret")));
4613 assert!(!authorize(key, Some("Basic s3cret")));
4614 }
4615
4616 #[test]
4627 fn auth_compares_full_token_not_a_prefix() {
4628 let key = Some("s3cret");
4629 assert!(authorize(key, Some("Bearer s3cret")));
4631 assert!(!authorize(key, Some("Bearer s3creT")));
4633 assert!(!authorize(key, Some("Bearer S3cret")));
4635 assert!(!authorize(key, Some("Bearer s3c")));
4637 assert!(!authorize(key, Some("Bearer s")));
4638 assert!(!authorize(key, Some("Bearer ")));
4639 assert!(!authorize(key, Some("Bearer s3cretx")));
4641 assert!(authorize(key, Some("Bearer s3cret ")));
4644 assert!(!authorize(key, Some("Bearer s3cre ")));
4645 }
4646
4647 #[test]
4653 fn configured_api_key_reads_the_config_and_empty_still_means_no_auth() {
4654 let mut cfg = Config::default();
4655 assert_eq!(configured_api_key(&cfg), None, "unset => auth disabled");
4656
4657 cfg.serve.api_key = Some(String::new());
4658 assert_eq!(configured_api_key(&cfg), None, "empty => auth DISABLED");
4659
4660 cfg.serve.api_key = Some("hunter2".into());
4661 assert_eq!(configured_api_key(&cfg), Some("hunter2"));
4662 assert!(authorize(configured_api_key(&cfg), Some("Bearer hunter2")));
4664 assert!(!authorize(configured_api_key(&cfg), None));
4665 }
4666
4667 #[test]
4670 fn max_tokens_cap_reads_the_config_and_rejects_non_positive() {
4671 let mut cfg = Config::default();
4672 assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
4673
4674 cfg.serve.max_tokens_cap = 4096;
4675 assert_eq!(max_tokens_cap(&cfg), 4096);
4676 assert_eq!(
4677 clamp_max_tokens(Some(10_000), max_tokens_cap(&cfg)),
4678 Some(4096)
4679 );
4680
4681 cfg.serve.max_tokens_cap = 0;
4682 assert_eq!(max_tokens_cap(&cfg), DEFAULT_MAX_TOKENS_CAP);
4683 }
4684
4685 #[tokio::test]
4689 async fn configured_api_key_gates_the_chat_endpoint() {
4690 let mut cfg = Config::default();
4691 cfg.serve.api_key = Some("s3cret".into());
4692 let state = AppState::headless("test-model", Arc::new(cfg));
4693 let body = r#"{"model":"test-model","messages":[{"role":"user","content":"hi"}]}"#;
4694 let req = |auth: Option<&str>| {
4695 let mut b = Request::builder()
4696 .method("POST")
4697 .uri("/v1/chat/completions")
4698 .header("content-type", "application/json");
4699 if let Some(a) = auth {
4700 b = b.header("authorization", a);
4701 }
4702 b.body(Body::from(body)).unwrap()
4703 };
4704 let resp = build_router(state.clone())
4705 .oneshot(req(None))
4706 .await
4707 .unwrap();
4708 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4709 let resp = build_router(state)
4712 .oneshot(req(Some("Bearer s3cret")))
4713 .await
4714 .unwrap();
4715 assert_ne!(resp.status(), StatusCode::UNAUTHORIZED);
4716 }
4717
4718 #[tokio::test]
4723 async fn configured_api_key_gates_models_but_never_health() {
4724 let mut cfg = Config::default();
4725 cfg.serve.api_key = Some("s3cret".into());
4726 let state = AppState::headless("test-model", Arc::new(cfg));
4727 let get = |uri: &str, auth: Option<&str>| {
4728 let mut b = Request::builder().uri(uri);
4729 if let Some(a) = auth {
4730 b = b.header("authorization", a);
4731 }
4732 b.body(Body::empty()).unwrap()
4733 };
4734
4735 let resp = build_router(state.clone())
4737 .oneshot(get("/v1/models", None))
4738 .await
4739 .unwrap();
4740 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4741 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4742 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4743 assert_eq!(v["error"]["type"], "invalid_request_error");
4744 assert_eq!(v["error"]["code"], "invalid_api_key");
4745 assert_eq!(
4746 v["error"]["message"],
4747 "missing or invalid Authorization bearer token"
4748 );
4749 assert!(
4751 !String::from_utf8_lossy(&bytes).contains("test-model"),
4752 "a 401 must not disclose the model set: {bytes:?}"
4753 );
4754
4755 let resp = build_router(state.clone())
4757 .oneshot(get("/v1/models", Some("Bearer wrong")))
4758 .await
4759 .unwrap();
4760 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
4761
4762 let resp = build_router(state.clone())
4764 .oneshot(get("/v1/models", Some("Bearer s3cret")))
4765 .await
4766 .unwrap();
4767 assert_eq!(resp.status(), StatusCode::OK);
4768 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4769 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4770 assert_eq!(v["object"], "list");
4771 assert_eq!(v["data"][0]["id"], "test-model");
4772 assert_eq!(v["data"][0]["object"], "model");
4773 assert_eq!(v["data"][0]["owned_by"], "local");
4774
4775 for auth in [None, Some("Bearer s3cret")] {
4777 let resp = build_router(state.clone())
4778 .oneshot(get("/health", auth))
4779 .await
4780 .unwrap();
4781 assert_eq!(resp.status(), StatusCode::OK, "auth={auth:?}");
4782 }
4783 }
4784
4785 #[test]
4790 fn request_timeout_is_off_by_default_and_zero_means_unbounded() {
4791 let mut cfg = Config::default();
4792 assert_eq!(request_timeout(&cfg), None, "default => no deadline");
4793
4794 cfg.serve.request_timeout_secs = 0;
4795 assert_eq!(request_timeout(&cfg), None, "0 => no deadline");
4796
4797 cfg.serve.request_timeout_secs = 300;
4798 assert_eq!(request_timeout(&cfg), Some(Duration::from_secs(300)));
4799 }
4800
4801 struct LoopGen;
4807 impl ChatGenerator for LoopGen {
4808 fn status(&self) -> GeneratorStatus {
4809 cpu_status()
4810 }
4811
4812 fn vocab_size(&self) -> usize {
4813 TEST_VOCAB
4814 }
4815
4816 fn chat(
4817 &self,
4818 _messages: &[ChatMessage],
4819 _tools: Option<&serde_json::Value>,
4820 _tool_choice: Option<&str>,
4821 _params: &GenParams,
4822 cancel: &Arc<AtomicBool>,
4823 on_delta: &mut dyn FnMut(Delta),
4824 ) -> anyhow::Result<ChatOutcome> {
4825 on_delta(Delta::Content("partial".into()));
4826 while !cancel.load(Ordering::Relaxed) {
4827 std::thread::sleep(Duration::from_millis(2));
4828 }
4829 Ok(ChatOutcome {
4830 finish: Finish::Stop,
4831 prompt_tokens: 3,
4832 completion_tokens: 1,
4833 cached_tokens: 0,
4834 })
4835 }
4836 }
4837
4838 fn deadline_entry(generator: Arc<dyn ChatGenerator>) -> ModelEntry {
4842 AppState::new(generator, "m", 1, Arc::new(Config::default())).route("m")
4843 }
4844
4845 fn test_ctx(deadline: Option<Duration>, stream: bool) -> ReqCtx {
4849 ReqCtx {
4850 id: next_req_id(),
4851 cid: "cid".into(),
4852 model_id: "m".into(),
4853 created: 0,
4854 deadline,
4855 keep_alive: None,
4856 stream,
4857 include_usage: false,
4858 stats: Arc::default(),
4859 }
4860 }
4861
4862 fn user_msg() -> Vec<ChatMessage> {
4863 vec![ChatMessage {
4864 role: "user".into(),
4865 content: "hi".into(),
4866 tool_calls: None,
4867 tool_call_id: None,
4868 name: None,
4869 }]
4870 }
4871
4872 async fn body_json(resp: Response) -> serde_json::Value {
4873 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4874 serde_json::from_slice(&bytes).unwrap()
4875 }
4876
4877 #[tokio::test]
4880 async fn non_streaming_deadline_returns_partial_content_as_length() {
4881 let started = std::time::Instant::now();
4882 let resp = non_streaming(
4883 deadline_entry(Arc::new(LoopGen)),
4884 None,
4885 user_msg(),
4886 None,
4887 None,
4888 GenParams::default(),
4889 test_ctx(Some(Duration::from_millis(150)), false),
4890 )
4891 .await;
4892 assert_eq!(resp.status(), StatusCode::OK, "a deadline is not a failure");
4893 let v = body_json(resp).await;
4894 assert_eq!(v["choices"][0]["finish_reason"], "length");
4895 assert_eq!(
4896 v["choices"][0]["message"]["content"], "partial",
4897 "the partial completion must survive the deadline"
4898 );
4899 assert!(
4902 started.elapsed() < Duration::from_secs(5),
4903 "the deadline did not stop the generator"
4904 );
4905 }
4906
4907 #[tokio::test]
4911 async fn deadline_frees_the_slot_for_the_next_request() {
4912 let entry = deadline_entry(Arc::new(LoopGen));
4913 for _ in 0..2 {
4914 let resp = non_streaming(
4915 entry.clone(),
4916 None,
4917 user_msg(),
4918 None,
4919 None,
4920 GenParams::default(),
4921 test_ctx(Some(Duration::from_millis(100)), false),
4922 )
4923 .await;
4924 assert_eq!(
4925 body_json(resp).await["choices"][0]["finish_reason"],
4926 "length"
4927 );
4928 }
4929 assert_eq!(
4930 entry.slots.available_permits(),
4931 1,
4932 "the slot must be back after a deadline hit"
4933 );
4934 }
4935
4936 #[tokio::test]
4939 async fn generation_inside_the_deadline_is_untouched() {
4940 let resp = non_streaming(
4941 deadline_entry(Arc::new(EchoGen("alpha"))),
4942 None,
4943 user_msg(),
4944 None,
4945 None,
4946 GenParams::default(),
4947 test_ctx(Some(Duration::from_secs(30)), false),
4948 )
4949 .await;
4950 let v = body_json(resp).await;
4951 assert_eq!(v["choices"][0]["finish_reason"], "stop");
4952 assert_eq!(v["choices"][0]["message"]["content"], "from:alpha");
4953 }
4954
4955 #[tokio::test]
4958 async fn streaming_deadline_finishes_with_length() {
4959 let resp = streaming(
4960 deadline_entry(Arc::new(LoopGen)),
4961 None,
4962 user_msg(),
4963 None,
4964 None,
4965 GenParams::default(),
4966 test_ctx(Some(Duration::from_millis(150)), true),
4967 )
4968 .await;
4969 assert_eq!(resp.status(), StatusCode::OK);
4970 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
4971 let text = String::from_utf8(bytes.to_vec()).unwrap();
4972 assert!(text.contains("partial"), "partial content lost: {text}");
4973 assert!(
4974 text.contains("\"finish_reason\":\"length\""),
4975 "a deadline hit must finish as `length`: {text}"
4976 );
4977 assert!(
4978 !text.contains("\"finish_reason\":\"stop\""),
4979 "the generator's `stop` must not reach the wire: {text}"
4980 );
4981 assert!(text.contains("[DONE]"), "sentinel missing: {text}");
4982 }
4983
4984 #[tokio::test]
4989 async fn dropping_the_done_signal_disarms_the_watchdog() {
4990 let cancel = Arc::new(AtomicBool::new(false));
4991 let hit = Arc::new(AtomicBool::new(false));
4992 let done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
4993 drop(done_tx); tokio::time::sleep(Duration::from_millis(200)).await;
4995 assert!(
4996 !cancel.load(Ordering::Relaxed) && !hit.load(Ordering::Relaxed),
4997 "a disarmed watchdog must never fire"
4998 );
4999
5000 let cancel = Arc::new(AtomicBool::new(false));
5003 let hit = Arc::new(AtomicBool::new(false));
5004 let _done_tx = arm_deadline(Duration::from_millis(50), cancel.clone(), hit.clone());
5005 tokio::time::sleep(Duration::from_millis(200)).await;
5006 assert!(cancel.load(Ordering::Relaxed) && hit.load(Ordering::Relaxed));
5007 }
5008
5009 struct FailGen;
5014 impl ChatGenerator for FailGen {
5015 fn status(&self) -> GeneratorStatus {
5016 cpu_status()
5017 }
5018
5019 fn vocab_size(&self) -> usize {
5020 TEST_VOCAB
5021 }
5022
5023 fn chat(
5024 &self,
5025 _messages: &[ChatMessage],
5026 _tools: Option<&serde_json::Value>,
5027 _tool_choice: Option<&str>,
5028 _params: &GenParams,
5029 _cancel: &Arc<AtomicBool>,
5030 on_delta: &mut dyn FnMut(Delta),
5031 ) -> anyhow::Result<ChatOutcome> {
5032 on_delta(Delta::Content("partial".into()));
5033 anyhow::bail!("boom mid-stream")
5034 }
5035 }
5036
5037 #[tokio::test]
5038 async fn streaming_error_emits_error_frame_not_stop() {
5039 let g: Arc<dyn ChatGenerator> = Arc::new(FailGen);
5040 let router = build_router(AppState::new(g, "m", 1, Arc::new(Config::default())));
5041 let resp = router
5042 .oneshot(
5043 Request::builder()
5044 .method("POST")
5045 .uri("/v1/chat/completions")
5046 .header("content-type", "application/json")
5047 .body(Body::from(
5048 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
5049 ))
5050 .unwrap(),
5051 )
5052 .await
5053 .unwrap();
5054 assert_eq!(resp.status(), StatusCode::OK);
5055 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5056 let text = String::from_utf8(bytes.to_vec()).unwrap();
5057 assert!(text.contains("\"error\""), "missing error frame: {text}");
5060 assert!(
5061 text.contains("boom mid-stream"),
5062 "error message lost: {text}"
5063 );
5064 assert!(text.contains("[DONE]"), "sentinel missing: {text}");
5065 assert!(
5066 !text.contains("\"finish_reason\":\"stop\""),
5067 "an Err must not report a clean stop: {text}"
5068 );
5069 }
5070
5071 struct RefusingGen;
5074 impl ChatGenerator for RefusingGen {
5075 fn status(&self) -> GeneratorStatus {
5076 cpu_status()
5077 }
5078
5079 fn vocab_size(&self) -> usize {
5080 TEST_VOCAB
5081 }
5082
5083 fn chat(
5084 &self,
5085 _messages: &[ChatMessage],
5086 _tools: Option<&serde_json::Value>,
5087 _tool_choice: Option<&str>,
5088 _params: &GenParams,
5089 _cancel: &Arc<AtomicBool>,
5090 _on_delta: &mut dyn FnMut(Delta),
5091 ) -> anyhow::Result<ChatOutcome> {
5092 Err(ParamError {
5093 param: "min_p",
5094 message: "min_p is not supported by the test backend".into(),
5095 }
5096 .into())
5097 }
5098 }
5099
5100 #[tokio::test]
5103 async fn a_generator_param_error_is_a_400_naming_the_field() {
5104 let gen: Arc<dyn ChatGenerator> = Arc::new(RefusingGen);
5105 let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
5106 let resp = post_chat(router_for(gen.clone()), &format!("{{{base}}}")).await;
5107 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5108 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5109 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
5110 assert_eq!(v["error"]["type"], "invalid_request_error");
5111 assert_eq!(v["error"]["param"], "min_p");
5112 let resp = post_chat(router_for(gen), &format!(r#"{{{base},"stream":true}}"#)).await;
5113 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5114 let text = String::from_utf8(bytes.to_vec()).unwrap();
5115 assert!(text.contains(r#""param":"min_p""#), "{text}");
5116 assert!(text.contains("invalid_request_error"), "{text}");
5117 }
5118
5119 struct PanicGen;
5123 impl ChatGenerator for PanicGen {
5124 fn status(&self) -> GeneratorStatus {
5125 cpu_status()
5126 }
5127
5128 fn vocab_size(&self) -> usize {
5129 TEST_VOCAB
5130 }
5131
5132 fn chat(
5133 &self,
5134 _messages: &[ChatMessage],
5135 _tools: Option<&serde_json::Value>,
5136 _tool_choice: Option<&str>,
5137 _params: &GenParams,
5138 _cancel: &Arc<AtomicBool>,
5139 on_delta: &mut dyn FnMut(Delta),
5140 ) -> anyhow::Result<ChatOutcome> {
5141 on_delta(Delta::Content("partial".into()));
5142 panic!("boom: generator panicked mid-stream")
5143 }
5144 }
5145
5146 #[tokio::test]
5152 async fn streaming_panic_is_reported_as_a_failure() {
5153 let g: Arc<dyn ChatGenerator> = Arc::new(PanicGen);
5154 let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
5155 let stats = state.stats.clone();
5156 let router = build_router(state);
5157 let resp = router
5161 .oneshot(
5162 Request::builder()
5163 .method("POST")
5164 .uri("/v1/chat/completions")
5165 .header("content-type", "application/json")
5166 .body(Body::from(
5167 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
5168 ))
5169 .unwrap(),
5170 )
5171 .await
5172 .unwrap();
5173 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5174 let text = String::from_utf8(bytes.to_vec()).unwrap();
5175
5176 assert!(
5177 text.contains("\"error\""),
5178 "a panicking generator must still put a terminal error frame on the wire: {text}"
5179 );
5180 assert!(text.contains("[DONE]"), "sentinel missing: {text}");
5181 assert!(
5182 !text.contains("\"finish_reason\":\"stop\""),
5183 "a panic must never look like a clean stop: {text}"
5184 );
5185
5186 let w = stats.drain(Duration::from_secs(1));
5187 assert_eq!(w.failed, 1, "the panic must be counted as a failure");
5188 assert_eq!(
5189 w.completed, 1,
5190 "a failure is still a completed request for the interval line"
5191 );
5192 assert_eq!(w.active, 0, "the slot gauge must be released by the unwind");
5193 }
5194
5195 #[test]
5199 fn send_failure_latches_the_cancel_flag() {
5200 let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<Event, Infallible>>();
5201 let cancel = AtomicBool::new(false);
5202 drop(rx); if tx.send(Ok(Event::default().data("x"))).is_err() {
5204 cancel.store(true, Ordering::Relaxed);
5205 }
5206 assert!(
5207 cancel.load(Ordering::Relaxed),
5208 "a failed send must latch the abort flag so the decode loop stops"
5209 );
5210 }
5211
5212 fn rec(prompt: u32, gen: u32, deltas: u64) -> ReqRecord {
5219 rec_in_window(prompt, gen, deltas, 0, deltas)
5220 }
5221
5222 fn rec_in_window(
5224 prompt: u32,
5225 gen: u32,
5226 deltas: u64,
5227 window: u64,
5228 deltas_in_window: u64,
5229 ) -> ReqRecord {
5230 ReqRecord {
5231 prompt_tokens: prompt,
5232 gen_tokens: gen,
5233 deltas,
5234 window,
5235 deltas_in_window,
5236 prefill: Duration::from_millis(100),
5237 decode: Duration::from_millis(400),
5238 total: Duration::from_millis(500),
5239 finish: Finish::Stop,
5240 }
5241 }
5242
5243 #[test]
5252 fn stats_windows_cover_the_interval_and_never_accumulate() {
5253 let stats = ServeStats::default();
5254 let window = Duration::from_secs(2);
5255
5256 for _ in 0..20 {
5257 stats.bump_gen(1);
5258 }
5259 stats.fold_completion(&rec(100, 20, 20));
5260 let busy = stats.drain(window);
5261 assert_eq!(
5262 (busy.prompt_tokens, busy.gen_tokens, busy.completed),
5263 (100, 20, 1)
5264 );
5265 assert!((busy.decode_tps() - 10.0).abs() < 1e-9, "{busy:?}");
5266 assert!((busy.prefill_tps() - 50.0).abs() < 1e-9, "{busy:?}");
5267
5268 for _ in 0..10 {
5269 stats.bump_gen(1);
5270 }
5271 stats.fold_completion(&rec(20, 10, 10));
5272 let quieter = stats.drain(window);
5273 assert_eq!((quieter.prompt_tokens, quieter.gen_tokens), (20, 10));
5274 assert!(
5275 (quieter.decode_tps() - 5.0).abs() < 1e-9,
5276 "the second interval must report only ITS OWN 10 tokens: {quieter:?}"
5277 );
5278 assert!(
5279 quieter.decode_tps() < busy.decode_tps() && quieter.prefill_tps() < busy.prefill_tps(),
5280 "half the work in the same wall time must report a LOWER rate: {busy:?} then {quieter:?}"
5281 );
5282
5283 let idle = stats.drain(window);
5284 assert_eq!(
5285 (idle.gen_tokens, idle.prompt_tokens, idle.completed),
5286 (0, 0, 0)
5287 );
5288 assert_eq!(idle.decode_tps(), 0.0);
5289 assert!(
5290 !idle.has_activity(),
5291 "an interval with nothing in it must emit no line: {idle:?}"
5292 );
5293 }
5294
5295 #[test]
5299 fn the_live_delta_count_is_reconciled_against_the_real_token_count() {
5300 let under = ServeStats::default();
5302 for _ in 0..3 {
5303 under.bump_gen(1);
5304 }
5305 under.fold_completion(&rec(1, 5, 3));
5306 assert_eq!(under.drain(Duration::from_secs(1)).gen_tokens, 5);
5307
5308 let over = ServeStats::default();
5310 for _ in 0..6 {
5311 over.bump_gen(1);
5312 }
5313 over.fold_completion(&rec(1, 4, 6));
5314 assert_eq!(over.drain(Duration::from_secs(1)).gen_tokens, 4);
5315 }
5316
5317 #[test]
5323 fn a_correction_never_retracts_another_requests_tokens() {
5324 let s = ServeStats::default();
5325
5326 let mut a = ReqTally::new();
5328 a.on_text_delta(&s);
5329 a.on_text_delta(&s);
5330 let w1 = s.drain(Duration::from_secs(1));
5331 assert_eq!(w1.gen_tokens, 2, "the open window had A's two deltas");
5332
5333 let mut b = ReqTally::new();
5335 for _ in 0..3 {
5336 b.on_text_delta(&s);
5337 }
5338
5339 s.fold_completion(&a.finish(
5342 ChatOutcome {
5343 finish: Finish::Stop,
5344 prompt_tokens: 1,
5345 completion_tokens: 1,
5346 cached_tokens: 0,
5347 },
5348 Finish::Stop,
5349 ));
5350
5351 let w2 = s.drain(Duration::from_secs(1));
5352 assert_eq!(
5353 w2.gen_tokens, 3,
5354 "B's three tokens must survive A's correction — the −1 belongs to a closed window"
5355 );
5356 }
5357
5358 #[test]
5361 fn a_correction_applies_within_the_open_window_and_is_clamped_to_its_own_deltas() {
5362 let s = ServeStats::default();
5363 let mut a = ReqTally::new();
5364 for _ in 0..4 {
5365 a.on_text_delta(&s);
5366 }
5367 s.fold_completion(&a.finish(
5369 ChatOutcome {
5370 finish: Finish::Stop,
5371 prompt_tokens: 1,
5372 completion_tokens: 2,
5373 cached_tokens: 0,
5374 },
5375 Finish::Stop,
5376 ));
5377 assert_eq!(s.drain(Duration::from_secs(1)).gen_tokens, 2);
5378
5379 let s = ServeStats::default();
5382 let mut c = ReqTally::new();
5383 c.on_text_delta(&s);
5384 for _ in 0..5 {
5385 s.bump_gen(1); }
5387 let mut r = c.finish(
5388 ChatOutcome {
5389 finish: Finish::Stop,
5390 prompt_tokens: 0,
5391 completion_tokens: 0,
5392 cached_tokens: 0,
5393 },
5394 Finish::Stop,
5395 );
5396 r.deltas = 4; s.fold_completion(&r);
5398 assert_eq!(
5399 s.drain(Duration::from_secs(1)).gen_tokens,
5400 5,
5401 "the retraction is capped at this request's own contribution to the window"
5402 );
5403 }
5404
5405 #[test]
5410 fn in_flight_requests_are_activity_and_an_empty_interval_is_not() {
5411 let stats = Arc::new(ServeStats::default());
5412 let w = Duration::from_secs(1);
5413 assert!(!stats.drain(w).has_activity(), "idle must be silent");
5414
5415 let generating = ActiveGuard::new(stats.clone());
5416 assert!(
5417 stats.drain(w).has_activity(),
5418 "a generation in flight is activity even before it yields a token"
5419 );
5420 drop(generating);
5421 assert!(!stats.drain(w).has_activity());
5422
5423 let waiting = QueuedGuard::new(stats.clone());
5424 assert!(
5425 stats.drain(w).has_activity(),
5426 "a request queued for a slot is activity"
5427 );
5428 drop(waiting);
5429 assert!(!stats.drain(w).has_activity());
5430 }
5431
5432 #[test]
5436 fn the_active_gauge_is_released_by_an_unwinding_panic() {
5437 let stats = Arc::new(ServeStats::default());
5438 let inner = stats.clone();
5439 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
5440 let _active = ActiveGuard::new(inner);
5441 panic!("decode closure blew up");
5442 }));
5443 assert!(caught.is_err(), "the panic must have happened");
5444 assert_eq!(stats.active.load(Ordering::Relaxed), 0);
5445 }
5446
5447 #[test]
5449 fn stats_interval_defaults_to_five_seconds_and_zero_disables_it() {
5450 let mut cfg = Config::default();
5451 assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(5)));
5452 cfg.serve.stats_interval_secs = 0;
5453 assert_eq!(stats_interval(&cfg), None, "0 => no periodic line at all");
5454 cfg.serve.stats_interval_secs = 30;
5455 assert_eq!(stats_interval(&cfg), Some(Duration::from_secs(30)));
5456 }
5457
5458 #[tokio::test]
5461 async fn slot_occupancy_counts_held_permits_across_models() {
5462 let a: Arc<dyn ChatGenerator> = Arc::new(EchoGen("alpha"));
5463 let b: Arc<dyn ChatGenerator> = Arc::new(EchoGen("beta"));
5464 let state = AppState::multi(
5465 vec![("alpha".into(), a, 3), ("beta".into(), b, 1)],
5466 Arc::new(Config::default()),
5467 );
5468 assert_eq!(state.slot_occupancy(), (0, 4));
5469 let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
5470 assert_eq!(state.slot_occupancy(), (1, 4));
5471 let held2 = state.models[1].slots.clone().acquire_owned().await.unwrap();
5472 assert_eq!(state.slot_occupancy(), (2, 4));
5473 drop(held);
5474 drop(held2);
5475 assert_eq!(state.slot_occupancy(), (0, 4));
5476 }
5477
5478 #[test]
5481 fn request_ids_are_monotonic_and_distinct() {
5482 let ids: Vec<u64> = (0..1000).map(|_| next_req_id()).collect();
5486 assert!(
5487 ids.windows(2).all(|w| w[1] > w[0]),
5488 "ids must increase monotonically"
5489 );
5490 let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
5491 assert_eq!(unique.len(), ids.len(), "ids must never repeat");
5492 }
5493
5494 #[tokio::test]
5499 async fn a_served_request_folds_its_counts_into_the_window() {
5500 let stats: Arc<ServeStats> = Arc::default();
5501 let ctx = ReqCtx {
5502 stats: stats.clone(),
5503 ..test_ctx(None, false)
5504 };
5505 let resp = non_streaming(
5506 deadline_entry(Arc::new(EchoGen("alpha"))),
5507 None,
5508 user_msg(),
5509 None,
5510 None,
5511 GenParams::default(),
5512 ctx,
5513 )
5514 .await;
5515 assert_eq!(resp.status(), StatusCode::OK);
5516 let w = stats.drain(Duration::from_secs(1));
5517 assert_eq!(
5518 (w.prompt_tokens, w.gen_tokens, w.completed, w.failed),
5519 (3, 2, 1, 0),
5520 "EchoGen reports prompt_tokens=3, completion_tokens=2 for one request: {w:?}"
5521 );
5522 assert_eq!(
5523 (w.active, w.queued),
5524 (0, 0),
5525 "both gauges must be back at zero once the request is answered"
5526 );
5527 }
5528
5529 #[tokio::test]
5532 async fn a_failed_request_is_counted_as_a_failure() {
5533 let stats: Arc<ServeStats> = Arc::default();
5534 let ctx = ReqCtx {
5535 stats: stats.clone(),
5536 ..test_ctx(None, false)
5537 };
5538 let resp = non_streaming(
5539 deadline_entry(Arc::new(FailGen)),
5540 None,
5541 user_msg(),
5542 None,
5543 None,
5544 GenParams::default(),
5545 ctx,
5546 )
5547 .await;
5548 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
5549 let w = stats.drain(Duration::from_secs(1));
5550 assert_eq!((w.completed, w.failed), (1, 1), "{w:?}");
5551 assert!(
5552 w.has_activity(),
5553 "an interval of failures is not an idle one"
5554 );
5555 }
5556
5557 async fn post_chat(router: Router, body: &str) -> Response {
5561 router
5562 .oneshot(
5563 Request::builder()
5564 .method("POST")
5565 .uri("/v1/chat/completions")
5566 .header("content-type", "application/json")
5567 .body(Body::from(body.to_owned()))
5568 .unwrap(),
5569 )
5570 .await
5571 .unwrap()
5572 }
5573
5574 struct VocabCountingGen(Arc<AtomicU64>);
5576 impl ChatGenerator for VocabCountingGen {
5577 fn status(&self) -> GeneratorStatus {
5578 cpu_status()
5579 }
5580
5581 fn vocab_size(&self) -> usize {
5582 self.0.fetch_add(1, Ordering::Relaxed);
5583 TEST_VOCAB
5584 }
5585
5586 fn chat(
5587 &self,
5588 _messages: &[ChatMessage],
5589 _tools: Option<&serde_json::Value>,
5590 _tool_choice: Option<&str>,
5591 _params: &GenParams,
5592 _cancel: &Arc<AtomicBool>,
5593 on_delta: &mut dyn FnMut(Delta),
5594 ) -> anyhow::Result<ChatOutcome> {
5595 on_delta(Delta::Content("ok".into()));
5596 Ok(ChatOutcome {
5597 finish: Finish::Stop,
5598 prompt_tokens: 1,
5599 completion_tokens: 1,
5600 cached_tokens: 0,
5601 })
5602 }
5603 }
5604
5605 #[tokio::test]
5608 async fn the_vocab_size_is_read_only_for_a_logit_bias() {
5609 let calls = Arc::new(AtomicU64::new(0));
5610 let gen: Arc<dyn ChatGenerator> = Arc::new(VocabCountingGen(calls.clone()));
5611 let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
5612 for extra in ["", r#","logit_bias":{}"#, r#","logit_bias":null"#] {
5613 let resp = post_chat(router_for(gen.clone()), &format!("{{{base}{extra}}}")).await;
5614 assert_eq!(resp.status(), StatusCode::OK);
5615 }
5616 assert_eq!(calls.load(Ordering::Relaxed), 0, "asked without a bias");
5617 let body = format!(r#"{{{base},"logit_bias":{{"3":-100}}}}"#);
5618 let resp = post_chat(router_for(gen), &body).await;
5619 assert_eq!(resp.status(), StatusCode::OK);
5620 assert_eq!(calls.load(Ordering::Relaxed), 1, "the bias was not checked");
5621 }
5622
5623 #[tokio::test]
5627 async fn unsupported_and_invalid_sampling_fields_are_400s() {
5628 let gen: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
5629 let base = r#""model":"m","messages":[{"role":"user","content":"hi"}]"#;
5630 let vocab = TEST_VOCAB;
5631 for stream in [false, true] {
5632 for (extra, param) in [
5633 (r#""n":2"#.to_string(), "n"),
5634 (r#""logprobs":true"#.to_string(), "logprobs"),
5635 (r#""top_logprobs":2"#.to_string(), "top_logprobs"),
5636 (r#""min_p":2"#.to_string(), "min_p"),
5637 (r#""logit_bias":{"1":-150}"#.to_string(), "logit_bias"),
5638 (format!(r#""logit_bias":{{"{vocab}":-100}}"#), "logit_bias"),
5639 (
5640 r#""logit_bias":{"5":-100,"+5":-100}"#.to_string(),
5641 "logit_bias",
5642 ),
5643 (r#""n":"2""#.to_string(), "n"),
5644 (r#""top_logprobs":1.5"#.to_string(), "top_logprobs"),
5645 ] {
5646 let body = format!(r#"{{{base},"stream":{stream},{extra}}}"#);
5647 let resp = post_chat(router_for(gen.clone()), &body).await;
5648 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{body}");
5649 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5650 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
5651 assert_eq!(v["error"]["type"], "invalid_request_error", "{body}");
5652 assert_eq!(v["error"]["param"], param, "{body}");
5653 }
5654 }
5655 let last = vocab - 1;
5656 let body = format!(
5657 r#"{{{base},"n":1.0,"logprobs":false,"top_logprobs":0,"min_p":0.1,
5658 "logit_bias":{{"{last}":-100}}}}"#
5659 );
5660 let resp = post_chat(router_for(gen), &body).await;
5661 assert_eq!(resp.status(), StatusCode::OK, "{body}");
5662 }
5663
5664 fn router_for(generator: Arc<dyn ChatGenerator>) -> Router {
5665 build_router(AppState::new(
5666 generator,
5667 "m",
5668 1,
5669 Arc::new(Config::default()),
5670 ))
5671 }
5672
5673 struct CachedPrefixGen;
5676 impl ChatGenerator for CachedPrefixGen {
5677 fn status(&self) -> GeneratorStatus {
5678 cpu_status()
5679 }
5680
5681 fn vocab_size(&self) -> usize {
5682 TEST_VOCAB
5683 }
5684
5685 fn chat(
5686 &self,
5687 _messages: &[ChatMessage],
5688 _tools: Option<&serde_json::Value>,
5689 _tool_choice: Option<&str>,
5690 _params: &GenParams,
5691 _cancel: &Arc<AtomicBool>,
5692 on_delta: &mut dyn FnMut(Delta),
5693 ) -> anyhow::Result<ChatOutcome> {
5694 on_delta(Delta::Content("ok".into()));
5695 Ok(ChatOutcome {
5696 finish: Finish::Stop,
5697 prompt_tokens: 20,
5698 completion_tokens: 1,
5699 cached_tokens: 19,
5700 })
5701 }
5702 }
5703
5704 #[tokio::test]
5708 async fn usage_counts_the_whole_prompt_and_reports_the_cached_part() {
5709 let g: Arc<dyn ChatGenerator> = Arc::new(CachedPrefixGen);
5710 let state = AppState::new(g, "m", 1, Arc::new(Config::default()));
5711 let stats = state.stats.clone();
5712 let resp = post_chat(
5713 build_router(state),
5714 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
5715 )
5716 .await;
5717 let v = body_json(resp).await;
5718 assert_eq!(v["usage"]["prompt_tokens"], 20);
5719 assert_eq!(v["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
5720 assert_eq!(v["usage"]["total_tokens"], 21);
5721 let w = stats.drain(Duration::from_secs(1));
5722 assert_eq!(w.prompt_tokens, 1, "only the prefilled token is throughput");
5723 }
5724
5725 async fn sse_frames(resp: Response) -> Vec<String> {
5727 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
5728 String::from_utf8(bytes.to_vec())
5729 .unwrap()
5730 .lines()
5731 .filter_map(|l| l.strip_prefix("data: ").map(str::to_owned))
5732 .collect()
5733 }
5734
5735 #[tokio::test]
5739 async fn include_usage_ends_the_stream_with_a_usage_chunk() {
5740 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true,
5741 "stream_options":{"include_usage":true}}"#;
5742 let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
5743 let n = frames.len();
5744 assert!(n >= 3, "{frames:?}");
5745 assert_eq!(frames[n - 1], "[DONE]");
5746 let usage: serde_json::Value = serde_json::from_str(&frames[n - 2]).unwrap();
5747 assert_eq!(usage["choices"], serde_json::json!([]), "{frames:?}");
5748 assert_eq!(usage["usage"]["prompt_tokens"], 20);
5749 assert_eq!(usage["usage"]["completion_tokens"], 1);
5750 assert_eq!(usage["usage"]["prompt_tokens_details"]["cached_tokens"], 19);
5751 let finish: serde_json::Value = serde_json::from_str(&frames[n - 3]).unwrap();
5752 assert_eq!(finish["choices"][0]["finish_reason"], "stop", "{frames:?}");
5753
5754 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#;
5755 let frames = sse_frames(post_chat(router_for(Arc::new(CachedPrefixGen)), body).await).await;
5756 assert!(
5757 frames.iter().all(|f| !f.contains("\"usage\"")),
5758 "usage was not asked for: {frames:?}"
5759 );
5760 }
5761
5762 #[tokio::test]
5765 async fn logprobs_are_returned_on_the_non_streaming_choice() {
5766 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5767 "logprobs":true,"top_logprobs":1}"#;
5768 let v = body_json(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
5769 assert_eq!(v["choices"][0]["message"]["content"], "hi");
5770 let lp = &v["choices"][0]["logprobs"]["content"][0];
5771 assert_eq!(lp["id"], 7);
5772 assert_eq!(lp["token"], "hi");
5773 assert_eq!(lp["bytes"], serde_json::json!([104, 105]));
5774 assert_eq!(lp["logprob"], -0.25);
5775 assert_eq!(lp["top_logprobs"][0]["id"], 9);
5776 assert_eq!(lp["top_logprobs"][0]["token"], "ho");
5777 assert_eq!(lp["top_logprobs"][0]["logprob"], -1.5);
5778 }
5779
5780 #[tokio::test]
5782 async fn zero_top_logprobs_returns_entries_without_alternatives() {
5783 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5784 "logprobs":true,"top_logprobs":0}"#;
5785 let v = body_json(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
5786 let lp = &v["choices"][0]["logprobs"]["content"][0];
5787 assert_eq!(lp["token"], "hi");
5788 assert_eq!(lp["logprob"], -0.25);
5789 assert_eq!(lp["top_logprobs"], serde_json::json!([]));
5790 }
5791
5792 #[tokio::test]
5795 async fn logprobs_ride_the_streaming_text_chunk() {
5796 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5797 "stream":true,"logprobs":true,"top_logprobs":1}"#;
5798 let frames = sse_frames(post_chat(router_for(Arc::new(LogprobGen)), body).await).await;
5799 let chunk = frames
5800 .iter()
5801 .filter(|f| *f != "[DONE]")
5802 .map(|f| serde_json::from_str::<serde_json::Value>(f).unwrap())
5803 .find(|v| v["choices"][0]["delta"]["content"] == "hi")
5804 .expect("a content chunk");
5805 let lp = &chunk["choices"][0]["logprobs"]["content"][0];
5806 assert_eq!(lp["token"], "hi");
5807 assert_eq!(lp["logprob"], -0.25);
5808 assert_eq!(lp["top_logprobs"][0]["token"], "ho");
5809 }
5810
5811 #[tokio::test]
5814 async fn logprobs_on_a_backend_without_them_is_a_400() {
5815 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
5816 "logprobs":true}"#;
5817 let resp = post_chat(router_for(Arc::new(EchoGen("a"))), body).await;
5818 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5819 let v = body_json(resp).await;
5820 assert_eq!(v["error"]["param"], "logprobs");
5821 }
5822
5823 struct OverflowGen;
5825 impl ChatGenerator for OverflowGen {
5826 fn status(&self) -> GeneratorStatus {
5827 cpu_status()
5828 }
5829
5830 fn vocab_size(&self) -> usize {
5831 TEST_VOCAB
5832 }
5833
5834 fn chat(
5835 &self,
5836 _messages: &[ChatMessage],
5837 _tools: Option<&serde_json::Value>,
5838 _tool_choice: Option<&str>,
5839 _params: &GenParams,
5840 _cancel: &Arc<AtomicBool>,
5841 _on_delta: &mut dyn FnMut(Delta),
5842 ) -> anyhow::Result<ChatOutcome> {
5843 Err(ContextLengthExceeded {
5844 message: "too long".into(),
5845 }
5846 .into())
5847 }
5848 }
5849
5850 #[tokio::test]
5853 async fn an_over_long_prompt_is_a_400_context_length_exceeded() {
5854 let resp = post_chat(
5855 router_for(Arc::new(OverflowGen)),
5856 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
5857 )
5858 .await;
5859 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5860 let v = body_json(resp).await;
5861 assert_eq!(v["error"]["type"], "invalid_request_error");
5862 assert_eq!(v["error"]["code"], "context_length_exceeded");
5863 assert_eq!(v["error"]["param"], "messages");
5864 assert_eq!(v["error"]["message"], "too long");
5865 }
5866
5867 #[tokio::test]
5871 async fn an_over_long_prompt_on_a_stream_is_a_typed_error_frame() {
5872 let frames = sse_frames(
5873 post_chat(
5874 router_for(Arc::new(OverflowGen)),
5875 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
5876 )
5877 .await,
5878 )
5879 .await;
5880 assert_eq!(
5881 frames.last().map(String::as_str),
5882 Some("[DONE]"),
5883 "{frames:?}"
5884 );
5885 let err: serde_json::Value = frames
5886 .iter()
5887 .filter_map(|f| serde_json::from_str::<serde_json::Value>(f).ok())
5888 .find(|v| v.get("error").is_some())
5889 .expect("an error frame");
5890 assert_eq!(err["error"]["type"], "invalid_request_error");
5891 assert_eq!(err["error"]["code"], "context_length_exceeded");
5892 assert_eq!(err["error"]["param"], "messages");
5893 assert_eq!(err["error"]["message"], "too long");
5894 }
5895
5896 #[tokio::test]
5899 async fn oversized_and_untyped_bodies_keep_their_status() {
5900 let huge = format!(
5901 r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
5902 "x".repeat(3 << 20)
5903 );
5904 let resp = post_chat(router_for(Arc::new(EchoGen("a"))), &huge).await;
5905 assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
5906 assert_eq!(
5907 body_json(resp).await["error"]["type"],
5908 "invalid_request_error"
5909 );
5910
5911 let resp = router_for(Arc::new(EchoGen("a")))
5912 .oneshot(
5913 Request::builder()
5914 .method("POST")
5915 .uri("/v1/chat/completions")
5916 .body(Body::from(
5917 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
5918 ))
5919 .unwrap(),
5920 )
5921 .await
5922 .unwrap();
5923 assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
5924 assert_eq!(
5925 body_json(resp).await["error"]["type"],
5926 "invalid_request_error"
5927 );
5928
5929 let resp = post_chat(router_for(Arc::new(EchoGen("a"))), "{not json").await;
5931 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5932 }
5933
5934 #[tokio::test]
5937 async fn the_bearer_check_does_not_wait_for_the_body() {
5938 let mut cfg = Config::default();
5939 cfg.serve.api_key = Some("s3cret".into());
5940 let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
5941 let router = build_router(AppState::new(g, "m", 1, Arc::new(cfg)));
5942 let never = futures_util::stream::pending::<Result<axum::body::Bytes, std::io::Error>>();
5943 let resp = tokio::time::timeout(
5944 Duration::from_secs(2),
5945 router.oneshot(
5946 Request::builder()
5947 .method("POST")
5948 .uri("/v1/chat/completions")
5949 .header("content-type", "application/json")
5950 .body(Body::from_stream(never))
5951 .unwrap(),
5952 ),
5953 )
5954 .await
5955 .expect("an unauthenticated request waited for its body")
5956 .unwrap();
5957 assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
5958 }
5959
5960 #[tokio::test]
5963 async fn minus_one_seed_and_max_tokens_mean_unset() {
5964 let p = GenParams::from_request(&req(
5965 r#"{"model":"m","messages":[],"seed":-1,"max_tokens":-1,"max_completion_tokens":-1}"#,
5966 ))
5967 .unwrap();
5968 assert_eq!((p.seed, p.max_tokens), (None, None));
5969 let p = GenParams::from_request(&req(
5970 r#"{"model":"m","messages":[],"seed":18446744073709551615,"max_tokens":7}"#,
5971 ))
5972 .unwrap();
5973 assert_eq!((p.seed, p.max_tokens), (Some(u64::MAX), Some(7)));
5974 for bad in [
5975 r#""seed":-2"#,
5976 r#""max_tokens":-5"#,
5977 r#""max_tokens":4294967296"#,
5978 ] {
5979 let raw = format!(r#"{{"model":"m","messages":[],{bad}}}"#);
5980 assert!(serde_json::from_str::<ChatRequest>(&raw).is_err(), "{bad}");
5981 }
5982
5983 let resp = post_chat(
5984 router_for(Arc::new(EchoGen("a"))),
5985 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"seed":-1,"max_tokens":-1}"#,
5986 )
5987 .await;
5988 assert_eq!(resp.status(), StatusCode::OK);
5989 }
5990
5991 struct HangGen {
5995 entered: Arc<AtomicBool>,
5996 cancelled: Arc<AtomicBool>,
5997 }
5998 impl ChatGenerator for HangGen {
5999 fn status(&self) -> GeneratorStatus {
6000 cpu_status()
6001 }
6002
6003 fn vocab_size(&self) -> usize {
6004 TEST_VOCAB
6005 }
6006
6007 fn chat(
6008 &self,
6009 _messages: &[ChatMessage],
6010 _tools: Option<&serde_json::Value>,
6011 _tool_choice: Option<&str>,
6012 _params: &GenParams,
6013 cancel: &Arc<AtomicBool>,
6014 _on_delta: &mut dyn FnMut(Delta),
6015 ) -> anyhow::Result<ChatOutcome> {
6016 self.entered.store(true, Ordering::Relaxed);
6017 let started = Instant::now();
6018 while started.elapsed() < Duration::from_secs(5) {
6019 if cancel.load(Ordering::Relaxed) {
6020 self.cancelled.store(true, Ordering::Relaxed);
6021 break;
6022 }
6023 std::thread::sleep(Duration::from_millis(2));
6024 }
6025 Ok(ChatOutcome {
6026 finish: Finish::Stop,
6027 prompt_tokens: 1,
6028 completion_tokens: 0,
6029 cached_tokens: 0,
6030 })
6031 }
6032 }
6033
6034 async fn eventually(flag: &AtomicBool, within: Duration) -> bool {
6036 let started = Instant::now();
6037 while !flag.load(Ordering::Relaxed) {
6038 if started.elapsed() > within {
6039 return false;
6040 }
6041 tokio::time::sleep(Duration::from_millis(5)).await;
6042 }
6043 true
6044 }
6045
6046 async fn hang_up_reaches_the_generator(stream: bool) -> bool {
6049 use tokio::io::AsyncWriteExt;
6050 let entered = Arc::new(AtomicBool::new(false));
6051 let cancelled = Arc::new(AtomicBool::new(false));
6052 let g: Arc<dyn ChatGenerator> = Arc::new(HangGen {
6053 entered: entered.clone(),
6054 cancelled: cancelled.clone(),
6055 });
6056 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
6057 let addr = listener.local_addr().unwrap();
6058 let router = router_for(g);
6059 let server = tokio::spawn(async move { axum::serve(listener, router).await });
6060 let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
6061 let body = format!(
6062 r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6063 );
6064 let head = format!(
6065 "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n\
6066 Content-Type: application/json\r\nContent-Length: {}\r\n\r\n",
6067 body.len()
6068 );
6069 sock.write_all(head.as_bytes()).await.unwrap();
6070 sock.write_all(body.as_bytes()).await.unwrap();
6071 assert!(
6072 eventually(&entered, Duration::from_secs(2)).await,
6073 "the generation never started"
6074 );
6075 drop(sock);
6076 let reached = eventually(&cancelled, Duration::from_secs(2)).await;
6077 server.abort();
6078 reached
6079 }
6080
6081 #[tokio::test]
6084 async fn a_non_streaming_hang_up_cancels_the_generation() {
6085 assert!(hang_up_reaches_the_generator(false).await);
6086 }
6087
6088 #[tokio::test]
6091 async fn a_streaming_hang_up_during_prefill_cancels_the_generation() {
6092 assert!(hang_up_reaches_the_generator(true).await);
6093 }
6094
6095 fn format_of(raw: &str) -> Result<Option<ResponseFormat>, ParamError> {
6098 GenParams::from_request(&req(&format!(
6099 r#"{{"model":"m","messages":[],"response_format":{raw}}}"#
6100 )))
6101 .map(|p| p.response_format)
6102 }
6103
6104 #[test]
6108 fn response_format_parses_and_refuses_what_it_cannot_do() {
6109 let schema =
6110 serde_json::json!({"type": "object", "properties": {"a": {"type": "integer"}}});
6111 assert_eq!(format_of("null"), Ok(None));
6112 assert_eq!(format_of(r#"{"type":"text"}"#), Ok(None));
6113 assert_eq!(
6114 format_of(r#"{"type":"json_object"}"#),
6115 Ok(Some(ResponseFormat::JsonObject))
6116 );
6117 assert_eq!(
6118 format_of(&format!(
6119 r#"{{"type":"json_schema",
6120 "json_schema":{{"name":"x","strict":true,"schema":{schema}}}}}"#
6121 )),
6122 Ok(Some(ResponseFormat::JsonSchema(schema.clone())))
6123 );
6124 assert_eq!(
6126 format_of(&format!(r#"{{"type":"json_object","schema":{schema}}}"#)),
6127 Ok(Some(ResponseFormat::JsonSchema(schema)))
6128 );
6129 assert_eq!(
6130 ResponseFormat::JsonObject.schema(),
6131 serde_json::json!({"type": "object"})
6132 );
6133 for any in [
6135 r#"{"type":"json_schema"}"#,
6136 r#"{"type":"json_schema","json_schema":{"name":"x"}}"#,
6137 r#"{"type":"json_schema","json_schema":{"name":"x","schema":null}}"#,
6138 r#"{"type":"json_schema","json_schema":null}"#,
6139 ] {
6140 assert_eq!(
6141 format_of(any),
6142 Ok(Some(ResponseFormat::JsonSchema(serde_json::json!({})))),
6143 "{any}"
6144 );
6145 }
6146 for bad in [
6147 r#"{"type":"xml"}"#,
6148 r#"{"type":"json_schema","json_schema":"x"}"#,
6149 r#"{"type":"json_schema","json_schema":{"schema":"object"}}"#,
6150 r#"{"type":"json_object","schema":[]}"#,
6151 r#""json_object""#,
6152 r#"{"kind":"json_object"}"#,
6153 ] {
6154 let e = format_of(bad).expect_err(bad);
6155 assert_eq!(e.param, "response_format", "{bad}");
6156 }
6157 assert!(format_of(r#"{"type":"xml"}"#)
6158 .unwrap_err()
6159 .message
6160 .contains("\"xml\""));
6161 }
6162
6163 #[derive(Default)]
6165 struct FormatProbe(std::sync::Mutex<Vec<Option<ResponseFormat>>>);
6166 impl ChatGenerator for FormatProbe {
6167 fn status(&self) -> GeneratorStatus {
6168 cpu_status()
6169 }
6170
6171 fn vocab_size(&self) -> usize {
6172 TEST_VOCAB
6173 }
6174
6175 fn chat(
6176 &self,
6177 _messages: &[ChatMessage],
6178 _tools: Option<&serde_json::Value>,
6179 _tool_choice: Option<&str>,
6180 params: &GenParams,
6181 _cancel: &Arc<AtomicBool>,
6182 on_delta: &mut dyn FnMut(Delta),
6183 ) -> anyhow::Result<ChatOutcome> {
6184 self.0.lock().unwrap().push(params.response_format.clone());
6185 on_delta(Delta::Content("{}".into()));
6186 Ok(ChatOutcome {
6187 finish: Finish::Stop,
6188 prompt_tokens: 1,
6189 completion_tokens: 1,
6190 cached_tokens: 0,
6191 })
6192 }
6193 }
6194
6195 #[tokio::test]
6198 async fn response_format_reaches_the_generator_or_is_a_400() {
6199 let probe = Arc::new(FormatProbe::default());
6200 let router = router_for(probe.clone());
6201 let ok = r#"{"model":"m","messages":[{"role":"user","content":"hi"}],
6202 "response_format":{"type":"json_object"}}"#;
6203 assert_eq!(post_chat(router.clone(), ok).await.status(), StatusCode::OK);
6204 for stream in [false, true] {
6205 let bad = format!(
6206 r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream},
6207 "response_format":{{"type":"yaml"}}}}"#
6208 );
6209 let resp = post_chat(router.clone(), &bad).await;
6210 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
6211 let v = body_json(resp).await;
6212 assert_eq!(v["error"]["type"], "invalid_request_error");
6213 assert_eq!(v["error"]["param"], "response_format");
6214 }
6215 assert_eq!(
6216 *probe.0.lock().unwrap(),
6217 vec![Some(ResponseFormat::JsonObject)]
6218 );
6219 }
6220
6221 struct RefuseGen {
6224 in_count: bool,
6225 chats: AtomicU64,
6226 }
6227 impl RefuseGen {
6228 fn refusal() -> anyhow::Error {
6229 ParamError {
6230 param: "response_format",
6231 message: "response_format cannot be enforced: unsupported keyword".into(),
6232 }
6233 .into()
6234 }
6235 }
6236 impl ChatGenerator for RefuseGen {
6237 fn status(&self) -> GeneratorStatus {
6238 cpu_status()
6239 }
6240
6241 fn vocab_size(&self) -> usize {
6242 TEST_VOCAB
6243 }
6244
6245 fn prepare(
6246 &self,
6247 _messages: &[ChatMessage],
6248 _tools: Option<&serde_json::Value>,
6249 _tool_choice: Option<&str>,
6250 _params: &GenParams,
6251 ) -> anyhow::Result<Option<PreparedRequest>> {
6252 if self.in_count {
6253 Err(Self::refusal())
6254 } else {
6255 Ok(None)
6256 }
6257 }
6258
6259 fn chat(
6260 &self,
6261 _messages: &[ChatMessage],
6262 _tools: Option<&serde_json::Value>,
6263 _tool_choice: Option<&str>,
6264 _params: &GenParams,
6265 _cancel: &Arc<AtomicBool>,
6266 _on_delta: &mut dyn FnMut(Delta),
6267 ) -> anyhow::Result<ChatOutcome> {
6268 self.chats.fetch_add(1, Ordering::Relaxed);
6269 Err(Self::refusal())
6270 }
6271 }
6272
6273 #[tokio::test]
6278 async fn a_generator_param_error_is_a_400() {
6279 let body = |stream: bool| {
6280 format!(
6281 r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6282 )
6283 };
6284 let early = Arc::new(RefuseGen {
6285 in_count: true,
6286 chats: AtomicU64::new(0),
6287 });
6288 for stream in [false, true] {
6289 let resp = post_chat(router_for(early.clone()), &body(stream)).await;
6290 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
6291 let v = body_json(resp).await;
6292 assert_eq!(v["error"]["param"], "response_format");
6293 assert_eq!(v["error"]["type"], "invalid_request_error");
6294 }
6295 assert_eq!(early.chats.load(Ordering::Relaxed), 0);
6296
6297 let late = Arc::new(RefuseGen {
6298 in_count: false,
6299 chats: AtomicU64::new(0),
6300 });
6301 let resp = post_chat(router_for(late.clone()), &body(false)).await;
6302 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
6303 assert_eq!(body_json(resp).await["error"]["param"], "response_format");
6304 let frames = sse_frames(post_chat(router_for(late), &body(true)).await).await;
6305 let err: serde_json::Value = frames
6306 .iter()
6307 .filter_map(|f| serde_json::from_str::<serde_json::Value>(f).ok())
6308 .find(|v| v.get("error").is_some())
6309 .expect("an error frame");
6310 assert_eq!(err["error"]["type"], "invalid_request_error");
6311 assert_eq!(err["error"]["param"], "response_format");
6312 }
6313
6314 #[derive(Default)]
6318 struct CountGen {
6319 tokens: u32,
6320 limit: Option<u32>,
6321 prepares: AtomicU64,
6322 prepared: AtomicU64,
6323 chats: AtomicU64,
6324 }
6325
6326 struct CountState(u32);
6328 impl ChatGenerator for CountGen {
6329 fn status(&self) -> GeneratorStatus {
6330 cpu_status()
6331 }
6332
6333 fn vocab_size(&self) -> usize {
6334 TEST_VOCAB
6335 }
6336
6337 fn prepare(
6338 &self,
6339 _messages: &[ChatMessage],
6340 _tools: Option<&serde_json::Value>,
6341 _tool_choice: Option<&str>,
6342 _params: &GenParams,
6343 ) -> anyhow::Result<Option<PreparedRequest>> {
6344 self.prepares.fetch_add(1, Ordering::Relaxed);
6345 Ok(Some(PreparedRequest::new(
6346 self.tokens,
6347 self.limit,
6348 CountState(self.tokens),
6349 )))
6350 }
6351
6352 fn chat_prepared(
6353 &self,
6354 prepared: PreparedRequest,
6355 _messages: &[ChatMessage],
6356 _tools: Option<&serde_json::Value>,
6357 _tool_choice: Option<&str>,
6358 _params: &GenParams,
6359 _cancel: &Arc<AtomicBool>,
6360 on_delta: &mut dyn FnMut(Delta),
6361 ) -> anyhow::Result<ChatOutcome> {
6362 let CountState(tokens) = prepared.into_state().expect("our own prepared state");
6363 self.prepared.fetch_add(1, Ordering::Relaxed);
6364 on_delta(Delta::Content("ok".into()));
6365 Ok(ChatOutcome {
6366 finish: Finish::Stop,
6367 prompt_tokens: tokens,
6368 completion_tokens: 1,
6369 cached_tokens: 0,
6370 })
6371 }
6372
6373 fn chat(
6374 &self,
6375 _messages: &[ChatMessage],
6376 _tools: Option<&serde_json::Value>,
6377 _tool_choice: Option<&str>,
6378 _params: &GenParams,
6379 _cancel: &Arc<AtomicBool>,
6380 on_delta: &mut dyn FnMut(Delta),
6381 ) -> anyhow::Result<ChatOutcome> {
6382 self.chats.fetch_add(1, Ordering::Relaxed);
6383 on_delta(Delta::Content("ok".into()));
6384 Ok(ChatOutcome {
6385 finish: Finish::Stop,
6386 prompt_tokens: self.tokens,
6387 completion_tokens: 1,
6388 cached_tokens: 0,
6389 })
6390 }
6391 }
6392
6393 #[tokio::test]
6398 async fn an_over_long_prompt_is_refused_before_it_takes_a_slot() {
6399 let long = Arc::new(CountGen {
6400 tokens: 100,
6401 limit: Some(99),
6402 ..Default::default()
6403 });
6404 let state = AppState::new(long.clone(), "m", 1, Arc::new(Config::default()));
6405 let held = state.models[0].slots.clone().acquire_owned().await.unwrap();
6406 let router = build_router(state);
6407 for stream in [false, true] {
6408 let body = format!(
6409 r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6410 );
6411 let resp =
6412 tokio::time::timeout(Duration::from_secs(2), post_chat(router.clone(), &body))
6413 .await
6414 .expect("an over-long prompt waited for a slot");
6415 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "stream={stream}");
6416 let v = body_json(resp).await;
6417 assert_eq!(v["error"]["code"], "context_length_exceeded");
6418 assert_eq!(v["error"]["param"], "messages");
6419 assert_eq!(
6420 v["error"]["message"],
6421 "This model's maximum context length is 99 tokens. However, your messages \
6422 resulted in 100 tokens. Please reduce the length of the messages."
6423 );
6424 }
6425 drop(held);
6426 assert_eq!(long.prepared.load(Ordering::Relaxed), 0);
6427 assert_eq!(long.chats.load(Ordering::Relaxed), 0);
6428
6429 for (tokens, limit) in [(99, Some(99)), (100_000, None)] {
6430 let g = Arc::new(CountGen {
6431 tokens,
6432 limit,
6433 ..Default::default()
6434 });
6435 let resp = post_chat(
6436 router_for(g.clone()),
6437 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
6438 )
6439 .await;
6440 assert_eq!(resp.status(), StatusCode::OK, "{tokens} / {limit:?}");
6441 assert_eq!(body_json(resp).await["usage"]["prompt_tokens"], tokens);
6442 }
6443 }
6444
6445 struct SlowFirstToken(Duration);
6447 impl ChatGenerator for SlowFirstToken {
6448 fn status(&self) -> GeneratorStatus {
6449 cpu_status()
6450 }
6451
6452 fn vocab_size(&self) -> usize {
6453 TEST_VOCAB
6454 }
6455
6456 fn chat(
6457 &self,
6458 _messages: &[ChatMessage],
6459 _tools: Option<&serde_json::Value>,
6460 _tool_choice: Option<&str>,
6461 _params: &GenParams,
6462 _cancel: &Arc<AtomicBool>,
6463 on_delta: &mut dyn FnMut(Delta),
6464 ) -> anyhow::Result<ChatOutcome> {
6465 std::thread::sleep(self.0);
6466 on_delta(Delta::Content("late".into()));
6467 Ok(ChatOutcome {
6468 finish: Finish::Stop,
6469 prompt_tokens: 1,
6470 completion_tokens: 1,
6471 cached_tokens: 0,
6472 })
6473 }
6474 }
6475
6476 async fn slow_stream_body(secs: u64) -> String {
6479 let mut cfg = Config::default();
6480 cfg.serve.sse_keepalive_secs = secs;
6481 let g: Arc<dyn ChatGenerator> = Arc::new(SlowFirstToken(Duration::from_millis(1600)));
6482 let resp = post_chat(
6483 build_router(AppState::new(g, "m", 1, Arc::new(cfg))),
6484 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
6485 )
6486 .await;
6487 let bytes = resp.into_body().collect().await.unwrap().to_bytes();
6488 String::from_utf8(bytes.to_vec()).unwrap()
6489 }
6490
6491 #[tokio::test]
6495 async fn a_quiet_stream_carries_keep_alive_comments_unless_disabled() {
6496 let comment = |body: &str| body.lines().any(|l| l.starts_with(':'));
6497 let on = slow_stream_body(1).await;
6498 assert!(comment(&on), "no keep-alive comment: {on:?}");
6499 let off = slow_stream_body(0).await;
6500 assert!(!comment(&off), "keep-alive sent while disabled: {off:?}");
6501 for body in [&on, &off] {
6502 assert!(body.contains("\"late\""), "{body:?}");
6503 assert!(body.contains("[DONE]"), "{body:?}");
6504 }
6505 assert_eq!(
6506 sse_keep_alive(&Config::default()),
6507 Some(Duration::from_secs(15))
6508 );
6509 }
6510
6511 #[tokio::test]
6514 async fn a_huge_keep_alive_interval_is_bounded_not_a_panic() {
6515 let mut cfg = Config::default();
6516 cfg.serve.sse_keepalive_secs = u64::MAX;
6517 assert_eq!(sse_keep_alive(&cfg), Some(MAX_SSE_KEEPALIVE));
6518 let g: Arc<dyn ChatGenerator> = Arc::new(EchoGen("a"));
6519 let frames = sse_frames(
6520 post_chat(
6521 build_router(AppState::new(g, "m", 1, Arc::new(cfg))),
6522 r#"{"model":"m","messages":[{"role":"user","content":"hi"}],"stream":true}"#,
6523 )
6524 .await,
6525 )
6526 .await;
6527 assert_eq!(
6528 frames.last().map(String::as_str),
6529 Some("[DONE]"),
6530 "{frames:?}"
6531 );
6532 }
6533
6534 #[tokio::test]
6538 async fn a_request_is_prepared_once_and_generated_from_its_preparation() {
6539 for stream in [false, true] {
6540 let g = Arc::new(CountGen {
6541 tokens: 7,
6542 ..Default::default()
6543 });
6544 let body = format!(
6545 r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],"stream":{stream}}}"#
6546 );
6547 let resp = post_chat(router_for(g.clone()), &body).await;
6548 assert_eq!(resp.status(), StatusCode::OK);
6549 let _ = resp.into_body().collect().await.unwrap();
6550 let counts = |c: &AtomicU64| c.load(Ordering::Relaxed);
6551 assert_eq!(
6552 (counts(&g.prepares), counts(&g.prepared), counts(&g.chats)),
6553 (1, 1, 0),
6554 "stream={stream}"
6555 );
6556 }
6557 let probe = Arc::new(FormatProbe::default());
6558 let resp = post_chat(
6559 router_for(probe.clone()),
6560 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
6561 )
6562 .await;
6563 assert_eq!(resp.status(), StatusCode::OK);
6564 assert_eq!(
6565 probe.0.lock().unwrap().len(),
6566 1,
6567 "a non-preparing generator still chats"
6568 );
6569 }
6570
6571 #[tokio::test]
6574 async fn malformed_tools_and_unknown_tool_choices_are_400s_naming_the_field() {
6575 let probe = Arc::new(FormatProbe::default());
6576 for (extra, param) in [
6577 (r#""tools":[{"type":"function","function":{}}]"#, "tools"),
6578 (r#""tools":{"a":1}"#, "tools"),
6579 (
6580 r#""tools":[{"type":"function","function":{"name":"f"}}],
6581 "tool_choice":{"type":"function","function":{"name":"g"}}"#,
6582 "tool_choice",
6583 ),
6584 ] {
6585 let body =
6586 format!(r#"{{"model":"m","messages":[{{"role":"user","content":"hi"}}],{extra}}}"#);
6587 let resp = post_chat(router_for(probe.clone()), &body).await;
6588 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{extra}");
6589 assert_eq!(body_json(resp).await["error"]["param"], param, "{extra}");
6590 }
6591 assert!(probe.0.lock().unwrap().is_empty());
6592 }
6593
6594 #[tokio::test]
6597 async fn the_body_limit_is_configurable() {
6598 let mut cfg = Config::default();
6599 cfg.serve.max_body_bytes = 1024;
6600 let router = build_router(AppState::new(Arc::new(EchoGen("a")), "m", 1, Arc::new(cfg)));
6601 let body = |n: usize| {
6602 format!(
6603 r#"{{"model":"m","messages":[{{"role":"user","content":"{}"}}]}}"#,
6604 "x".repeat(n)
6605 )
6606 };
6607 let resp = post_chat(router.clone(), &body(2048)).await;
6608 assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
6609 assert_eq!(
6610 body_json(resp).await["error"]["type"],
6611 "invalid_request_error"
6612 );
6613 assert_eq!(post_chat(router, &body(512)).await.status(), StatusCode::OK);
6614
6615 let mut zero = Config::default();
6616 zero.serve.max_body_bytes = 0;
6617 assert_eq!(max_body_bytes(&zero), 2 << 20);
6618 }
6619
6620 #[derive(Default)]
6623 struct SlowPrepare {
6624 running: AtomicU64,
6625 most: AtomicU64,
6626 prepares: AtomicU64,
6627 }
6628 impl SlowPrepare {
6629 fn slow_prepare(&self) {
6630 self.prepares.fetch_add(1, Ordering::Relaxed);
6631 let now = self.running.fetch_add(1, Ordering::SeqCst) + 1;
6632 self.most.fetch_max(now, Ordering::SeqCst);
6633 std::thread::sleep(Duration::from_millis(150));
6634 self.running.fetch_sub(1, Ordering::SeqCst);
6635 }
6636 }
6637 impl ChatGenerator for SlowPrepare {
6638 fn status(&self) -> GeneratorStatus {
6639 cpu_status()
6640 }
6641
6642 fn vocab_size(&self) -> usize {
6643 TEST_VOCAB
6644 }
6645
6646 fn prepare(
6647 &self,
6648 _messages: &[ChatMessage],
6649 _tools: Option<&serde_json::Value>,
6650 _tool_choice: Option<&str>,
6651 _params: &GenParams,
6652 ) -> anyhow::Result<Option<PreparedRequest>> {
6653 self.slow_prepare();
6654 Ok(None)
6655 }
6656
6657 fn prepare_completion(&self, prompt: &str) -> anyhow::Result<Option<(u32, Option<u32>)>> {
6658 self.slow_prepare();
6659 Ok(Some((prompt.len() as u32, None)))
6660 }
6661
6662 fn complete(
6663 &self,
6664 _prompt: &str,
6665 _params: &GenParams,
6666 _cancel: &Arc<AtomicBool>,
6667 on_text: &mut dyn FnMut(&str),
6668 ) -> anyhow::Result<ChatOutcome> {
6669 on_text("ok");
6670 Ok(ChatOutcome {
6671 finish: Finish::Stop,
6672 prompt_tokens: 1,
6673 completion_tokens: 1,
6674 cached_tokens: 0,
6675 })
6676 }
6677
6678 fn chat(
6679 &self,
6680 _messages: &[ChatMessage],
6681 _tools: Option<&serde_json::Value>,
6682 _tool_choice: Option<&str>,
6683 _params: &GenParams,
6684 _cancel: &Arc<AtomicBool>,
6685 on_delta: &mut dyn FnMut(Delta),
6686 ) -> anyhow::Result<ChatOutcome> {
6687 on_delta(Delta::Content("ok".into()));
6688 Ok(ChatOutcome {
6689 finish: Finish::Stop,
6690 prompt_tokens: 1,
6691 completion_tokens: 1,
6692 cached_tokens: 0,
6693 })
6694 }
6695 }
6696
6697 #[tokio::test]
6700 async fn concurrent_preparations_are_bounded_by_the_slots() {
6701 let g = Arc::new(SlowPrepare::default());
6702 let router = build_router(AppState::new(
6703 g.clone(),
6704 "m",
6705 2,
6706 Arc::new(Config::default()),
6707 ));
6708 let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
6709 let all = (0..5).map(|_| post_chat(router.clone(), body));
6710 for resp in futures_util::future::join_all(all).await {
6711 assert_eq!(resp.status(), StatusCode::OK);
6712 }
6713 assert_eq!(g.prepares.load(Ordering::Relaxed), 5);
6714 assert_eq!(g.most.load(Ordering::SeqCst), 2, "the bound, and no less");
6715 }
6716
6717 #[tokio::test]
6721 async fn completion_preparations_share_the_chat_bound() {
6722 let g = Arc::new(SlowPrepare::default());
6723 let router = build_router(AppState::new(
6724 g.clone(),
6725 "m",
6726 2,
6727 Arc::new(Config::default()),
6728 ));
6729 let chat = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#;
6730 let raw = r#"{"model":"m","prompt":"hi"}"#;
6731 let all = (0..6).map(|i| {
6732 let router = router.clone();
6733 async move {
6734 let (uri, body) = if i % 2 == 0 {
6735 ("/v1/chat/completions", chat)
6736 } else {
6737 ("/v1/completions", raw)
6738 };
6739 router
6740 .oneshot(
6741 Request::builder()
6742 .method("POST")
6743 .uri(uri)
6744 .header("content-type", "application/json")
6745 .body(Body::from(body))
6746 .unwrap(),
6747 )
6748 .await
6749 .unwrap()
6750 }
6751 });
6752 for resp in futures_util::future::join_all(all).await {
6753 assert_eq!(resp.status(), StatusCode::OK);
6754 }
6755 assert_eq!(g.prepares.load(Ordering::Relaxed), 6);
6756 assert_eq!(g.most.load(Ordering::SeqCst), 2, "the bound, and no less");
6757 }
6758
6759 #[tokio::test]
6762 async fn an_abandoned_wait_for_preparation_is_cancelled() {
6763 let g = Arc::new(SlowPrepare::default());
6764 let state = AppState::new(g.clone(), "m", 1, Arc::new(Config::default()));
6765 let prepares = state.models[0].prepares.clone();
6766 let held = prepares.clone().acquire_owned().await.unwrap();
6767 let waited = tokio::time::timeout(
6768 Duration::from_millis(200),
6769 post_chat(
6770 build_router(state),
6771 r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#,
6772 ),
6773 )
6774 .await;
6775 assert!(waited.is_err(), "the request must still be waiting");
6776 drop(held);
6777 assert_eq!(prepares.available_permits(), 1);
6778 assert_eq!(g.prepares.load(Ordering::Relaxed), 0);
6779 }
6780}