rig/pipeline/
op.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::future::Future;

#[allow(unused_imports)] // Needed since this is used in a macro rule
use futures::join;
use futures::stream;

// ================================================================
// Core Op trait
// ================================================================
pub trait Op: Send + Sync {
    type Input: Send + Sync;
    type Output: Send + Sync;

    fn call(&self, input: Self::Input) -> impl Future<Output = Self::Output> + Send;

    /// Execute the current pipeline with the given inputs. `n` is the number of concurrent
    /// inputs that will be processed concurrently.
    fn batch_call<I>(&self, n: usize, input: I) -> impl Future<Output = Vec<Self::Output>> + Send
    where
        I: IntoIterator<Item = Self::Input> + Send,
        I::IntoIter: Send,
        Self: Sized,
    {
        use futures::stream::StreamExt;

        async move {
            stream::iter(input)
                .map(|input| self.call(input))
                .buffered(n)
                .collect()
                .await
        }
    }

    /// Chain a function `f` to the current op.
    ///
    /// # Example
    /// ```rust
    /// use rig::pipeline::{self, Op};
    ///
    /// let chain = pipeline::new()
    ///    .map(|(x, y)| x + y)
    ///    .map(|z| format!("Result: {z}!"));
    ///
    /// let result = chain.call((1, 2)).await;
    /// assert_eq!(result, "Result: 3!");
    /// ```
    fn map<F, Input>(self, f: F) -> Sequential<Self, Map<F, Self::Output>>
    where
        F: Fn(Self::Output) -> Input + Send + Sync,
        Input: Send + Sync,
        Self: Sized,
    {
        Sequential::new(self, Map::new(f))
    }

    /// Same as `map` but for asynchronous functions
    ///
    /// # Example
    /// ```rust
    /// use rig::pipeline::{self, Op};
    ///
    /// let chain = pipeline::new()
    ///     .then(|email: String| async move {
    ///         email.split('@').next().unwrap().to_string()
    ///     })
    ///     .then(|username: String| async move {
    ///         format!("Hello, {}!", username)
    ///     });
    ///
    /// let result = chain.call("bob@gmail.com".to_string()).await;
    /// assert_eq!(result, "Hello, bob!");
    /// ```
    fn then<F, Fut>(self, f: F) -> Sequential<Self, Then<F, Fut::Output>>
    where
        F: Fn(Self::Output) -> Fut + Send + Sync,
        Fut: Future + Send + Sync,
        Fut::Output: Send + Sync,
        Self: Sized,
    {
        Sequential::new(self, Then::new(f))
    }

    /// Chain an arbitrary operation to the current op.
    ///
    /// # Example
    /// ```rust
    /// use rig::pipeline::{self, Op};
    ///
    /// struct AddOne;
    ///
    /// impl Op for AddOne {
    ///     type Input = i32;
    ///     type Output = i32;
    ///
    ///     async fn call(&self, input: Self::Input) -> Self::Output {
    ///         input + 1
    ///     }
    /// }
    ///
    /// let chain = pipeline::new()
    ///    .chain(AddOne);
    ///
    /// let result = chain.call(1).await;
    /// assert_eq!(result, 2);
    /// ```
    fn chain<T>(self, op: T) -> Sequential<Self, T>
    where
        T: Op<Input = Self::Output>,
        Self: Sized,
    {
        Sequential::new(self, op)
    }

    /// Chain a lookup operation to the current chain. The lookup operation expects the
    /// current chain to output a query string. The lookup operation will use the query to
    /// retrieve the top `n` documents from the index and return them with the query string.
    ///
    /// # Example
    /// ```rust
    /// use rig::chain::{self, Chain};
    ///
    /// let chain = chain::new()
    ///     .lookup(index, 2)
    ///     .chain(|(query, docs): (_, Vec<String>)| async move {
    ///         format!("User query: {}\n\nTop documents:\n{}", query, docs.join("\n"))
    ///     });
    ///
    /// let result = chain.call("What is a flurbo?".to_string()).await;
    /// ```
    fn lookup<I, Input>(
        self,
        index: I,
        n: usize,
    ) -> Sequential<Self, Lookup<I, Self::Output, Input>>
    where
        I: vector_store::VectorStoreIndex,
        Input: Send + Sync + for<'a> serde::Deserialize<'a>,
        Self::Output: Into<String>,
        Self: Sized,
    {
        Sequential::new(self, Lookup::new(index, n))
    }

    /// Chain a prompt operation to the current chain. The prompt operation expects the
    /// current chain to output a string. The prompt operation will use the string to prompt
    /// the given agent (or any other type that implements the `Prompt` trait) and return
    /// the response.
    ///
    /// # Example
    /// ```rust
    /// use rig::chain::{self, Chain};
    ///
    /// let agent = &openai_client.agent("gpt-4").build();
    ///
    /// let chain = chain::new()
    ///    .map(|name| format!("Find funny nicknames for the following name: {name}!"))
    ///    .prompt(agent);
    ///
    /// let result = chain.call("Alice".to_string()).await;
    /// ```
    fn prompt<P>(self, prompt: P) -> Sequential<Self, Prompt<P, Self::Output>>
    where
        P: completion::Prompt,
        Self::Output: Into<String>,
        Self: Sized,
    {
        Sequential::new(self, Prompt::new(prompt))
    }
}

impl<T: Op> Op for &T {
    type Input = T::Input;
    type Output = T::Output;

    #[inline]
    async fn call(&self, input: Self::Input) -> Self::Output {
        (*self).call(input).await
    }
}

// ================================================================
// Op combinators
// ================================================================
pub struct Sequential<Op1, Op2> {
    prev: Op1,
    op: Op2,
}

