Skip to main content

rig_core/serve/
adapters.rs

1//! Effect handlers adapting model, tool, and retrieval traits.
2//! Each adapter translates its effect family into trait calls and returns
3//! outcomes or streaming events.
4//!
5//! ```
6//! use rig_core::message::ToolName;
7//! use rig_core::serve::Serve;
8//! use rig_core::tool::{DynamicTool, ToolContext, ToolOutput};
9//! use rig_core::wasm_compat::WasmBoxedFuture;
10//!
11//! let handler = DynamicTool::new_with_context(
12//!     ToolName::new("echo")?,
13//!     "Echo the arguments",
14//!     serde_json::json!({ "type": "object" }),
15//!     |_context: &mut ToolContext, args: serde_json::Value| {
16//!         Box::pin(async move { Ok(ToolOutput::text(args.to_string())) })
17//!             as WasmBoxedFuture<'_, _>
18//!     },
19//! );
20//! assert_eq!(handler.descriptor().key, rig_core::effect::tool_key("echo"));
21//! # Ok::<(), rig_core::message::EmptyToolName>(())
22//! ```
23
24use 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
56/// A model as a handler under `label`. Completion, text-embedding and
57/// rerank models serve their effect families. The model is erased to its
58/// operation, so one adapter type serves every wire and transport.
59pub struct ModelAdapter<Op: Operation> {
60    label: ModelRef,
61    model: DynModel<Op>,
62    /// The last completion request [`Serve::check`] answered, as it was
63    /// checked (without its messages), and what the model refused of it.
64    checked: Mutex<Option<(CompletionRequest, Vec<UnsupportedOption>)>>,
65}
66
67impl<Op: Operation> ModelAdapter<Op> {
68    /// Wrap `model` under `label`.
69    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    /// How the model sends for `dispatch` under `handler`: its HTTP request
78    /// carries the [`Serving`].
79    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/// What an outgoing HTTP request to a model serves, in its
91/// [extensions](http::Request::extensions): the effect it answers and the
92/// handler it was dispatched to. A model adapter sets it on every request
93/// it sends, so a [transport wrapper](crate::catalog::Connector::wrap_http)
94/// can tell one model call's requests from another's and from those of no
95/// call, such as a model listing. The request's headers and body are the
96/// wrapper's to read, such as rig-cassette's traffic log, which records them.
97///
98/// ```
99/// use rig_core::http_client::Request;
100/// use rig_core::serve::Serving;
101///
102/// fn served(request: &Request<Vec<u8>>) -> Option<u64> {
103///     request
104///         .extensions()
105///         .get::<Serving>()
106///         .map(|serving| serving.effect.as_u64())
107/// }
108/// assert_eq!(served(&Request::new(Vec::new())), None);
109/// ```
110#[derive(Clone, Debug, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct Serving {
113    /// The effect the request answers, such as an ECS effect's id.
114    pub effect: EffectId,
115    /// The handler it was dispatched to, such as `model:openai/gpt-5`.
116    pub handler: HandlerKey,
117    /// The provider the model is reached through, when the model was
118    /// connected from a catalog spec.
119    pub provider: Option<ProviderId>,
120}
121
122impl Serving {
123    /// What a request answering `effect` through `handler` serves, reached
124    /// through no provider a catalog names.
125    pub fn new(effect: EffectId, handler: HandlerKey) -> Self {
126        Self {
127            effect,
128            handler,
129            provider: None,
130        }
131    }
132}
133
134/// Unary and streaming completions both route here; the descriptor carries
135/// the model's label and capability snapshot.
136impl 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    /// What the model's wire or the model leaves out of a completion's
151    /// request ([`DynModel::check`]); nothing for a request that cannot be
152    /// built at all, which sending reports, or for another family. The
153    /// check reads no messages but the system prompt, so the answer for
154    /// the last request is kept for the next that differs only in its
155    /// messages. A request with provider options is always checked: two
156    /// equal entries can still refuse differently.
157    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
210/// A text embedding model embeds texts and refuses images.
211impl 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
258/// A reranking model orders documents for a query.
259impl 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
295/// Serve one tool call: `args` parsed and handed to `call`, with the
296/// driver's inbound values from the dispatch's scope (`ToolContext`, as
297/// `for_dispatch`), else an empty context, and every scope of the dispatch
298/// attached, so the tool reaches its runtime by type for the length of the
299/// call. What the tool published goes back beside the dispatch when the
300/// driver asked for it ([`PublishedContext`](crate::tool::PublishedContext)
301/// in the dispatch's scope); the result carries data only. A call to
302/// another tool than `bound`, when given, is refused, so key routing never
303/// runs a different tool than the bound target.
304pub(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
335/// The body of [`call_tool`] once the call is known to be the tool's: `args`
336/// parsed and handed to `call` in the dispatch's context, and what the tool
337/// published handed back.
338pub(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
359/// A direct call of a tool, outside any dispatch: [`run_in`] over the
360/// caller's inbound values (as `for_dispatch`), with what the tool published
361/// handed back into `context` (as `accept_dispatch_result`).
362pub(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
377/// Every tool call's body: `args` parsed and handed to `call` in `context`,
378/// and its output converted.
379async 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
394/// A [`Tool`] as a handler, keyed by its name.
395pub struct ToolAdapter<T> {
396    tool: T,
397    embedding: Option<ToolEmbeddingDescriptor>,
398}
399
400impl<T: Tool> ToolAdapter<T> {
401    /// Wrap a static tool.
402    pub fn new(tool: T) -> Self {
403        Self {
404            tool,
405            embedding: None,
406        }
407    }
408
409    /// Wraps a tool with its embedding documents and serialized context.
410    /// Returns an error if context serialization fails.
411    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    /// The wrapped tool.
426    pub fn tool(&self) -> &T {
427        &self.tool
428    }
429
430    /// The retrieval descriptor of a [`Self::retrievable`] adapter.
431    pub fn embedding(&self) -> Option<&ToolEmbeddingDescriptor> {
432        self.embedding.as_ref()
433    }
434
435    /// Runs the tool on JSON `args` with an empty [`ToolContext`], as
436    /// [`Self::run_with`] does.
437    ///
438    /// [`ToolContext`]: crate::tool::ToolContext
439    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    /// Runs the tool on JSON `args` as a dispatch of its call runs it:
448    /// arguments parsed, errors normalized by [`Tool::map_error`], output
449    /// converted. The tool sees `context`'s inbound values, and what it
450    /// publishes with `insert_result` lands in `context`. No registry or
451    /// agent is involved.
452    ///
453    /// ```
454    /// use rig_core::{serve::adapters::ToolAdapter, tool::{ContextValue, Tool, ToolContext}};
455    /// use serde_json::json;
456    ///
457    /// #[derive(serde::Serialize, serde::Deserialize)]
458    /// struct Calls(u32);
459    /// impl ContextValue for Calls { const KEY: &'static str = "calls"; }
460    ///
461    /// struct Double;
462    ///
463    /// impl Tool for Double {
464    ///     const NAME: &'static str = "double";
465    ///     type Args = i64;
466    ///     type Output = i64;
467    ///     type Error = rig_core::tool::ToolContextError;
468    ///
469    ///     fn description(&self) -> String {
470    ///         "Doubles a number.".to_string()
471    ///     }
472    ///
473    ///     fn parameters(&self) -> serde_json::Value {
474    ///         json!({ "type": "integer" })
475    ///     }
476    ///
477    ///     async fn call(&self, context: &mut ToolContext, n: i64) -> Result<i64, Self::Error> {
478    ///         context.insert_result(Calls(1))?;
479    ///         Ok(n * 2)
480    ///     }
481    /// }
482    ///
483    /// let double = ToolAdapter::new(Double);
484    /// let mut context = ToolContext::new();
485    /// let output = futures::executor::block_on(double.run_with(&mut context, json!(21)))?;
486    /// assert_eq!(output.as_json(), Some(&json!(42)));
487    /// assert_eq!(context.result::<Calls>()?.map(|calls| calls.0), Some(1));
488    /// assert!(futures::executor::block_on(double.run(json!("21"))).is_err());
489    /// # Ok::<(), Box<dyn std::error::Error>>(())
490    /// ```
491    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    /// The tool's call with its error normalized, as every run makes it.
503    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
556/// Contextual tool callback accepting JSON arguments and returning canonical
557/// output or a tool execution error.
558pub 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
582/// A [`VectorStoreIndex`] as a handler. The index's filter type is rebuilt
583/// from the dynamic filter on the wire; documents come back as JSON, and the
584/// typed view deserialises on the client side.
585pub struct RetrieveAdapter<I> {
586    index: I,
587    label: Option<String>,
588}
589
590impl<I> RetrieveAdapter<I> {
591    /// Wrap `index` as an agent's own index, under the bare `retrieve` key.
592    pub fn new(index: I) -> Self {
593        Self { index, label: None }
594    }
595
596    /// Wrap `index` under `retrieve:<label>`, so a host can serve several
597    /// indexes in one table and dispatch to each by
598    /// [`retrieve_key`](crate::effect::retrieve_key).
599    pub fn labelled(label: impl Into<String>, index: I) -> Self {
600        Self {
601            index,
602            label: Some(label.into()),
603        }
604    }
605
606    /// The wrapped index.
607    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}