1use std::pin::pin;
84use std::sync::Arc;
85use std::time::Duration;
86
87use tokio::time::Instant;
88
89use async_trait::async_trait;
90use serde::{Deserialize, Serialize};
91use serde_json::Value;
92use tokio::sync::mpsc;
93
94use super::queue::{Admission, Turn};
95use super::{InferHost, model_error};
96use crate::cancel::CancelToken;
97use crate::model::{DeltaSink, Message, Modalities, ModelBackend, Role, ToolCall};
98use crate::remote::{Caller, Channel, RemoteError, bytes, request_id};
99use crate::session::AgentEvent;
100use crate::speech::{AudioFormat, SpeechNeeds};
101use crate::tool::ToolSpec;
102
103pub const PROTOCOL: &str = "/weirdnet-agent/infer/2";
105
106pub const QUEUE_KEEPALIVE: Duration = Duration::from_secs(3);
108
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
112#[serde(rename_all = "snake_case")]
113#[non_exhaustive]
114pub enum Priority {
115 #[default]
116 Interactive,
117 Batch,
118 Background,
119}
120
121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124#[non_exhaustive]
125pub enum CacheMode {
126 #[default]
128 Use,
129 Bypass,
131 Refresh,
133}
134
135impl CacheMode {
136 pub fn is_use(&self) -> bool {
137 *self == CacheMode::Use
138 }
139
140 pub fn may_read(&self) -> bool {
142 *self == CacheMode::Use
143 }
144
145 pub fn may_store(&self) -> bool {
147 matches!(self, CacheMode::Use | CacheMode::Refresh)
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
153#[non_exhaustive]
154pub struct ContextRef {
155 pub conversation: String,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub head: Option<String>,
159}
160
161impl ContextRef {
162 pub fn new(conversation: impl Into<String>, head: Option<String>) -> Self {
163 Self { conversation: conversation.into(), head }
164 }
165}
166
167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169#[serde(rename_all = "snake_case")]
170#[non_exhaustive]
171pub enum Input {
172 Messages(Vec<Message>),
174 Context(ContextRef),
176 Prompt(String),
179}
180
181impl Default for Input {
182 fn default() -> Self {
183 Input::Messages(Vec::new())
184 }
185}
186
187#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
189#[non_exhaustive]
190pub struct Prefix {
191 pub text: String,
192 pub len: u64,
193 #[serde(default, skip_serializing_if = "String::is_empty")]
194 pub reasoning: String,
195 #[serde(default)]
196 pub reasoning_len: u64,
197}
198
199impl Prefix {
200 pub fn new(text: impl Into<String>, reasoning: impl Into<String>) -> Self {
201 let (text, reasoning) = (text.into(), reasoning.into());
202 Self { len: chars(&text), reasoning_len: chars(&reasoning), text, reasoning }
203 }
204
205 pub fn is_consistent(&self) -> bool {
207 self.len == chars(&self.text) && self.reasoning_len == chars(&self.reasoning)
208 }
209
210 pub fn is_empty(&self) -> bool {
211 self.text.is_empty() && self.reasoning.is_empty()
212 }
213}
214
215pub fn chars(s: &str) -> u64 {
217 s.chars().count() as u64
218}
219
220#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct Sampling {
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub temperature: Option<f32>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub top_p: Option<f32>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub top_k: Option<u32>,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub min_p: Option<f32>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub max_tokens: Option<u32>,
234 #[serde(default, skip_serializing_if = "Vec::is_empty")]
235 pub stop: Vec<String>,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub presence_penalty: Option<f32>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub frequency_penalty: Option<f32>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub repeat_penalty: Option<f32>,
242}
243
244#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[serde(rename_all = "snake_case")]
247#[non_exhaustive]
248pub enum ResponseFormat {
249 Text,
250 Json,
252 JsonSchema {
254 name: String,
255 schema: Value,
256 #[serde(default)]
257 strict: bool,
258 },
259}
260
261#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
263#[non_exhaustive]
264pub struct Request {
265 pub id: String,
267 pub job_id: String,
269 #[serde(default)]
271 pub attempt: u32,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub model: Option<String>,
275 #[serde(default)]
276 pub priority: Priority,
277 pub input: Input,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub assistant_prefix: Option<Prefix>,
281 #[serde(default)]
282 pub sampling: Sampling,
283 #[serde(default, skip_serializing_if = "Option::is_none")]
284 pub seed: Option<u64>,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
286 pub response_format: Option<ResponseFormat>,
287 #[serde(default, skip_serializing_if = "Vec::is_empty")]
288 pub tools: Vec<ToolSpec>,
289 #[serde(default)]
292 pub raw: bool,
293 #[serde(default)]
295 pub wait_for_model: bool,
296 #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
299 pub cert: Option<Vec<u8>>,
300 #[serde(default, skip_serializing_if = "is_false")]
304 pub early_meta: bool,
305 #[serde(default, skip_serializing_if = "CacheMode::is_use")]
308 pub cache: CacheMode,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub adapter_scale: Option<f32>,
315}
316
317fn is_false(b: &bool) -> bool {
318 !*b
319}
320
321impl Request {
322 pub fn messages(messages: Vec<Message>) -> Self {
324 Self::with_input(Input::Messages(messages))
325 }
326
327 pub fn context(context: ContextRef) -> Self {
329 Self::with_input(Input::Context(context))
330 }
331
332 pub fn prompt(prompt: impl Into<String>) -> Self {
334 Self::with_input(Input::Prompt(prompt.into()))
335 }
336
337 fn with_input(input: Input) -> Self {
338 let id = request_id();
339 Self { job_id: id.clone(), id, input, ..Default::default() }
340 }
341
342 pub fn with_model(mut self, model: impl Into<String>) -> Self {
343 self.model = Some(model.into());
344 self
345 }
346
347 pub fn with_priority(mut self, priority: Priority) -> Self {
348 self.priority = priority;
349 self
350 }
351
352 pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
353 self.tools = tools;
354 self
355 }
356
357 pub fn with_sampling(mut self, sampling: Sampling) -> Self {
358 self.sampling = sampling;
359 self
360 }
361
362 pub fn with_seed(mut self, seed: u64) -> Self {
363 self.seed = Some(seed);
364 self
365 }
366
367 pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
368 self.response_format = Some(format);
369 self
370 }
371
372 pub fn with_job_id(mut self, job_id: impl Into<String>) -> Self {
373 self.job_id = job_id.into();
374 self
375 }
376
377 pub fn with_prefix(mut self, prefix: Prefix) -> Self {
378 self.assistant_prefix = Some(prefix);
379 self
380 }
381
382 pub fn continuing(mut self) -> Self {
387 if let Input::Messages(m) = &mut self.input
388 && m.last().is_some_and(|last| last.role == Role::Assistant && last.tool_calls.is_empty() && last.content.as_text().is_some())
389 && let Some(last) = m.pop()
390 {
391 self.assistant_prefix = Some(Prefix::new(last.content.into_text(), ""));
392 }
393 self
394 }
395
396 pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
397 self.cert = Some(cert);
398 self
399 }
400
401 pub fn with_cache(mut self, cache: CacheMode) -> Self {
403 self.cache = cache;
404 self
405 }
406
407 pub fn with_adapter_scale(mut self, scale: f32) -> Self {
410 self.adapter_scale = Some(scale);
411 self
412 }
413
414 pub fn with_wait_for_model(mut self, wait: bool) -> Self {
416 self.wait_for_model = wait;
417 self
418 }
419
420 pub fn raw(mut self) -> Self {
422 self.raw = true;
423 self
424 }
425
426 pub fn inline_messages(&self) -> Option<&[Message]> {
428 match &self.input {
429 Input::Messages(m) => Some(m),
430 _ => None,
431 }
432 }
433
434 pub fn needs(&self) -> Modalities {
437 self.inline_messages().map(crate::model::needs).unwrap_or(Modalities::TEXT)
438 }
439
440 pub fn raw_prompt(&self) -> Option<&str> {
442 match &self.input {
443 Input::Prompt(p) => Some(p),
444 _ => None,
445 }
446 }
447
448 pub fn next_attempt(&self) -> Self {
450 Self { id: request_id(), attempt: self.attempt + 1, ..self.clone() }
451 }
452}
453
454#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
456#[non_exhaustive]
457pub struct EmbedRequest {
458 pub id: String,
459 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub model: Option<String>,
461 pub inputs: Vec<String>,
462 #[serde(default)]
463 pub priority: Priority,
464 #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
465 pub cert: Option<Vec<u8>>,
466}
467
468impl EmbedRequest {
469 pub fn new(inputs: Vec<String>) -> Self {
470 Self { id: request_id(), inputs, ..Default::default() }
471 }
472
473 pub fn with_model(mut self, model: impl Into<String>) -> Self {
474 self.model = Some(model.into());
475 self
476 }
477
478 pub fn with_priority(mut self, priority: Priority) -> Self {
479 self.priority = priority;
480 self
481 }
482}
483
484#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
487#[non_exhaustive]
488pub struct TranscribeRequest {
489 pub id: String,
490 #[serde(default, skip_serializing_if = "Option::is_none")]
492 pub model: Option<String>,
493 #[serde(with = "bytes")]
495 pub audio: Vec<u8>,
496 pub format: String,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
501 pub language: Option<String>,
502 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub prompt: Option<String>,
506 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
508 pub timestamps: bool,
509 #[serde(default)]
510 pub priority: Priority,
511 #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
512 pub cert: Option<Vec<u8>>,
513}
514
515impl TranscribeRequest {
516 pub fn new(audio: Vec<u8>, format: impl Into<String>) -> Self {
518 Self { id: request_id(), audio, format: format.into(), ..Default::default() }
519 }
520
521 pub fn with_model(mut self, model: impl Into<String>) -> Self {
522 self.model = Some(model.into());
523 self
524 }
525
526 pub fn with_language(mut self, language: impl Into<String>) -> Self {
528 self.language = Some(language.into());
529 self
530 }
531
532 pub fn with_prompt(mut self, prompt: impl Into<String>) -> Self {
534 self.prompt = Some(prompt.into());
535 self
536 }
537
538 pub fn with_timestamps(mut self, timestamps: bool) -> Self {
540 self.timestamps = timestamps;
541 self
542 }
543
544 pub fn with_priority(mut self, priority: Priority) -> Self {
545 self.priority = priority;
546 self
547 }
548
549 pub fn check(&self) -> Result<(), RemoteError> {
552 if self.audio.is_empty() {
553 return Err(RemoteError::BadRequest { message: "a transcription request needs audio".into() });
554 }
555 if self.format.trim().is_empty() {
556 return Err(RemoteError::BadRequest { message: "a transcription request needs the audio format (wav, mp3, ...)".into() });
557 }
558 Ok(())
559 }
560}
561
562#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
564#[non_exhaustive]
565pub struct Transcript {
566 pub text: String,
568 #[serde(default, skip_serializing_if = "Option::is_none")]
570 pub language: Option<String>,
571 #[serde(default, skip_serializing_if = "Option::is_none")]
573 pub duration_ms: Option<u64>,
574 #[serde(default, skip_serializing_if = "Vec::is_empty")]
576 pub segments: Vec<Segment>,
577}
578
579impl Transcript {
580 pub fn new(text: impl Into<String>) -> Self {
581 Self { text: text.into(), ..Default::default() }
582 }
583
584 pub fn with_language(mut self, language: impl Into<String>) -> Self {
585 self.language = Some(language.into());
586 self
587 }
588
589 pub fn with_duration_ms(mut self, duration_ms: u64) -> Self {
590 self.duration_ms = Some(duration_ms);
591 self
592 }
593
594 pub fn with_segments(mut self, segments: Vec<Segment>) -> Self {
595 self.segments = segments;
596 self
597 }
598}
599
600#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
602#[non_exhaustive]
603pub struct Segment {
604 pub start_ms: u64,
605 pub end_ms: u64,
606 pub text: String,
607}
608
609impl Segment {
610 pub fn new(start_ms: u64, end_ms: u64, text: impl Into<String>) -> Self {
611 Self { start_ms, end_ms, text: text.into() }
612 }
613}
614
615pub const MAX_REFERENCE_BYTES: usize = 30 << 20;
618
619pub const MAX_AUDIO_CHUNK: usize = 256 << 10;
621
622#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
624#[serde(rename_all = "snake_case")]
625#[non_exhaustive]
626pub enum SpeakInput {
627 Text(String),
629 Script(Vec<ScriptTurn>),
632 Raw(String),
635}
636
637impl Default for SpeakInput {
638 fn default() -> Self {
639 SpeakInput::Text(String::new())
640 }
641}
642
643impl SpeakInput {
644 pub fn chars(&self) -> u64 {
646 match self {
647 SpeakInput::Text(t) | SpeakInput::Raw(t) => chars(t),
648 SpeakInput::Script(turns) => turns.iter().map(|t| chars(&t.text)).sum(),
649 }
650 }
651
652 pub fn highest_speaker(&self) -> Option<u8> {
654 match self {
655 SpeakInput::Script(turns) => turns.iter().map(|t| t.speaker).max(),
656 _ => None,
657 }
658 }
659}
660
661#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
663#[non_exhaustive]
664pub struct ScriptTurn {
665 pub speaker: u8,
667 pub text: String,
668}
669
670impl ScriptTurn {
671 pub fn new(speaker: u8, text: impl Into<String>) -> Self {
672 Self { speaker, text: text.into() }
673 }
674}
675
676#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
678#[serde(rename_all = "snake_case")]
679#[non_exhaustive]
680pub enum Voice {
681 Preset { name: String },
684 Design { description: String },
686 Clone {
691 #[serde(with = "bytes")]
692 audio: Vec<u8>,
693 format: String,
695 #[serde(default, skip_serializing_if = "Option::is_none")]
697 text: Option<String>,
698 #[serde(default)]
699 consent: bool,
700 },
701}
702
703impl Voice {
704 pub fn preset(name: impl Into<String>) -> Self {
705 Voice::Preset { name: name.into() }
706 }
707
708 pub fn design(description: impl Into<String>) -> Self {
709 Voice::Design { description: description.into() }
710 }
711
712 pub fn clone_from(audio: Vec<u8>, format: impl Into<String>, text: Option<String>, consent: bool) -> Self {
714 Voice::Clone { audio, format: format.into(), text, consent }
715 }
716}
717
718#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
720#[non_exhaustive]
721pub struct SpeakerVoice {
722 pub speaker: u8,
723 pub voice: Voice,
724}
725
726impl SpeakerVoice {
727 pub fn new(speaker: u8, voice: Voice) -> Self {
728 Self { speaker, voice }
729 }
730}
731
732#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
735#[non_exhaustive]
736pub struct SpeakRequest {
737 pub id: String,
738 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub model: Option<String>,
742 pub input: SpeakInput,
743 #[serde(default, skip_serializing_if = "Option::is_none")]
746 pub voice: Option<Voice>,
747 #[serde(default, skip_serializing_if = "Vec::is_empty")]
749 pub voices: Vec<SpeakerVoice>,
750 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub instructions: Option<String>,
753 #[serde(default, skip_serializing_if = "Option::is_none")]
755 pub language: Option<String>,
756 #[serde(default, skip_serializing_if = "Option::is_none")]
759 pub speed: Option<u32>,
760 #[serde(default, skip_serializing_if = "Option::is_none")]
761 pub seed: Option<u64>,
762 #[serde(default, skip_serializing_if = "Option::is_none")]
765 pub format: Option<AudioFormat>,
766 #[serde(default, skip_serializing_if = "Option::is_none")]
768 pub sample_rate: Option<u32>,
769 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
772 pub stream: bool,
773 #[serde(default)]
774 pub priority: Priority,
775 #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
776 pub cert: Option<Vec<u8>>,
777}
778
779impl SpeakRequest {
780 pub fn text(text: impl Into<String>) -> Self {
782 Self::with_input(SpeakInput::Text(text.into()))
783 }
784
785 pub fn script(turns: Vec<ScriptTurn>) -> Self {
787 Self::with_input(SpeakInput::Script(turns))
788 }
789
790 pub fn raw(input: impl Into<String>) -> Self {
792 Self::with_input(SpeakInput::Raw(input.into()))
793 }
794
795 pub fn with_input(input: SpeakInput) -> Self {
797 Self { id: request_id(), input, ..Default::default() }
798 }
799
800 pub fn with_model(mut self, model: impl Into<String>) -> Self {
801 self.model = Some(model.into());
802 self
803 }
804
805 pub fn with_voice(mut self, voice: Voice) -> Self {
806 self.voice = Some(voice);
807 self
808 }
809
810 pub fn with_speaker_voice(mut self, speaker: u8, voice: Voice) -> Self {
812 self.voices.retain(|v| v.speaker != speaker);
813 self.voices.push(SpeakerVoice::new(speaker, voice));
814 self
815 }
816
817 pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
818 self.instructions = Some(instructions.into());
819 self
820 }
821
822 pub fn with_language(mut self, language: impl Into<String>) -> Self {
823 self.language = Some(language.into());
824 self
825 }
826
827 pub fn with_speed(mut self, per_mille: u32) -> Self {
829 self.speed = Some(per_mille);
830 self
831 }
832
833 pub fn with_seed(mut self, seed: u64) -> Self {
834 self.seed = Some(seed);
835 self
836 }
837
838 pub fn with_format(mut self, format: AudioFormat) -> Self {
839 self.format = Some(format);
840 self
841 }
842
843 pub fn with_sample_rate(mut self, hz: u32) -> Self {
844 self.sample_rate = Some(hz);
845 self
846 }
847
848 pub fn with_stream(mut self, stream: bool) -> Self {
849 self.stream = stream;
850 self
851 }
852
853 pub fn with_priority(mut self, priority: Priority) -> Self {
854 self.priority = priority;
855 self
856 }
857
858 pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
859 self.cert = Some(cert);
860 self
861 }
862
863 pub fn all_voices(&self) -> impl Iterator<Item = &Voice> {
865 self.voice.iter().chain(self.voices.iter().map(|v| &v.voice))
866 }
867
868 pub fn clones(&self) -> bool {
870 self.all_voices().any(|v| matches!(v, Voice::Clone { .. }))
871 }
872
873 pub fn check(&self) -> Result<(), RemoteError> {
879 let bad = |m: &str| Err(RemoteError::BadRequest { message: m.to_string() });
880 match &self.input {
881 SpeakInput::Text(t) | SpeakInput::Raw(t) if t.trim().is_empty() => return bad("a speech request needs text to speak"),
882 SpeakInput::Script(turns) if turns.is_empty() => return bad("a speech script needs at least one turn"),
883 SpeakInput::Script(turns) if turns.iter().any(|t| t.text.trim().is_empty()) => return bad("every turn of a speech script needs text"),
884 _ => {}
885 }
886 if !self.voices.is_empty() && !matches!(self.input, SpeakInput::Script(_)) {
887 return bad("per-speaker voices need a script input");
888 }
889 let mut seen = std::collections::BTreeSet::new();
890 if let Some(v) = self.voices.iter().find(|v| !seen.insert(v.speaker)) {
891 return Err(RemoteError::BadRequest { message: format!("speaker {} has more than one voice", v.speaker) });
892 }
893 for voice in self.all_voices() {
894 match voice {
895 Voice::Preset { name } if name.trim().is_empty() => return bad("a preset voice needs a name"),
896 Voice::Design { description } if description.trim().is_empty() => return bad("a designed voice needs a description"),
897 Voice::Clone { audio, format, consent, .. } => {
898 if !consent {
899 return bad("cloning a voice needs consent: confirm the voice is yours or you have permission to use it");
900 }
901 if audio.is_empty() {
902 return bad("cloning a voice needs a reference clip");
903 }
904 if audio.len() > MAX_REFERENCE_BYTES {
905 return Err(RemoteError::BadRequest {
906 message: format!("the reference clip is {} bytes, over the {MAX_REFERENCE_BYTES}-byte limit", audio.len()),
907 });
908 }
909 if format.trim().is_empty() {
910 return bad("a reference clip needs its format (wav, mp3, ...)");
911 }
912 }
913 _ => {}
914 }
915 }
916 if self.speed == Some(0) {
917 return bad("a speaking speed of 0 is not a speed (1000 is the model's pace)");
918 }
919 if self.sample_rate == Some(0) {
920 return bad("a sample rate of 0 Hz is not a rate");
921 }
922 Ok(())
923 }
924
925 pub fn needs(&self) -> SpeechNeeds {
930 let mut n = SpeechNeeds::new().with_input_chars(self.input.chars().min(u64::from(u32::MAX)) as u32);
931 for voice in self.all_voices() {
932 n = match voice {
933 Voice::Preset { name } => n.with_preset(name.clone()),
934 Voice::Design { .. } => n.with_design(),
935 Voice::Clone { audio, format, text, .. } => {
936 let ms = if format.eq_ignore_ascii_case("wav") { crate::speech::wav_duration_ms(audio) } else { None };
937 n.with_clone(text.as_deref().is_some_and(|t| !t.trim().is_empty())).with_reference(audio.len() as u64, ms)
938 }
939 };
940 }
941 if let Some(h) = self.input.highest_speaker() {
942 n = n.with_script(h);
943 }
944 if matches!(self.input, SpeakInput::Raw(_)) {
945 n = n.with_raw();
946 }
947 if self.instructions.as_deref().is_some_and(|i| !i.trim().is_empty()) {
948 n = n.with_instructions();
949 }
950 if self.speed.is_some_and(|s| s != 1000) {
951 n = n.with_speed();
952 }
953 if let Some(f) = self.format {
954 n = n.with_format(f);
955 }
956 n
957 }
958}
959
960#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
962#[non_exhaustive]
963pub struct Usage {
964 pub prompt_tokens: u64,
965 pub completion_tokens: u64,
966 #[serde(default)]
967 pub reasoning_tokens: u64,
968 #[serde(default)]
970 pub cached_tokens: u64,
971 #[serde(default, skip_serializing_if = "is_zero")]
973 pub input_chars: u64,
974 #[serde(default, skip_serializing_if = "is_zero")]
976 pub audio_ms: u64,
977}
978
979fn is_zero(n: &u64) -> bool {
980 *n == 0
981}
982
983impl Usage {
984 pub fn new(prompt_tokens: u64, completion_tokens: u64) -> Self {
985 Self { prompt_tokens, completion_tokens, ..Default::default() }
986 }
987
988 pub fn speech(input_chars: u64, audio_ms: u64) -> Self {
990 Self { input_chars, audio_ms, ..Default::default() }
991 }
992}
993
994#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
996#[non_exhaustive]
997pub struct Timings {
998 pub queued_ms: u64,
1000 #[serde(default, skip_serializing_if = "Option::is_none")]
1002 pub first_token_ms: Option<u64>,
1003 pub total_ms: u64,
1005}
1006
1007#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1009#[non_exhaustive]
1010pub struct Resume {
1011 pub offset: u64,
1012 pub node: String,
1013}
1014
1015impl Resume {
1016 pub fn new(offset: u64, node: impl Into<String>) -> Self {
1017 Self { offset, node: node.into() }
1018 }
1019}
1020
1021#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1023#[non_exhaustive]
1024pub struct Meta {
1025 #[serde(default, skip_serializing_if = "Option::is_none")]
1027 pub served_by: Option<String>,
1028 #[serde(default, skip_serializing_if = "Option::is_none")]
1029 pub revision: Option<String>,
1030 #[serde(default)]
1031 pub cache_hit: bool,
1032 #[serde(default, skip_serializing_if = "Option::is_none")]
1034 pub standin: Option<String>,
1035 #[serde(default, skip_serializing_if = "Option::is_none")]
1037 pub resumed_from: Option<u64>,
1038 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1040 pub resumes: Vec<Resume>,
1041 #[serde(default)]
1042 pub timings: Timings,
1043 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1047 pub ignored: Vec<String>,
1048}
1049
1050impl Meta {
1051 pub fn with_ignored(mut self, field: impl Into<String>) -> Self {
1054 let field = field.into();
1055 if !self.ignored.contains(&field) {
1056 self.ignored.push(field);
1057 }
1058 self
1059 }
1060}
1061
1062#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1064#[non_exhaustive]
1065pub struct Finish {
1066 #[serde(default, skip_serializing_if = "Option::is_none")]
1068 pub finish_reason: Option<String>,
1069 #[serde(default, skip_serializing_if = "Option::is_none")]
1070 pub usage: Option<Usage>,
1071 #[serde(default)]
1072 pub meta: Meta,
1073}
1074
1075impl Finish {
1076 pub fn new(finish_reason: impl Into<String>) -> Self {
1077 Self { finish_reason: Some(finish_reason.into()), ..Default::default() }
1078 }
1079
1080 pub fn with_usage(mut self, usage: Usage) -> Self {
1081 self.usage = Some(usage);
1082 self
1083 }
1084}
1085
1086#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1088#[serde(rename_all = "snake_case")]
1089#[non_exhaustive]
1090#[allow(clippy::large_enum_variant)]
1091pub enum ClientFrame {
1092 Infer(Request),
1093 Embed(EmbedRequest),
1094 Cancel {
1095 id: String,
1096 },
1097 Transcribe(TranscribeRequest),
1099 Speak(SpeakRequest),
1101}
1102
1103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1105#[serde(rename_all = "snake_case")]
1106#[non_exhaustive]
1107pub enum ServerFrame {
1108 Queued {
1109 id: String,
1110 position: u32,
1111 },
1112 Accepted {
1113 id: String,
1114 model: String,
1115 attempt: u32,
1116 resume: bool,
1117 },
1118 Delta {
1119 id: String,
1120 offset: u64,
1121 text: String,
1122 },
1123 Reasoning {
1124 id: String,
1125 offset: u64,
1126 text: String,
1127 },
1128 ToolCall {
1129 id: String,
1130 index: u32,
1131 call: ToolCall,
1132 },
1133 Embedding {
1134 id: String,
1135 index: u32,
1136 #[serde(with = "bytes")]
1137 vector: Vec<u8>,
1138 },
1139 Usage {
1140 id: String,
1141 usage: Usage,
1142 },
1143 Done {
1144 id: String,
1145 finish: Finish,
1146 },
1147 Failed {
1148 id: String,
1149 error: RemoteError,
1150 },
1151 Cancelled {
1152 id: String,
1153 },
1154 Meta {
1157 id: String,
1158 meta: Meta,
1159 },
1160 Transcript {
1162 id: String,
1163 transcript: Transcript,
1164 },
1165 Working {
1169 id: String,
1170 },
1171 SpeechStart {
1174 id: String,
1175 format: AudioFormat,
1176 #[serde(default, skip_serializing_if = "Option::is_none")]
1177 sample_rate: Option<u32>,
1178 #[serde(default, skip_serializing_if = "Option::is_none")]
1179 channels: Option<u16>,
1180 },
1181 Audio {
1184 id: String,
1185 offset: u64,
1186 #[serde(with = "bytes")]
1187 data: Vec<u8>,
1188 },
1189}
1190
1191impl ServerFrame {
1192 pub fn id(&self) -> &str {
1194 match self {
1195 ServerFrame::Queued { id, .. }
1196 | ServerFrame::Accepted { id, .. }
1197 | ServerFrame::Delta { id, .. }
1198 | ServerFrame::Reasoning { id, .. }
1199 | ServerFrame::ToolCall { id, .. }
1200 | ServerFrame::Embedding { id, .. }
1201 | ServerFrame::Usage { id, .. }
1202 | ServerFrame::Meta { id, .. }
1203 | ServerFrame::Transcript { id, .. }
1204 | ServerFrame::Working { id }
1205 | ServerFrame::SpeechStart { id, .. }
1206 | ServerFrame::Audio { id, .. }
1207 | ServerFrame::Done { id, .. }
1208 | ServerFrame::Failed { id, .. }
1209 | ServerFrame::Cancelled { id } => id,
1210 }
1211 }
1212}
1213
1214pub fn f32_bytes(v: &[f32]) -> Vec<u8> {
1216 v.iter().flat_map(|x| x.to_le_bytes()).collect()
1217}
1218
1219pub fn bytes_f32(b: &[u8]) -> Result<Vec<f32>, RemoteError> {
1221 if !b.len().is_multiple_of(4) {
1222 return Err(RemoteError::protocol(format!("an embedding of {} bytes is not whole f32s", b.len())));
1223 }
1224 Ok(b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect())
1225}
1226
1227#[derive(Debug, Clone, PartialEq)]
1229pub(crate) enum Piece {
1230 Text(String),
1231 Reasoning(String),
1232 ToolCall(ToolCall),
1233 Usage(Usage),
1234 Meta(Meta),
1235}
1236
1237#[derive(Debug, Clone)]
1239pub struct Output {
1240 tx: mpsc::UnboundedSender<Piece>,
1241}
1242
1243impl Output {
1244 pub(crate) fn channel() -> (Self, mpsc::UnboundedReceiver<Piece>) {
1245 let (tx, rx) = mpsc::unbounded_channel();
1246 (Self { tx }, rx)
1247 }
1248
1249 pub fn text(&self, delta: impl Into<String>) {
1251 let d = delta.into();
1252 if !d.is_empty() {
1253 let _ = self.tx.send(Piece::Text(d));
1254 }
1255 }
1256
1257 pub fn reasoning(&self, delta: impl Into<String>) {
1259 let d = delta.into();
1260 if !d.is_empty() {
1261 let _ = self.tx.send(Piece::Reasoning(d));
1262 }
1263 }
1264
1265 pub fn tool_call(&self, call: ToolCall) {
1267 let _ = self.tx.send(Piece::ToolCall(call));
1268 }
1269
1270 pub fn usage(&self, usage: Usage) {
1272 let _ = self.tx.send(Piece::Usage(usage));
1273 }
1274
1275 pub fn meta(&self, meta: Meta) {
1279 let _ = self.tx.send(Piece::Meta(meta));
1280 }
1281}
1282
1283#[async_trait]
1286pub trait InferBackend: Send + Sync {
1287 fn name(&self) -> String;
1288
1289 fn resumes(&self) -> bool {
1292 false
1293 }
1294
1295 async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError>;
1296}
1297
1298#[async_trait]
1300pub trait EmbedBackend: Send + Sync {
1301 fn name(&self) -> String;
1302
1303 async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError>;
1304
1305 async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
1308 Ok((self.embed(input, cancel).await?, None))
1309 }
1310}
1311
1312#[async_trait]
1315pub trait TranscribeBackend: Send + Sync {
1316 fn name(&self) -> String;
1317
1318 async fn transcribe(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcript, RemoteError>;
1320
1321 async fn transcribe_counted(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<(Transcript, Option<Usage>), RemoteError> {
1324 Ok((self.transcribe(request, cancel).await?, None))
1325 }
1326}
1327
1328#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1331#[non_exhaustive]
1332pub struct AudioHeader {
1333 pub format: AudioFormat,
1334 pub sample_rate: Option<u32>,
1335 pub channels: Option<u16>,
1336}
1337
1338impl AudioHeader {
1339 pub fn new(format: AudioFormat) -> Self {
1340 Self { format, ..Default::default() }
1341 }
1342
1343 pub fn with_sample_rate(mut self, hz: u32) -> Self {
1344 self.sample_rate = Some(hz);
1345 self
1346 }
1347
1348 pub fn with_channels(mut self, channels: u16) -> Self {
1349 self.channels = Some(channels);
1350 self
1351 }
1352}
1353
1354#[derive(Debug, Clone, PartialEq)]
1357#[non_exhaustive]
1358pub enum SpeechPiece {
1359 Start(AudioHeader),
1361 Audio(Vec<u8>),
1364 Usage(Usage),
1367 Meta(Meta),
1370}
1371
1372#[derive(Debug)]
1377pub struct AudioStream {
1378 rx: mpsc::Receiver<Result<SpeechPiece, RemoteError>>,
1379}
1380
1381#[derive(Debug, Clone)]
1384pub struct AudioSink {
1385 tx: mpsc::Sender<Result<SpeechPiece, RemoteError>>,
1386}
1387
1388impl AudioStream {
1389 pub fn channel(buffer: usize) -> (AudioSink, AudioStream) {
1391 let (tx, rx) = mpsc::channel(buffer.max(1));
1392 (AudioSink { tx }, AudioStream { rx })
1393 }
1394
1395 pub fn from_file(header: AudioHeader, audio: Vec<u8>, usage: Option<Usage>) -> Self {
1397 let mut pieces = vec![Ok(SpeechPiece::Start(header)), Ok(SpeechPiece::Audio(audio))];
1398 pieces.extend(usage.map(|u| Ok(SpeechPiece::Usage(u))));
1399 Self::from_pieces(pieces)
1400 }
1401
1402 pub fn from_pieces(pieces: Vec<Result<SpeechPiece, RemoteError>>) -> Self {
1404 let (tx, rx) = mpsc::channel(pieces.len().max(1));
1405 for p in pieces {
1406 let _ = tx.try_send(p);
1407 }
1408 Self { rx }
1409 }
1410
1411 pub async fn next(&mut self) -> Option<Result<SpeechPiece, RemoteError>> {
1413 self.rx.recv().await
1414 }
1415}
1416
1417impl AudioSink {
1418 async fn send(&self, piece: Result<SpeechPiece, RemoteError>) -> Result<(), RemoteError> {
1419 self.tx.send(piece).await.map_err(|_| RemoteError::Cancelled)
1420 }
1421
1422 pub async fn start(&self, header: AudioHeader) -> Result<(), RemoteError> {
1424 self.send(Ok(SpeechPiece::Start(header))).await
1425 }
1426
1427 pub async fn audio(&self, data: Vec<u8>) -> Result<(), RemoteError> {
1429 if data.is_empty() {
1430 return Ok(());
1431 }
1432 self.send(Ok(SpeechPiece::Audio(data))).await
1433 }
1434
1435 pub async fn usage(&self, usage: Usage) -> Result<(), RemoteError> {
1436 self.send(Ok(SpeechPiece::Usage(usage))).await
1437 }
1438
1439 pub async fn meta(&self, meta: Meta) -> Result<(), RemoteError> {
1440 self.send(Ok(SpeechPiece::Meta(meta))).await
1441 }
1442
1443 pub async fn fail(&self, error: RemoteError) -> Result<(), RemoteError> {
1445 self.send(Err(error)).await
1446 }
1447
1448 pub fn is_closed(&self) -> bool {
1450 self.tx.is_closed()
1451 }
1452}
1453
1454#[async_trait]
1457pub trait SpeakBackend: Send + Sync {
1458 fn name(&self) -> String;
1459
1460 async fn speak(&self, request: &SpeakRequest, cancel: &CancelToken) -> Result<AudioStream, RemoteError>;
1466}
1467
1468pub struct ModelAdapter {
1471 backend: Arc<dyn ModelBackend>,
1472}
1473
1474impl ModelAdapter {
1475 pub fn new(backend: Arc<dyn ModelBackend>) -> Self {
1476 Self { backend }
1477 }
1478}
1479
1480#[async_trait]
1481impl InferBackend for ModelAdapter {
1482 fn name(&self) -> String {
1483 self.backend.name()
1484 }
1485
1486 async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
1487 let messages = match &request.input {
1488 Input::Messages(m) => m,
1489 Input::Prompt(_) => return Err(RemoteError::Unsupported { message: "this backend takes messages, not a raw prompt".into() }),
1490 _ => return Err(RemoteError::unavailable("this node keeps no conversations; send the messages")),
1491 };
1492 let (tx, mut rx) = mpsc::unbounded_channel();
1493 let sink = DeltaSink::new(Some(tx));
1494 let forward = |ev: AgentEvent| match ev {
1495 AgentEvent::TextDelta(t) => out.text(t),
1496 AgentEvent::ReasoningDelta(t) => out.reasoning(t),
1497 _ => {}
1498 };
1499 let mut run = pin!(self.backend.complete(messages, &request.tools, &sink, cancel));
1500 let turn = loop {
1501 tokio::select! {
1502 r = &mut run => break r,
1503 Some(ev) = rx.recv() => forward(ev),
1504 }
1505 };
1506 while let Ok(ev) = rx.try_recv() {
1507 forward(ev);
1508 }
1509 let turn = turn.map_err(model_error)?;
1510 let calls = !turn.tool_calls.is_empty();
1511 for call in turn.tool_calls {
1512 out.tool_call(call);
1513 }
1514 Ok(Finish::new(if calls { "tool_calls" } else { "stop" }))
1515 }
1516}
1517
1518fn is_cancel(bytes: &[u8], id: &str) -> bool {
1519 matches!(crate::remote::from_cbor::<ClientFrame>(bytes), Ok(ClientFrame::Cancel { id: c }) if c == id)
1520}
1521
1522fn millis(d: Duration) -> u64 {
1523 d.as_millis().min(u64::MAX as u128) as u64
1524}
1525
1526enum Waited {
1527 Go(super::queue::Permit),
1528 Gone,
1530}
1531
1532async fn wait_turn(ch: &mut Channel, id: &str, admission: &Admission, priority: Priority) -> Result<Waited, RemoteError> {
1534 let mut ticket = match admission.enter(priority) {
1535 Ok(t) => t,
1536 Err(error) => {
1537 ch.send_cbor(&ServerFrame::Failed { id: id.to_string(), error }).await?;
1538 return Ok(Waited::Gone);
1539 }
1540 };
1541 let mut last = None;
1542 loop {
1543 tokio::select! {
1544 turn = ticket.turn(last, QUEUE_KEEPALIVE) => match turn {
1545 Turn::Go(permit) => return Ok(Waited::Go(permit)),
1546 Turn::Waiting(position) => {
1547 last = Some(position);
1548 ch.send_cbor(&ServerFrame::Queued { id: id.to_string(), position }).await?;
1549 }
1550 },
1551 m = ch.rx.recv() => match m {
1552 Ok(Some(bytes)) if is_cancel(&bytes, id) => {
1553 ch.send_cbor(&ServerFrame::Cancelled { id: id.to_string() }).await?;
1554 return Ok(Waited::Gone);
1555 }
1556 Ok(Some(_)) => {}
1557 Ok(None) | Err(_) => return Ok(Waited::Gone),
1558 },
1559 }
1560 }
1561}
1562
1563pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission) -> Result<(), RemoteError> {
1568 match ch.recv_cbor::<ClientFrame>().await? {
1569 Some(ClientFrame::Infer(request)) => serve_infer(ch, caller, host, admission, request).await,
1570 Some(ClientFrame::Embed(request)) => serve_embed(ch, caller, host, admission, request).await,
1571 Some(ClientFrame::Transcribe(request)) => serve_transcribe(ch, caller, host, admission, request).await,
1572 Some(ClientFrame::Speak(request)) => serve_speak(ch, caller, host, admission, request).await,
1573 Some(ClientFrame::Cancel { .. }) | None => Ok(()),
1574 }
1575}
1576
1577async fn serve_infer(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission, mut request: Request) -> Result<(), RemoteError> {
1578 let started = Instant::now();
1579 let id = request.id.clone();
1580 let caller = caller.presenting(request.cert.take());
1581 let checked = host.authorize(&caller).and_then(|()| {
1582 if matches!(request.input, Input::Prompt(_)) && !request.tools.is_empty() {
1583 return Err(RemoteError::BadRequest { message: "a raw prompt takes no tools".into() });
1584 }
1585 if request.raw && matches!(request.input, Input::Context(_)) {
1586 return Err(RemoteError::BadRequest { message: "raw mode takes assembled messages, not a context_ref".into() });
1587 }
1588 if request.assistant_prefix.as_ref().is_some_and(|p| !p.is_consistent()) {
1589 return Err(RemoteError::BadRequest { message: "assistant_prefix lengths do not match its text".into() });
1590 }
1591 host.open_request(&caller, &request)
1592 });
1593 let backend = match checked {
1594 Ok(b) => b,
1595 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1596 };
1597 let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1598 Waited::Go(p) => p,
1599 Waited::Gone => return Ok(()),
1600 };
1601 let queued = started.elapsed();
1602 let resume = backend.resumes();
1603 let prefix = request.assistant_prefix.clone().filter(|_| resume);
1604 if !resume {
1605 request.assistant_prefix = None;
1606 }
1607 let (text_at, reasoning_at) = prefix.as_ref().map(|p| (p.len, p.reasoning_len)).unwrap_or((0, 0));
1608 ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: request.attempt, resume }).await?;
1609 let accepted = Instant::now();
1610
1611 let (out, mut pieces) = Output::channel();
1612 let cancel = CancelToken::new();
1613 let mut framer =
1614 Framer { id: id.clone(), text_at, reasoning_at, calls: 0, accepted, first_token: None, early_meta: request.early_meta, meta: None };
1615 let mut run = pin!(backend.infer(&request, &out, &cancel));
1616 let mut asker_open = true;
1617 let mut send_failed = false;
1618 let result = loop {
1619 tokio::select! {
1620 r = &mut run => break r,
1621 Some(p) = pieces.recv() => {
1622 let Some(f) = framer.frame(p) else { continue };
1623 if !send_failed && ch.send_cbor(&f).await.is_err() {
1624 send_failed = true;
1625 cancel.cancel();
1626 }
1627 }
1628 m = ch.rx.recv(), if asker_open => match m {
1629 Ok(Some(bytes)) => {
1630 if is_cancel(&bytes, &id) {
1631 cancel.cancel();
1632 }
1633 }
1634 Ok(None) | Err(_) => {
1635 asker_open = false;
1636 cancel.cancel();
1637 }
1638 },
1639 }
1640 };
1641 if send_failed || !asker_open {
1642 return Ok(());
1643 }
1644 while let Ok(p) = pieces.try_recv() {
1645 if let Some(f) = framer.frame(p) {
1646 ch.send_cbor(&f).await?;
1647 }
1648 }
1649 let reply = match result {
1650 Ok(mut finish) => {
1651 let meta = &mut finish.meta;
1652 if let Some(early) = framer.meta.take() {
1653 meta.cache_hit |= early.cache_hit;
1654 if meta.served_by.is_none() {
1655 meta.served_by = early.served_by;
1656 }
1657 if meta.revision.is_none() {
1658 meta.revision = early.revision;
1659 }
1660 if meta.standin.is_none() {
1661 meta.standin = early.standin;
1662 }
1663 }
1664 meta.served_by.get_or_insert_with(|| backend.name());
1665 if let Some(p) = &prefix {
1666 meta.resumed_from = Some(p.len);
1667 }
1668 meta.timings.queued_ms = millis(queued);
1669 meta.timings.first_token_ms = framer.first_token.map(millis);
1670 meta.timings.total_ms = millis(started.elapsed());
1671 ServerFrame::Done { id, finish }
1672 }
1673 Err(_) if cancel.is_cancelled() => ServerFrame::Cancelled { id },
1674 Err(error) => ServerFrame::Failed { id, error },
1675 };
1676 ch.send_cbor(&reply).await
1677}
1678
1679struct Framer {
1681 id: String,
1682 text_at: u64,
1683 reasoning_at: u64,
1684 calls: u32,
1685 accepted: Instant,
1686 first_token: Option<Duration>,
1687 early_meta: bool,
1689 meta: Option<Meta>,
1691}
1692
1693impl Framer {
1694 fn frame(&mut self, p: Piece) -> Option<ServerFrame> {
1695 let id = self.id.clone();
1696 Some(match p {
1697 Piece::Text(text) => {
1698 self.first_token.get_or_insert_with(|| self.accepted.elapsed());
1699 let offset = self.text_at;
1700 self.text_at += chars(&text);
1701 ServerFrame::Delta { id, offset, text }
1702 }
1703 Piece::Reasoning(text) => {
1704 self.first_token.get_or_insert_with(|| self.accepted.elapsed());
1705 let offset = self.reasoning_at;
1706 self.reasoning_at += chars(&text);
1707 ServerFrame::Reasoning { id, offset, text }
1708 }
1709 Piece::ToolCall(call) => {
1710 self.calls += 1;
1711 ServerFrame::ToolCall { id, index: self.calls - 1, call }
1712 }
1713 Piece::Usage(usage) => ServerFrame::Usage { id, usage },
1714 Piece::Meta(meta) => {
1715 self.meta = Some(meta.clone());
1716 if !self.early_meta {
1717 return None;
1718 }
1719 ServerFrame::Meta { id, meta }
1720 }
1721 })
1722 }
1723}
1724
1725async fn serve_embed(
1726 mut ch: Channel,
1727 caller: Caller,
1728 host: &dyn InferHost,
1729 admission: &Admission,
1730 mut request: EmbedRequest,
1731) -> Result<(), RemoteError> {
1732 let started = Instant::now();
1733 let id = request.id.clone();
1734 let caller = caller.presenting(request.cert.take());
1735 let backend = match host.authorize(&caller).and_then(|()| host.open_embed(&caller, request.model.as_deref())) {
1736 Ok(b) => b,
1737 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1738 };
1739 let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1740 Waited::Go(p) => p,
1741 Waited::Gone => return Ok(()),
1742 };
1743 let queued = started.elapsed();
1744 ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1745 let cancel = CancelToken::new();
1746 let mut tokens: Option<u64> = None;
1747 for (index, input) in request.inputs.iter().enumerate() {
1748 let vector = tokio::select! {
1749 v = backend.embed_counted(input, &cancel) => v,
1750 m = async { loop {
1751 match ch.rx.recv().await {
1752 Ok(Some(bytes)) if is_cancel(&bytes, &id) => return true,
1753 Ok(Some(_)) => {}
1754 Ok(None) | Err(_) => return false,
1755 }
1756 } } => {
1757 cancel.cancel();
1758 return if m { ch.send_cbor(&ServerFrame::Cancelled { id }).await } else { Ok(()) };
1759 }
1760 };
1761 match vector {
1762 Ok((v, n)) => {
1763 if let Some(n) = n {
1764 *tokens.get_or_insert(0) += n;
1765 }
1766 ch.send_cbor(&ServerFrame::Embedding { id: id.clone(), index: index as u32, vector: f32_bytes(&v) }).await?
1767 }
1768 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1769 }
1770 }
1771 let mut finish = Finish::new("stop");
1772 finish.usage = tokens.map(|n| Usage::new(n, 0));
1773 finish.meta.served_by = Some(backend.name());
1774 finish.meta.timings.queued_ms = millis(queued);
1775 finish.meta.timings.total_ms = millis(started.elapsed());
1776 ch.send_cbor(&ServerFrame::Done { id, finish }).await
1777}
1778
1779async fn serve_transcribe(
1780 mut ch: Channel,
1781 caller: Caller,
1782 host: &dyn InferHost,
1783 admission: &Admission,
1784 mut request: TranscribeRequest,
1785) -> Result<(), RemoteError> {
1786 let started = Instant::now();
1787 let id = request.id.clone();
1788 let caller = caller.presenting(request.cert.take());
1789 let opened = host.authorize(&caller).and_then(|()| request.check()).and_then(|()| host.open_transcribe(&caller, request.model.as_deref()));
1790 let backend = match opened {
1791 Ok(b) => b,
1792 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1793 };
1794 let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1795 Waited::Go(p) => p,
1796 Waited::Gone => return Ok(()),
1797 };
1798 let queued = started.elapsed();
1799 ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1800 let cancel = CancelToken::new();
1801 let mut run = pin!(backend.transcribe_counted(&request, &cancel));
1802 let mut keepalive = tokio::time::interval_at(Instant::now() + QUEUE_KEEPALIVE, QUEUE_KEEPALIVE);
1803 let result = loop {
1804 tokio::select! {
1805 r = &mut run => break r,
1806 _ = keepalive.tick() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
1807 m = ch.rx.recv() => match m {
1808 Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
1809 cancel.cancel();
1810 return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
1811 }
1812 Ok(Some(_)) => {}
1813 Ok(None) | Err(_) => {
1814 cancel.cancel();
1815 return Ok(());
1816 }
1817 },
1818 }
1819 };
1820 let (transcript, usage) = match result {
1821 Ok(r) => r,
1822 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1823 };
1824 ch.send_cbor(&ServerFrame::Transcript { id: id.clone(), transcript }).await?;
1825 let mut finish = Finish::new("stop");
1826 finish.usage = usage;
1827 finish.meta.served_by = Some(backend.name());
1828 finish.meta.timings.queued_ms = millis(queued);
1829 finish.meta.timings.total_ms = millis(started.elapsed());
1830 ch.send_cbor(&ServerFrame::Done { id, finish }).await
1831}
1832
1833struct CancelOnDrop(CancelToken);
1835
1836impl Drop for CancelOnDrop {
1837 fn drop(&mut self) {
1838 self.0.cancel();
1839 }
1840}
1841
1842async fn serve_speak(
1843 mut ch: Channel,
1844 caller: Caller,
1845 host: &dyn InferHost,
1846 admission: &Admission,
1847 mut request: SpeakRequest,
1848) -> Result<(), RemoteError> {
1849 let started = Instant::now();
1850 let id = request.id.clone();
1851 let caller = caller.presenting(request.cert.take());
1852 let opened = host.authorize(&caller).and_then(|()| request.check()).and_then(|()| host.open_speak(&caller, &request));
1853 let backend = match opened {
1854 Ok(b) => b,
1855 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1856 };
1857 let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1858 Waited::Go(p) => p,
1859 Waited::Gone => return Ok(()),
1860 };
1861 let queued = started.elapsed();
1862 ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1863 let accepted = Instant::now();
1864 let cancel = CancelToken::new();
1865 let _stop = CancelOnDrop(cancel.clone());
1866 let mut keepalive = tokio::time::interval_at(Instant::now() + QUEUE_KEEPALIVE, QUEUE_KEEPALIVE);
1867 let opened = {
1868 let mut run = pin!(backend.speak(&request, &cancel));
1869 loop {
1870 tokio::select! {
1871 r = &mut run => break r,
1872 _ = keepalive.tick() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
1873 m = ch.rx.recv() => match m {
1874 Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
1875 cancel.cancel();
1876 return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
1877 }
1878 Ok(Some(_)) => {}
1879 Ok(None) | Err(_) => return Ok(()),
1880 },
1881 }
1882 }
1883 };
1884 let mut stream = match opened {
1885 Ok(s) => s,
1886 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1887 };
1888 let mut first_audio = None;
1889 let mut offset = 0u64;
1890 let mut usage: Option<Usage> = None;
1891 let mut meta = Meta::default();
1892 loop {
1893 tokio::select! {
1894 p = stream.next() => match p {
1895 None => break,
1896 Some(Err(error)) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1897 Some(Ok(SpeechPiece::Start(h))) if first_audio.is_none() => {
1898 first_audio = Some(accepted.elapsed());
1899 ch.send_cbor(&ServerFrame::SpeechStart { id: id.clone(), format: h.format, sample_rate: h.sample_rate, channels: h.channels }).await?;
1900 }
1901 Some(Ok(SpeechPiece::Start(_))) => {
1902 let error = RemoteError::protocol("the speech backend started the audio twice");
1903 return ch.send_cbor(&ServerFrame::Failed { id, error }).await;
1904 }
1905 Some(Ok(SpeechPiece::Audio(data))) if first_audio.is_some() => {
1906 for chunk in data.chunks(MAX_AUDIO_CHUNK) {
1907 ch.send_cbor(&ServerFrame::Audio { id: id.clone(), offset, data: chunk.to_vec() }).await?;
1908 offset += chunk.len() as u64;
1909 }
1910 }
1911 Some(Ok(SpeechPiece::Audio(_))) => {
1912 let error = RemoteError::protocol("the speech backend sent audio before its format");
1913 return ch.send_cbor(&ServerFrame::Failed { id, error }).await;
1914 }
1915 Some(Ok(SpeechPiece::Usage(u))) => usage = Some(u),
1916 Some(Ok(SpeechPiece::Meta(m))) => {
1917 for field in m.ignored {
1918 if !meta.ignored.contains(&field) {
1919 meta.ignored.push(field);
1920 }
1921 }
1922 if m.served_by.is_some() {
1923 meta.served_by = m.served_by;
1924 }
1925 if m.revision.is_some() {
1926 meta.revision = m.revision;
1927 }
1928 }
1929 },
1930 _ = keepalive.tick(), if first_audio.is_none() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
1931 m = ch.rx.recv() => match m {
1932 Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
1933 cancel.cancel();
1934 return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
1935 }
1936 Ok(Some(_)) => {}
1937 Ok(None) | Err(_) => return Ok(()),
1938 },
1939 }
1940 }
1941 if first_audio.is_none() {
1942 let error = RemoteError::Failed { message: "the speech backend finished without audio".into() };
1943 return ch.send_cbor(&ServerFrame::Failed { id, error }).await;
1944 }
1945 let mut usage = usage.unwrap_or_default();
1946 if usage.input_chars == 0 {
1947 usage.input_chars = request.input.chars();
1948 }
1949 let mut finish = Finish::new("stop").with_usage(usage);
1950 meta.served_by.get_or_insert_with(|| backend.name());
1951 meta.timings.queued_ms = millis(queued);
1952 meta.timings.first_token_ms = first_audio.map(millis);
1953 meta.timings.total_ms = millis(started.elapsed());
1954 finish.meta = meta;
1955 ch.send_cbor(&ServerFrame::Done { id, finish }).await
1956}