impl<Op1, Op2> Sequential<Op1, Op2> {
    pub(crate) fn new(prev: Op1, op: Op2) -> Self {
        Self { prev, op }
    }
}

impl<Op1, Op2> Op for Sequential<Op1, Op2>
where
    Op1: Op,
    Op2: Op<Input = Op1::Output>,
{
    type Input = Op1::Input;
    type Output = Op2::Output;

    #[inline]
    async fn call(&self, input: Self::Input) -> Self::Output {
        let prev = self.prev.call(input).await;
        self.op.call(prev).await
    }
}

use crate::{completion, vector_store};

use super::agent_ops::{Lookup, Prompt};

// ================================================================
// Core Op implementations
// ================================================================
pub struct Map<F, Input> {
    f: F,
    _t: std::marker::PhantomData<Input>,
}

impl<F, Input> Map<F, Input> {
    pub(crate) fn new(f: F) -> Self {
        Self {
            f,
            _t: std::marker::PhantomData,
        }
    }
}

impl<F, Input, Output> Op for Map<F, Input>
where
    F: Fn(Input) -> Output + Send + Sync,
    Input: Send + Sync,
    Output: Send + Sync,
{
    type Input = Input;
    type Output = Output;

    #[inline]
    async fn call(&self, input: Self::Input) -> Self::Output {
        (self.f)(input)
    }
}

pub fn map<F, Input, Output>(f: F) -> Map<F, Input>
where
    F: Fn(Input) -> Output + Send + Sync,
    Input: Send + Sync,
    Output: Send + Sync,
{
    Map::new(f)
}

pub struct Passthrough<T> {
    _t: std::marker::PhantomData<T>,
}

impl<T> Passthrough<T> {
    pub(crate) fn new() -> Self {
        Self {
            _t: std::marker::PhantomData,
        }
    }
}

impl<T> Op for Passthrough<T>
where
    T: Send + Sync,
{
    type Input = T;
    type Output = T;

    async fn call(&self, input: Self::Input) -> Self::Output {
        input
    }
}

pub fn passthrough<T>() -> Passthrough<T>
where
    T: Send + Sync,
{
    Passthrough::new()
}

pub struct Then<F, Input> {
    f: F,
    _t: std::marker::PhantomData<Input>,
}

impl<F, Input> Then<F, Input> {
    pub(crate) fn new(f: F) -> Self {
        Self {
            f,
            _t: std::marker::PhantomData,
        }
    }
}

impl<F, Input, Fut> Op for Then<F, Input>
where
    F: Fn(Input) -> Fut + Send + Sync,
    Input: Send + Sync,
    Fut: Future + Send,
    Fut::Output: Send + Sync,
{
    type Input = Input;
    type Output = Fut::Output;

    #[inline]
    async fn call(&self, input: Self::Input) -> Self::Output {
        (self.f)(input).await
    }
}

pub fn then<F, Input, Fut>(f: F) -> Then<F, Input>
where
    F: Fn(Input) -> Fut + Send + Sync,
    Input: Send + Sync,
    Fut: Future + Send,
    Fut::Output: Send + Sync,
{
    Then::new(f)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_sequential_constructor() {
        let op1 = map(|x: i32| x + 1);
        let op2 = map(|x: i32| x * 2);
        let op3 = map(|x: i32| x * 3);

        let pipeline = Sequential::new(Sequential::new(op1, op2), op3);

        let result = pipeline.call(1).await;
        assert_eq!(result, 12);
    }

    #[tokio::test]
    async fn test_sequential_chain() {
        let pipeline = map(|x: i32| x + 1)
            .map(|x| x * 2)
            .then(|x| async move { x * 3 });

        let result = pipeline.call(1).await;
        assert_eq!(result, 12);
    }

    // #[tokio::test]
    // async fn test_flatten() {
    //     let op = Parallel::new(
    //         Parallel::new(
    //             map(|x: i32| x + 1),
    //             map(|x: i32| x * 2),
    //         ),
    //         map(|x: i32| x * 3),
    //     );

    //     let pipeline = flatten::<_, (_, _, _)>(op);

    //     let result = pipeline.call(1).await;
    //     assert_eq!(result, (2, 2, 3));
    // }

    // #[tokio::test]
    // async fn test_parallel_macro() {
    //     let op1 = map(|x: i32| x + 1);
    //     let op2 = map(|x: i32| x * 3);
    //     let op3 = map(|x: i32| format!("{} is the number!", x));
    //     let op4 = map(|x: i32| x - 1);

    //     let pipeline = parallel!(op1, op2, op3, op4);

    //     let result = pipeline.call(1).await;
    //     assert_eq!(result, (2, 3, "1 is the number!".to_string(), 0));
    // }

    // #[tokio::test]
    // async fn test_parallel_join() {
    //     let op3 = map(|x: i32| format!("{} is the number!", x));

    //     let pipeline = Sequential::new(
    //         map(|x: i32| x + 1),
    //         then(|x| {
    //             // let op1 = map(|x: i32| x * 2);
    //             // let op2 = map(|x: i32| x * 3);
    //             let op3 = &op3;

    //             async move {
    //             join!(
    //                 (&map(|x: i32| x * 2)).call(x),
    //                 {
    //                     let op = map(|x: i32| x * 3);
    //                     op.call(x)
    //                 },
    //                 op3.call(x),
    //             )
    //         }}),
    //     );

    //     let result = pipeline.call(1).await;
    //     assert_eq!(result, (2, 3, "1 is the number!".to_string()));
    // }

    // #[test]
    // fn test_flatten() {
    //     let x = (1, (2, (3, 4)));
    //     let result = flatten!(0, 1, 1, 1, 1);
    //     assert_eq!(result, (1, 2, 3, 4));
    // }
}