Skip to main content

rig_core/
operation.rs

1//! The operations a [`Wire`](crate::wire::Wire) can perform.
2//!
3//! Each operation declares its request, event, end and response types and
4//! the fold one reply goes through. [`Completion`] streams events; most
5//! others answer with one whole document, folded by [`Whole`]. Listings
6//! follow their cursors above the driver: each page is one call.
7//!
8//! ```
9//! use rig_core::operation::{Completion, Embedding};
10//! use rig_core::wire::Operation;
11//!
12//! fn streams<Op: Operation>() {}
13//! streams::<Completion>();
14//! streams::<Embedding>();
15//! ```
16
17use crate::error::ProviderError;
18use crate::wire::{Fold, Operation, Reply};
19
20pub(crate) mod completion;
21mod listing;
22mod modality;
23mod verify;
24
25pub use completion::{Block, CallFragment, Completion, Finish, ReplyFold, merge};
26pub use listing::{ModelListing, ModelPage};
27pub use modality::{
28    AudioGeneration, Embedding, ImageEmbedding, ImageGeneration, Rerank, RerankRequest,
29    Transcription,
30};
31pub use verify::{Verify, VerifyDecoder};
32
33/// The fold of an operation whose reply is one whole answer: it has no
34/// events, and the provider's end is the response. The stamp writes what
35/// the driver learned about the reply onto it.
36///
37/// ```
38/// use std::convert::Infallible;
39/// use rig_core::operation::Whole;
40/// use rig_core::wire::{Call, Free, Operation};
41///
42/// struct Echo;
43///
44/// impl Operation for Echo {
45///     type Request = String;
46///     type Event = Infallible;
47///     type End = String;
48///     type Response = String;
49///     type Fold = Whole<Self>;
50///     type Emit = Free;
51///
52///     fn fold(_request: &String, _call: &mut Call<'_>) -> Whole<Self> {
53///         Whole::<Self>::stamping(|response, reply| response.push_str(&reply.provider))
54///     }
55/// }
56/// ```
57pub struct Whole<Op: Operation> {
58    stamp: fn(&mut Op::Response, &Reply),
59}
60
61impl<Op: Operation> Whole<Op> {
62    /// A fold that stamps nothing.
63    pub fn new() -> Self {
64        Self::stamping(|_, _| {})
65    }
66
67    /// A fold that writes what the driver learned about the reply onto the
68    /// response with `stamp`.
69    pub fn stamping(stamp: fn(&mut Op::Response, &Reply)) -> Self {
70        Self { stamp }
71    }
72}
73
74impl<Op: Operation> Default for Whole<Op> {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80impl<Op> Fold<Op> for Whole<Op>
81where
82    Op: Operation<Event = std::convert::Infallible>,
83    Op::End: Into<Op::Response>,
84{
85    fn absorb(&mut self, event: &std::convert::Infallible) -> Result<(), ProviderError> {
86        match *event {}
87    }
88
89    fn finish(self, end: Op::End, reply: Reply) -> Result<Op::Response, ProviderError> {
90        let mut response = end.into();
91        (self.stamp)(&mut response, &reply);
92        Ok(response)
93    }
94}