1use std::pin::pin;
48use std::sync::Arc;
49use std::time::Duration;
50
51use tokio::time::Instant;
52
53use async_trait::async_trait;
54use serde::{Deserialize, Serialize};
55use serde_json::Value;
56use tokio::sync::mpsc;
57
58use super::queue::{Admission, Turn};
59use super::{InferHost, model_error};
60use crate::cancel::CancelToken;
61use crate::model::{DeltaSink, Message, Modalities, ModelBackend, Role, ToolCall};
62use crate::remote::{Caller, Channel, RemoteError, bytes, request_id};
63use crate::session::AgentEvent;
64use crate::tool::ToolSpec;
65
66pub const PROTOCOL: &str = "/weirdnet-agent/infer/2";
68
69pub const QUEUE_KEEPALIVE: Duration = Duration::from_secs(3);
71
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76#[non_exhaustive]
77pub enum Priority {
78 #[default]
79 Interactive,
80 Batch,
81 Background,
82}
83
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87#[non_exhaustive]
88pub enum CacheMode {
89 #[default]
91 Use,
92 Bypass,
94 Refresh,
96}
97
98impl CacheMode {
99 pub fn is_use(&self) -> bool {
100 *self == CacheMode::Use
101 }
102
103 pub fn may_read(&self) -> bool {
105 *self == CacheMode::Use
106 }
107
108 pub fn may_store(&self) -> bool {
110 matches!(self, CacheMode::Use | CacheMode::Refresh)
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
116#[non_exhaustive]
117pub struct ContextRef {
118 pub conversation: String,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub head: Option<String>,
122}
123
124impl ContextRef {
125 pub fn new(conversation: impl Into<String>, head: Option<String>) -> Self {
126 Self { conversation: conversation.into(), head }
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[serde(rename_all = "snake_case")]
133#[non_exhaustive]
134pub enum Input {
135 Messages(Vec<Message>),
137 Context(ContextRef),
139 Prompt(String),
142}
143
144impl Default for Input {
145 fn default() -> Self {
146 Input::Messages(Vec::new())
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
152#[non_exhaustive]
153pub struct Prefix {
154 pub text: String,
155 pub len: u64,
156 #[serde(default, skip_serializing_if = "String::is_empty")]
157 pub reasoning: String,
158 #[serde(default)]
159 pub reasoning_len: u64,
160}
161
162impl Prefix {
163 pub fn new(text: impl Into<String>, reasoning: impl Into<String>) -> Self {
164 let (text, reasoning) = (text.into(), reasoning.into());
165 Self { len: chars(&text), reasoning_len: chars(&reasoning), text, reasoning }
166 }
167
168 pub fn is_consistent(&self) -> bool {
170 self.len == chars(&self.text) && self.reasoning_len == chars(&self.reasoning)
171 }
172
173 pub fn is_empty(&self) -> bool {
174 self.text.is_empty() && self.reasoning.is_empty()
175 }
176}
177
178pub fn chars(s: &str) -> u64 {
180 s.chars().count() as u64
181}
182
183#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
185#[non_exhaustive]
186pub struct Sampling {
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub temperature: Option<f32>,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub top_p: Option<f32>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub top_k: Option<u32>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub min_p: Option<f32>,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub max_tokens: Option<u32>,
197 #[serde(default, skip_serializing_if = "Vec::is_empty")]
198 pub stop: Vec<String>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub presence_penalty: Option<f32>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub frequency_penalty: Option<f32>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub repeat_penalty: Option<f32>,
205}
206
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
209#[serde(rename_all = "snake_case")]
210#[non_exhaustive]
211pub enum ResponseFormat {
212 Text,
213 Json,
215 JsonSchema {
217 name: String,
218 schema: Value,
219 #[serde(default)]
220 strict: bool,
221 },
222}
223
224#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
226#[non_exhaustive]
227pub struct Request {
228 pub id: String,
230 pub job_id: String,
232 #[serde(default)]
234 pub attempt: u32,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub model: Option<String>,
238 #[serde(default)]
239 pub priority: Priority,
240 pub input: Input,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub assistant_prefix: Option<Prefix>,
244 #[serde(default)]
245 pub sampling: Sampling,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub seed: Option<u64>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub response_format: Option<ResponseFormat>,
250 #[serde(default, skip_serializing_if = "Vec::is_empty")]
251 pub tools: Vec<ToolSpec>,
252 #[serde(default)]
255 pub raw: bool,
256 #[serde(default)]
258 pub wait_for_model: bool,
259 #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
262 pub cert: Option<Vec<u8>>,
263 #[serde(default, skip_serializing_if = "is_false")]
267 pub early_meta: bool,
268 #[serde(default, skip_serializing_if = "CacheMode::is_use")]
271 pub cache: CacheMode,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub adapter_scale: Option<f32>,
278}
279
280fn is_false(b: &bool) -> bool {
281 !*b
282}
283
284impl Request {
285 pub fn messages(messages: Vec<Message>) -> Self {
287 Self::with_input(Input::Messages(messages))
288 }
289
290 pub fn context(context: ContextRef) -> Self {
292 Self::with_input(Input::Context(context))
293 }
294
295 pub fn prompt(prompt: impl Into<String>) -> Self {
297 Self::with_input(Input::Prompt(prompt.into()))
298 }
299
300 fn with_input(input: Input) -> Self {
301 let id = request_id();
302 Self { job_id: id.clone(), id, input, ..Default::default() }
303 }
304
305 pub fn with_model(mut self, model: impl Into<String>) -> Self {
306 self.model = Some(model.into());
307 self
308 }
309
310 pub fn with_priority(mut self, priority: Priority) -> Self {
311 self.priority = priority;
312 self
313 }
314
315 pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
316 self.tools = tools;
317 self
318 }
319
320 pub fn with_sampling(mut self, sampling: Sampling) -> Self {
321 self.sampling = sampling;
322 self
323 }
324
325 pub fn with_seed(mut self, seed: u64) -> Self {
326 self.seed = Some(seed);
327 self
328 }
329
330 pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
331 self.response_format = Some(format);
332 self
333 }
334
335 pub fn with_job_id(mut self, job_id: impl Into<String>) -> Self {
336 self.job_id = job_id.into();
337 self
338 }
339
340 pub fn with_prefix(mut self, prefix: Prefix) -> Self {
341 self.assistant_prefix = Some(prefix);
342 self
343 }
344
345 pub fn continuing(mut self) -> Self {
350 if let Input::Messages(m) = &mut self.input
351 && m.last().is_some_and(|last| last.role == Role::Assistant && last.tool_calls.is_empty() && last.content.as_text().is_some())
352 && let Some(last) = m.pop()
353 {
354 self.assistant_prefix = Some(Prefix::new(last.content.into_text(), ""));
355 }
356 self
357 }
358
359 pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
360 self.cert = Some(cert);
361 self
362 }
363
364 pub fn with_cache(mut self, cache: CacheMode) -> Self {
366 self.cache = cache;
367 self
368 }
369
370 pub fn with_adapter_scale(mut self, scale: f32) -> Self {
373 self.adapter_scale = Some(scale);
374 self
375 }
376
377 pub fn with_wait_for_model(mut self, wait: bool) -> Self {
379 self.wait_for_model = wait;
380 self
381 }
382
383 pub fn raw(mut self) -> Self {
385 self.raw = true;
386 self
387 }
388
389 pub fn inline_messages(&self) -> Option<&[Message]> {
391 match &self.input {
392 Input::Messages(m) => Some(m),
393 _ => None,
394 }
395 }
396
397 pub fn needs(&self) -> Modalities {
400 self.inline_messages().map(crate::model::needs).unwrap_or(Modalities::TEXT)
401 }
402
403 pub fn raw_prompt(&self) -> Option<&str> {
405 match &self.input {
406 Input::Prompt(p) => Some(p),
407 _ => None,
408 }
409 }
410
411 pub fn next_attempt(&self) -> Self {
413 Self { id: request_id(), attempt: self.attempt + 1, ..self.clone() }
414 }
415}
416
417#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
419#[non_exhaustive]
420pub struct EmbedRequest {
421 pub id: String,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 pub model: Option<String>,
424 pub inputs: Vec<String>,
425 #[serde(default)]
426 pub priority: Priority,
427 #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
428 pub cert: Option<Vec<u8>>,
429}
430
431impl EmbedRequest {
432 pub fn new(inputs: Vec<String>) -> Self {
433 Self { id: request_id(), inputs, ..Default::default() }
434 }
435
436 pub fn with_model(mut self, model: impl Into<String>) -> Self {
437 self.model = Some(model.into());
438 self
439 }
440
441 pub fn with_priority(mut self, priority: Priority) -> Self {
442 self.priority = priority;
443 self
444 }
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
449#[non_exhaustive]
450pub struct Usage {
451 pub prompt_tokens: u64,
452 pub completion_tokens: u64,
453 #[serde(default)]
454 pub reasoning_tokens: u64,
455 #[serde(default)]
457 pub cached_tokens: u64,
458}
459
460impl Usage {
461 pub fn new(prompt_tokens: u64, completion_tokens: u64) -> Self {
462 Self { prompt_tokens, completion_tokens, ..Default::default() }
463 }
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
468#[non_exhaustive]
469pub struct Timings {
470 pub queued_ms: u64,
472 #[serde(default, skip_serializing_if = "Option::is_none")]
474 pub first_token_ms: Option<u64>,
475 pub total_ms: u64,
477}
478
479#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
481#[non_exhaustive]
482pub struct Resume {
483 pub offset: u64,
484 pub node: String,
485}
486
487impl Resume {
488 pub fn new(offset: u64, node: impl Into<String>) -> Self {
489 Self { offset, node: node.into() }
490 }
491}
492
493#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
495#[non_exhaustive]
496pub struct Meta {
497 #[serde(default, skip_serializing_if = "Option::is_none")]
499 pub served_by: Option<String>,
500 #[serde(default, skip_serializing_if = "Option::is_none")]
501 pub revision: Option<String>,
502 #[serde(default)]
503 pub cache_hit: bool,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub standin: Option<String>,
507 #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub resumed_from: Option<u64>,
510 #[serde(default, skip_serializing_if = "Vec::is_empty")]
512 pub resumes: Vec<Resume>,
513 #[serde(default)]
514 pub timings: Timings,
515}
516
517#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
519#[non_exhaustive]
520pub struct Finish {
521 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub finish_reason: Option<String>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
525 pub usage: Option<Usage>,
526 #[serde(default)]
527 pub meta: Meta,
528}
529
530impl Finish {
531 pub fn new(finish_reason: impl Into<String>) -> Self {
532 Self { finish_reason: Some(finish_reason.into()), ..Default::default() }
533 }
534
535 pub fn with_usage(mut self, usage: Usage) -> Self {
536 self.usage = Some(usage);
537 self
538 }
539}
540
541#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
543#[serde(rename_all = "snake_case")]
544#[non_exhaustive]
545#[allow(clippy::large_enum_variant)]
546pub enum ClientFrame {
547 Infer(Request),
548 Embed(EmbedRequest),
549 Cancel { id: String },
550}
551
552#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
554#[serde(rename_all = "snake_case")]
555#[non_exhaustive]
556pub enum ServerFrame {
557 Queued {
558 id: String,
559 position: u32,
560 },
561 Accepted {
562 id: String,
563 model: String,
564 attempt: u32,
565 resume: bool,
566 },
567 Delta {
568 id: String,
569 offset: u64,
570 text: String,
571 },
572 Reasoning {
573 id: String,
574 offset: u64,
575 text: String,
576 },
577 ToolCall {
578 id: String,
579 index: u32,
580 call: ToolCall,
581 },
582 Embedding {
583 id: String,
584 index: u32,
585 #[serde(with = "bytes")]
586 vector: Vec<u8>,
587 },
588 Usage {
589 id: String,
590 usage: Usage,
591 },
592 Done {
593 id: String,
594 finish: Finish,
595 },
596 Failed {
597 id: String,
598 error: RemoteError,
599 },
600 Cancelled {
601 id: String,
602 },
603 Meta {
606 id: String,
607 meta: Meta,
608 },
609}
610
611impl ServerFrame {
612 pub fn id(&self) -> &str {
614 match self {
615 ServerFrame::Queued { id, .. }
616 | ServerFrame::Accepted { id, .. }
617 | ServerFrame::Delta { id, .. }
618 | ServerFrame::Reasoning { id, .. }
619 | ServerFrame::ToolCall { id, .. }
620 | ServerFrame::Embedding { id, .. }
621 | ServerFrame::Usage { id, .. }
622 | ServerFrame::Meta { id, .. }
623 | ServerFrame::Done { id, .. }
624 | ServerFrame::Failed { id, .. }
625 | ServerFrame::Cancelled { id } => id,
626 }
627 }
628}
629
630pub fn f32_bytes(v: &[f32]) -> Vec<u8> {
632 v.iter().flat_map(|x| x.to_le_bytes()).collect()
633}
634
635pub fn bytes_f32(b: &[u8]) -> Result<Vec<f32>, RemoteError> {
637 if !b.len().is_multiple_of(4) {
638 return Err(RemoteError::protocol(format!("an embedding of {} bytes is not whole f32s", b.len())));
639 }
640 Ok(b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect())
641}
642
643#[derive(Debug, Clone, PartialEq)]
645pub(crate) enum Piece {
646 Text(String),
647 Reasoning(String),
648 ToolCall(ToolCall),
649 Usage(Usage),
650 Meta(Meta),
651}
652
653#[derive(Debug, Clone)]
655pub struct Output {
656 tx: mpsc::UnboundedSender<Piece>,
657}
658
659impl Output {
660 pub(crate) fn channel() -> (Self, mpsc::UnboundedReceiver<Piece>) {
661 let (tx, rx) = mpsc::unbounded_channel();
662 (Self { tx }, rx)
663 }
664
665 pub fn text(&self, delta: impl Into<String>) {
667 let d = delta.into();
668 if !d.is_empty() {
669 let _ = self.tx.send(Piece::Text(d));
670 }
671 }
672
673 pub fn reasoning(&self, delta: impl Into<String>) {
675 let d = delta.into();
676 if !d.is_empty() {
677 let _ = self.tx.send(Piece::Reasoning(d));
678 }
679 }
680
681 pub fn tool_call(&self, call: ToolCall) {
683 let _ = self.tx.send(Piece::ToolCall(call));
684 }
685
686 pub fn usage(&self, usage: Usage) {
688 let _ = self.tx.send(Piece::Usage(usage));
689 }
690
691 pub fn meta(&self, meta: Meta) {
695 let _ = self.tx.send(Piece::Meta(meta));
696 }
697}
698
699#[async_trait]
702pub trait InferBackend: Send + Sync {
703 fn name(&self) -> String;
704
705 fn resumes(&self) -> bool {
708 false
709 }
710
711 async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError>;
712}
713
714#[async_trait]
716pub trait EmbedBackend: Send + Sync {
717 fn name(&self) -> String;
718
719 async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError>;
720
721 async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
724 Ok((self.embed(input, cancel).await?, None))
725 }
726}
727
728pub struct ModelAdapter {
731 backend: Arc<dyn ModelBackend>,
732}
733
734impl ModelAdapter {
735 pub fn new(backend: Arc<dyn ModelBackend>) -> Self {
736 Self { backend }
737 }
738}
739
740#[async_trait]
741impl InferBackend for ModelAdapter {
742 fn name(&self) -> String {
743 self.backend.name()
744 }
745
746 async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
747 let messages = match &request.input {
748 Input::Messages(m) => m,
749 Input::Prompt(_) => return Err(RemoteError::Unsupported { message: "this backend takes messages, not a raw prompt".into() }),
750 _ => return Err(RemoteError::unavailable("this node keeps no conversations; send the messages")),
751 };
752 let (tx, mut rx) = mpsc::unbounded_channel();
753 let sink = DeltaSink::new(Some(tx));
754 let forward = |ev: AgentEvent| match ev {
755 AgentEvent::TextDelta(t) => out.text(t),
756 AgentEvent::ReasoningDelta(t) => out.reasoning(t),
757 _ => {}
758 };
759 let mut run = pin!(self.backend.complete(messages, &request.tools, &sink, cancel));
760 let turn = loop {
761 tokio::select! {
762 r = &mut run => break r,
763 Some(ev) = rx.recv() => forward(ev),
764 }
765 };
766 while let Ok(ev) = rx.try_recv() {
767 forward(ev);
768 }
769 let turn = turn.map_err(model_error)?;
770 let calls = !turn.tool_calls.is_empty();
771 for call in turn.tool_calls {
772 out.tool_call(call);
773 }
774 Ok(Finish::new(if calls { "tool_calls" } else { "stop" }))
775 }
776}
777
778fn is_cancel(bytes: &[u8], id: &str) -> bool {
779 matches!(crate::remote::from_cbor::<ClientFrame>(bytes), Ok(ClientFrame::Cancel { id: c }) if c == id)
780}
781
782fn millis(d: Duration) -> u64 {
783 d.as_millis().min(u64::MAX as u128) as u64
784}
785
786enum Waited {
787 Go(super::queue::Permit),
788 Gone,
790}
791
792async fn wait_turn(ch: &mut Channel, id: &str, admission: &Admission, priority: Priority) -> Result<Waited, RemoteError> {
794 let mut ticket = match admission.enter(priority) {
795 Ok(t) => t,
796 Err(error) => {
797 ch.send_cbor(&ServerFrame::Failed { id: id.to_string(), error }).await?;
798 return Ok(Waited::Gone);
799 }
800 };
801 let mut last = None;
802 loop {
803 tokio::select! {
804 turn = ticket.turn(last, QUEUE_KEEPALIVE) => match turn {
805 Turn::Go(permit) => return Ok(Waited::Go(permit)),
806 Turn::Waiting(position) => {
807 last = Some(position);
808 ch.send_cbor(&ServerFrame::Queued { id: id.to_string(), position }).await?;
809 }
810 },
811 m = ch.rx.recv() => match m {
812 Ok(Some(bytes)) if is_cancel(&bytes, id) => {
813 ch.send_cbor(&ServerFrame::Cancelled { id: id.to_string() }).await?;
814 return Ok(Waited::Gone);
815 }
816 Ok(Some(_)) => {}
817 Ok(None) | Err(_) => return Ok(Waited::Gone),
818 },
819 }
820 }
821}
822
823pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission) -> Result<(), RemoteError> {
828 match ch.recv_cbor::<ClientFrame>().await? {
829 Some(ClientFrame::Infer(request)) => serve_infer(ch, caller, host, admission, request).await,
830 Some(ClientFrame::Embed(request)) => serve_embed(ch, caller, host, admission, request).await,
831 Some(ClientFrame::Cancel { .. }) | None => Ok(()),
832 }
833}
834
835async fn serve_infer(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission, mut request: Request) -> Result<(), RemoteError> {
836 let started = Instant::now();
837 let id = request.id.clone();
838 let caller = caller.presenting(request.cert.take());
839 let checked = host.authorize(&caller).and_then(|()| {
840 if matches!(request.input, Input::Prompt(_)) && !request.tools.is_empty() {
841 return Err(RemoteError::BadRequest { message: "a raw prompt takes no tools".into() });
842 }
843 if request.raw && matches!(request.input, Input::Context(_)) {
844 return Err(RemoteError::BadRequest { message: "raw mode takes assembled messages, not a context_ref".into() });
845 }
846 if request.assistant_prefix.as_ref().is_some_and(|p| !p.is_consistent()) {
847 return Err(RemoteError::BadRequest { message: "assistant_prefix lengths do not match its text".into() });
848 }
849 host.open_request(&caller, &request)
850 });
851 let backend = match checked {
852 Ok(b) => b,
853 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
854 };
855 let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
856 Waited::Go(p) => p,
857 Waited::Gone => return Ok(()),
858 };
859 let queued = started.elapsed();
860 let resume = backend.resumes();
861 let prefix = request.assistant_prefix.clone().filter(|_| resume);
862 if !resume {
863 request.assistant_prefix = None;
864 }
865 let (text_at, reasoning_at) = prefix.as_ref().map(|p| (p.len, p.reasoning_len)).unwrap_or((0, 0));
866 ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: request.attempt, resume }).await?;
867 let accepted = Instant::now();
868
869 let (out, mut pieces) = Output::channel();
870 let cancel = CancelToken::new();
871 let mut framer =
872 Framer { id: id.clone(), text_at, reasoning_at, calls: 0, accepted, first_token: None, early_meta: request.early_meta, meta: None };
873 let mut run = pin!(backend.infer(&request, &out, &cancel));
874 let mut asker_open = true;
875 let mut send_failed = false;
876 let result = loop {
877 tokio::select! {
878 r = &mut run => break r,
879 Some(p) = pieces.recv() => {
880 let Some(f) = framer.frame(p) else { continue };
881 if !send_failed && ch.send_cbor(&f).await.is_err() {
882 send_failed = true;
883 cancel.cancel();
884 }
885 }
886 m = ch.rx.recv(), if asker_open => match m {
887 Ok(Some(bytes)) => {
888 if is_cancel(&bytes, &id) {
889 cancel.cancel();
890 }
891 }
892 Ok(None) | Err(_) => {
893 asker_open = false;
894 cancel.cancel();
895 }
896 },
897 }
898 };
899 if send_failed || !asker_open {
900 return Ok(());
901 }
902 while let Ok(p) = pieces.try_recv() {
903 if let Some(f) = framer.frame(p) {
904 ch.send_cbor(&f).await?;
905 }
906 }
907 let reply = match result {
908 Ok(mut finish) => {
909 let meta = &mut finish.meta;
910 if let Some(early) = framer.meta.take() {
911 meta.cache_hit |= early.cache_hit;
912 if meta.served_by.is_none() {
913 meta.served_by = early.served_by;
914 }
915 if meta.revision.is_none() {
916 meta.revision = early.revision;
917 }
918 if meta.standin.is_none() {
919 meta.standin = early.standin;
920 }
921 }
922 meta.served_by.get_or_insert_with(|| backend.name());
923 if let Some(p) = &prefix {
924 meta.resumed_from = Some(p.len);
925 }
926 meta.timings.queued_ms = millis(queued);
927 meta.timings.first_token_ms = framer.first_token.map(millis);
928 meta.timings.total_ms = millis(started.elapsed());
929 ServerFrame::Done { id, finish }
930 }
931 Err(_) if cancel.is_cancelled() => ServerFrame::Cancelled { id },
932 Err(error) => ServerFrame::Failed { id, error },
933 };
934 ch.send_cbor(&reply).await
935}
936
937struct Framer {
939 id: String,
940 text_at: u64,
941 reasoning_at: u64,
942 calls: u32,
943 accepted: Instant,
944 first_token: Option<Duration>,
945 early_meta: bool,
947 meta: Option<Meta>,
949}
950
951impl Framer {
952 fn frame(&mut self, p: Piece) -> Option<ServerFrame> {
953 let id = self.id.clone();
954 Some(match p {
955 Piece::Text(text) => {
956 self.first_token.get_or_insert_with(|| self.accepted.elapsed());
957 let offset = self.text_at;
958 self.text_at += chars(&text);
959 ServerFrame::Delta { id, offset, text }
960 }
961 Piece::Reasoning(text) => {
962 self.first_token.get_or_insert_with(|| self.accepted.elapsed());
963 let offset = self.reasoning_at;
964 self.reasoning_at += chars(&text);
965 ServerFrame::Reasoning { id, offset, text }
966 }
967 Piece::ToolCall(call) => {
968 self.calls += 1;
969 ServerFrame::ToolCall { id, index: self.calls - 1, call }
970 }
971 Piece::Usage(usage) => ServerFrame::Usage { id, usage },
972 Piece::Meta(meta) => {
973 self.meta = Some(meta.clone());
974 if !self.early_meta {
975 return None;
976 }
977 ServerFrame::Meta { id, meta }
978 }
979 })
980 }
981}
982
983async fn serve_embed(
984 mut ch: Channel,
985 caller: Caller,
986 host: &dyn InferHost,
987 admission: &Admission,
988 mut request: EmbedRequest,
989) -> Result<(), RemoteError> {
990 let started = Instant::now();
991 let id = request.id.clone();
992 let caller = caller.presenting(request.cert.take());
993 let backend = match host.authorize(&caller).and_then(|()| host.open_embed(&caller, request.model.as_deref())) {
994 Ok(b) => b,
995 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
996 };
997 let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
998 Waited::Go(p) => p,
999 Waited::Gone => return Ok(()),
1000 };
1001 let queued = started.elapsed();
1002 ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1003 let cancel = CancelToken::new();
1004 let mut tokens: Option<u64> = None;
1005 for (index, input) in request.inputs.iter().enumerate() {
1006 let vector = tokio::select! {
1007 v = backend.embed_counted(input, &cancel) => v,
1008 m = async { loop {
1009 match ch.rx.recv().await {
1010 Ok(Some(bytes)) if is_cancel(&bytes, &id) => return true,
1011 Ok(Some(_)) => {}
1012 Ok(None) | Err(_) => return false,
1013 }
1014 } } => {
1015 cancel.cancel();
1016 return if m { ch.send_cbor(&ServerFrame::Cancelled { id }).await } else { Ok(()) };
1017 }
1018 };
1019 match vector {
1020 Ok((v, n)) => {
1021 if let Some(n) = n {
1022 *tokens.get_or_insert(0) += n;
1023 }
1024 ch.send_cbor(&ServerFrame::Embedding { id: id.clone(), index: index as u32, vector: f32_bytes(&v) }).await?
1025 }
1026 Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1027 }
1028 }
1029 let mut finish = Finish::new("stop");
1030 finish.usage = tokens.map(|n| Usage::new(n, 0));
1031 finish.meta.served_by = Some(backend.name());
1032 finish.meta.timings.queued_ms = millis(queued);
1033 finish.meta.timings.total_ms = millis(started.elapsed());
1034 ch.send_cbor(&ServerFrame::Done { id, finish }).await
1035}