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