1use std::sync::{Arc, Mutex};
25
26use crate::{
27 completion::{CompletionRequest, ModelRef, UnsupportedOption},
28 driver::{DynModel, Sending, without_messages},
29 effect::{
30 Answered, EffectFamily, EffectId, EffectKind, EmbedInputs, EmbedModality, EmbedOutputs,
31 FamilyDescriptor, HandlerDescriptor, HandlerKey, RetrieveQuery, RetrievedDocuments,
32 ToolEmbeddingDescriptor,
33 },
34 error::{ErrorKind, ErrorReport},
35 operation::{Completion, Embedding, Rerank},
36 providers::registry::ProviderId,
37 tool::{Tool, ToolEmbedding, ToolExecutionError},
38 vector_store::{VectorStoreError, VectorStoreIndex, request::DynamicSearchFilter},
39 wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync},
40 wire::Operation,
41};
42
43use super::{Dispatch, Reply, Serve};
44use crate::effect::family;
45
46fn wrong_family(handler: EffectFamily, kind: &EffectKind) -> ErrorReport {
47 ErrorReport::new(
48 ErrorKind::HandlerUnavailable,
49 format!(
50 "a {handler} handler cannot serve a `{}` effect",
51 kind.name()
52 ),
53 )
54}
55
56pub struct ModelAdapter<Op: Operation> {
60 label: ModelRef,
61 model: DynModel<Op>,
62 checked: Mutex<Option<(CompletionRequest, Vec<UnsupportedOption>)>>,
65}
66
67impl<Op: Operation> ModelAdapter<Op> {
68 pub fn new(label: impl Into<ModelRef>, model: impl Into<DynModel<Op>>) -> Self {
70 Self {
71 label: label.into(),
72 model: model.into(),
73 checked: Mutex::new(None),
74 }
75 }
76
77 fn sending(&self, handler: HandlerKey, dispatch: &Dispatch) -> Sending {
80 let mut extensions = http::Extensions::new();
81 extensions.insert(Serving {
82 effect: dispatch.id(),
83 handler,
84 provider: self.model.spec().map(|spec| spec.provider),
85 });
86 Sending { extensions }
87 }
88}
89
90#[derive(Clone, Debug, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct Serving {
113 pub effect: EffectId,
115 pub handler: HandlerKey,
117 pub provider: Option<ProviderId>,
120}
121
122impl Serving {
123 pub fn new(effect: EffectId, handler: HandlerKey) -> Self {
126 Self {
127 effect,
128 handler,
129 provider: None,
130 }
131 }
132}
133
134impl Serve for ModelAdapter<Completion> {
137 type Family = family::Completion;
138
139 fn descriptor(&self) -> HandlerDescriptor {
140 HandlerDescriptor {
141 key: crate::effect::model_key(self.label.as_str()),
142 family: FamilyDescriptor::Completion {
143 model: self.label.clone(),
144 capabilities: self.model.capabilities().completion,
145 },
146 layers: Vec::new(),
147 }
148 }
149
150 fn check(&self, kind: &EffectKind) -> Vec<UnsupportedOption> {
158 let EffectKind::Completion { request, .. } = kind else {
159 return Vec::new();
160 };
161 let memo = request.provider_options.is_empty();
162 let checked = without_messages(request);
163 if memo
164 && let Ok(last) = self.checked.lock()
165 && let Some((last, refused)) = last.as_ref()
166 && *last == checked
167 {
168 return refused.clone();
169 }
170 let refused = match self.model.check(request) {
171 Err(crate::completion::CheckError::Unsupported(refused)) => refused,
172 Ok(()) | Err(crate::completion::CheckError::Invalid(_)) => Vec::new(),
173 };
174 if memo && let Ok(mut last) = self.checked.lock() {
175 *last = Some((checked, refused.clone()));
176 }
177 refused
178 }
179
180 async fn serve(&self, kind: EffectKind, dispatch: Dispatch) -> Reply {
181 let model = &self.model;
182 let sending = self.sending(crate::effect::model_key(self.label.as_str()), &dispatch);
183 match kind {
184 EffectKind::Completion {
185 request,
186 stream: false,
187 } => {
188 let result = model.finished(Arc::unwrap_or_clone(request), sending).await;
189 let result = result.map(Arc::new);
190 Reply::Outcome(result.map(Answered::Completion).map_err(ErrorReport::from))
191 }
192 EffectKind::Completion {
193 request,
194 stream: true,
195 } => match model.opened(Arc::unwrap_or_clone(request), sending) {
196 Ok(stream) => Reply::Stream(stream.into_relay()),
197 Err(error) => Reply::Outcome(Err(ErrorReport::from(error))),
198 },
199 other @ (EffectKind::ToolCall { .. }
200 | EffectKind::Embed { .. }
201 | EffectKind::Retrieve { .. }
202 | EffectKind::Rerank { .. }
203 | EffectKind::Custom { .. }) => {
204 Reply::Outcome(Err(wrong_family(EffectFamily::Completion, &other)))
205 }
206 }
207 }
208}
209
210impl Serve for ModelAdapter<Embedding> {
212 type Family = family::Embed;
213
214 fn descriptor(&self) -> HandlerDescriptor {
215 let capabilities = self.model.capabilities();
216 HandlerDescriptor {
217 key: crate::effect::embed_key(self.label.as_str()),
218 family: FamilyDescriptor::Embed {
219 model: self.label.to_string(),
220 dims: (capabilities.ndims != 0).then_some(capabilities.ndims),
221 max_documents: capabilities.max_documents,
222 modality: EmbedModality::Text,
223 },
224 layers: Vec::new(),
225 }
226 }
227
228 async fn serve(&self, kind: EffectKind, dispatch: Dispatch) -> Reply {
229 let model = &self.model;
230 let sending = self.sending(crate::effect::embed_key(self.label.as_str()), &dispatch);
231 match kind {
232 EffectKind::Embed {
233 inputs: EmbedInputs::Texts(texts),
234 } => Reply::Outcome(
235 model
236 .finished(texts, sending)
237 .await
238 .map(|response| Answered::Embeddings(EmbedOutputs::Texts(response)))
239 .map_err(ErrorReport::from),
240 ),
241 EffectKind::Embed {
242 inputs: EmbedInputs::Images(_),
243 } => Reply::Outcome(Err(ErrorReport::new(
244 ErrorKind::HandlerUnavailable,
245 "a text embedding handler cannot embed images",
246 ))),
247 other @ (EffectKind::Completion { .. }
248 | EffectKind::ToolCall { .. }
249 | EffectKind::Retrieve { .. }
250 | EffectKind::Rerank { .. }
251 | EffectKind::Custom { .. }) => {
252 Reply::Outcome(Err(wrong_family(EffectFamily::Embed, &other)))
253 }
254 }
255 }
256}
257
258impl Serve for ModelAdapter<Rerank> {
260 type Family = family::Rerank;
261
262 fn descriptor(&self) -> HandlerDescriptor {
263 HandlerDescriptor {
264 key: crate::effect::rerank_key(self.label.as_str()),
265 family: FamilyDescriptor::Rerank {
266 model: self.label.to_string(),
267 max_documents: self.model.capabilities().max_documents,
268 },
269 layers: Vec::new(),
270 }
271 }
272
273 async fn serve(&self, kind: EffectKind, dispatch: Dispatch) -> Reply {
274 let model = &self.model;
275 let sending = self.sending(crate::effect::rerank_key(self.label.as_str()), &dispatch);
276 match kind {
277 EffectKind::Rerank { request } => Reply::Outcome(
278 model
279 .finished(request, sending)
280 .await
281 .map(Answered::Reranked)
282 .map_err(ErrorReport::from),
283 ),
284 other @ (EffectKind::Completion { .. }
285 | EffectKind::ToolCall { .. }
286 | EffectKind::Embed { .. }
287 | EffectKind::Retrieve { .. }
288 | EffectKind::Custom { .. }) => {
289 Reply::Outcome(Err(wrong_family(EffectFamily::Rerank, &other)))
290 }
291 }
292 }
293}
294
295pub(crate) async fn call_tool<A, O>(
305 kind: EffectKind,
306 dispatch: Dispatch,
307 bound: Option<&str>,
308 call: impl AsyncFnOnce(&mut crate::tool::ToolContext, A) -> Result<O, ToolExecutionError>,
309) -> Reply
310where
311 A: serde::de::DeserializeOwned,
312 O: crate::tool::IntoToolOutput,
313{
314 let args = match (kind, bound) {
315 (EffectKind::ToolCall { name, .. }, Some(bound)) if bound != name => {
316 return Reply::Outcome(Err(ErrorReport::new(
317 ErrorKind::Internal,
318 format!("tool handler `{bound}` asked to run `{name}`"),
319 )));
320 }
321 (EffectKind::ToolCall { args, .. }, _) => args,
322 (
323 other @ (EffectKind::Completion { .. }
324 | EffectKind::Embed { .. }
325 | EffectKind::Retrieve { .. }
326 | EffectKind::Rerank { .. }
327 | EffectKind::Custom { .. }),
328 _,
329 ) => return Reply::Outcome(Err(wrong_family(EffectFamily::Tool, &other))),
330 };
331 let result = run_tool(&args, &dispatch, call).await;
332 Reply::Outcome(Ok(Answered::ToolResult { result }))
333}
334
335pub(crate) async fn run_tool<A, O>(
339 args: &str,
340 dispatch: &Dispatch,
341 call: impl AsyncFnOnce(&mut crate::tool::ToolContext, A) -> Result<O, ToolExecutionError>,
342) -> crate::tool::ToolResult
343where
344 A: serde::de::DeserializeOwned,
345 O: crate::tool::IntoToolOutput,
346{
347 let mut context = dispatch
348 .scope::<crate::tool::ToolContext>()
349 .map(|inbound| inbound.for_dispatch())
350 .unwrap_or_default()
351 .with_scopes(dispatch.scopes());
352 let result = run_in(args, &mut context, call).await;
353 if let Some(published) = dispatch.scope::<crate::tool::PublishedContext>() {
354 published.publish(context);
355 }
356 result
357}
358
359pub(crate) async fn run_direct<A, O>(
363 context: &mut crate::tool::ToolContext,
364 args: serde_json::Value,
365 call: impl AsyncFnOnce(&mut crate::tool::ToolContext, A) -> Result<O, ToolExecutionError>,
366) -> Result<crate::tool::ToolOutput, ToolExecutionError>
367where
368 A: serde::de::DeserializeOwned,
369 O: crate::tool::IntoToolOutput,
370{
371 let mut dispatched = context.for_dispatch();
372 let result = run_in(&args.to_string(), &mut dispatched, call).await;
373 context.accept_dispatch_result(dispatched);
374 result.into_result()
375}
376
377async fn run_in<A, O>(
380 args: &str,
381 context: &mut crate::tool::ToolContext,
382 call: impl AsyncFnOnce(&mut crate::tool::ToolContext, A) -> Result<O, ToolExecutionError>,
383) -> crate::tool::ToolResult
384where
385 A: serde::de::DeserializeOwned,
386 O: crate::tool::IntoToolOutput,
387{
388 match crate::tool::contextual::parse_tool_args::<A>(args) {
389 Ok(args) => crate::tool::contextual::tool_result_from(call(context, args).await),
390 Err(error) => crate::tool::ToolResult::failed(error),
391 }
392}
393
394pub struct ToolAdapter<T> {
396 tool: T,
397 embedding: Option<ToolEmbeddingDescriptor>,
398}
399
400impl<T: Tool> ToolAdapter<T> {
401 pub fn new(tool: T) -> Self {
403 Self {
404 tool,
405 embedding: None,
406 }
407 }
408
409 pub fn retrievable(tool: T) -> Result<Self, serde_json::Error>
412 where
413 T: ToolEmbedding,
414 {
415 let embedding = ToolEmbeddingDescriptor {
416 context: serde_json::to_value(tool.context())?,
417 embedding_docs: tool.embedding_docs(),
418 };
419 Ok(Self {
420 tool,
421 embedding: Some(embedding),
422 })
423 }
424
425 pub fn tool(&self) -> &T {
427 &self.tool
428 }
429
430 pub fn embedding(&self) -> Option<&ToolEmbeddingDescriptor> {
432 self.embedding.as_ref()
433 }
434
435 pub async fn run(
440 &self,
441 args: serde_json::Value,
442 ) -> Result<crate::tool::ToolOutput, ToolExecutionError> {
443 self.run_with(&mut crate::tool::ToolContext::new(), args)
444 .await
445 }
446
447 pub async fn run_with(
492 &self,
493 context: &mut crate::tool::ToolContext,
494 args: serde_json::Value,
495 ) -> Result<crate::tool::ToolOutput, ToolExecutionError> {
496 run_direct(context, args, async |context, args| {
497 self.call(context, args).await
498 })
499 .await
500 }
501
502 async fn call(
504 &self,
505 context: &mut crate::tool::ToolContext,
506 args: T::Args,
507 ) -> Result<T::Output, ToolExecutionError> {
508 self.tool
509 .call(context, args)
510 .await
511 .map_err(|error| self.tool.map_error(error))
512 }
513}
514
515impl<T> Serve for ToolAdapter<T>
516where
517 T: Tool + 'static,
518{
519 type Family = family::Tool;
520
521 fn descriptor(&self) -> HandlerDescriptor {
522 HandlerDescriptor {
523 key: crate::effect::tool_key(T::NAME),
524 family: FamilyDescriptor::Tool {
525 name: T::NAME.to_owned(),
526 description: self.tool.description(),
527 parameters: self.tool.parameters(),
528 embedding: self.embedding.clone(),
529 },
530 layers: Vec::new(),
531 }
532 }
533
534 fn key(&self) -> HandlerKey {
535 crate::effect::tool_key(T::NAME)
536 }
537
538 fn footprint(&self, kind: &EffectKind) -> Option<crate::tool::Touches> {
539 match kind {
540 EffectKind::ToolCall { name, args } if name == T::NAME => {
541 let args = crate::tool::contextual::parse_tool_args::<T::Args>(args).ok()?;
542 Some(self.tool.footprint(&args))
543 }
544 _ => None,
545 }
546 }
547
548 async fn serve(&self, kind: EffectKind, dispatch: Dispatch) -> Reply {
549 call_tool(kind, dispatch, Some(T::NAME), async |context, args| {
550 self.call(context, args).await
551 })
552 .await
553 }
554}
555
556pub trait ToolCallback:
559 for<'a> Fn(
560 &'a mut crate::tool::ToolContext,
561 serde_json::Value,
562 ) -> WasmBoxedFuture<
563 'a,
564 Result<crate::tool::ToolOutput, crate::tool::ToolExecutionError>,
565 > + WasmCompatSend
566 + WasmCompatSync
567{
568}
569
570impl<F> ToolCallback for F where
571 F: for<'a> Fn(
572 &'a mut crate::tool::ToolContext,
573 serde_json::Value,
574 ) -> WasmBoxedFuture<
575 'a,
576 Result<crate::tool::ToolOutput, crate::tool::ToolExecutionError>,
577 > + WasmCompatSend
578 + WasmCompatSync
579{
580}
581
582pub struct RetrieveAdapter<I> {
586 index: I,
587 label: Option<String>,
588}
589
590impl<I> RetrieveAdapter<I> {
591 pub fn new(index: I) -> Self {
593 Self { index, label: None }
594 }
595
596 pub fn labelled(label: impl Into<String>, index: I) -> Self {
600 Self {
601 index,
602 label: Some(label.into()),
603 }
604 }
605
606 pub fn index(&self) -> &I {
608 &self.index
609 }
610}
611
612impl<I, F> Serve for RetrieveAdapter<I>
613where
614 I: VectorStoreIndex<Filter = F> + 'static,
615 F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
616{
617 type Family = family::Retrieve;
618
619 fn descriptor(&self) -> HandlerDescriptor {
620 HandlerDescriptor {
621 key: self
622 .label
623 .as_deref()
624 .map_or_else(|| HandlerKey::from("retrieve"), crate::effect::retrieve_key),
625 family: FamilyDescriptor::Retrieve {},
626 layers: Vec::new(),
627 }
628 }
629
630 async fn serve(&self, kind: EffectKind, _dispatch: Dispatch) -> Reply {
631 match kind {
632 EffectKind::Retrieve { query } => {
633 let ids = matches!(query, RetrieveQuery::TopNIds { .. });
634 let (RetrieveQuery::TopN { req } | RetrieveQuery::TopNIds { req }) = query;
635 let outcome = match req.try_map_filter(F::from_dynamic_filter) {
636 Ok(req) if ids => self.index.top_n_ids(req).await.map(|results| {
637 RetrievedDocuments::Ids(
638 results
639 .into_iter()
640 .map(|result| (result.score, result.id))
641 .collect(),
642 )
643 }),
644 Ok(req) => self
645 .index
646 .top_n::<serde_json::Value>(req)
647 .await
648 .map(|results| {
649 RetrievedDocuments::Scored(
650 results
651 .into_iter()
652 .map(|result| {
653 (
654 result.score,
655 result.id,
656 F::normalize_dynamic_document(result.document),
657 )
658 })
659 .collect(),
660 )
661 }),
662 Err(error) => Err(VectorStoreError::from(error)),
663 };
664 Reply::Outcome(outcome.map(Answered::Documents).map_err(ErrorReport::from))
665 }
666 other @ (EffectKind::Completion { .. }
667 | EffectKind::ToolCall { .. }
668 | EffectKind::Embed { .. }
669 | EffectKind::Rerank { .. }
670 | EffectKind::Custom { .. }) => {
671 Reply::Outcome(Err(wrong_family(EffectFamily::Retrieve, &other)))
672 }
673 }
674 }
675}