rig/pipeline/mod.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
//! This module defines a flexible pipeline API for defining a sequence of operations that
//! may or may not use AI components (e.g.: semantic search, LLMs prompting, etc).
//!
//! The pipeline API was inspired by general orchestration pipelines such as Airflow, Dagster and Prefect,
//! but implemented with idiomatic Rust patterns and providing some AI-specific ops out-of-the-box along
//! general combinators.
//!
//! Pipelines are made up of one or more operations, or "ops", each of which must implement the [Op] trait.
//! The [Op] trait requires the implementation of only one method: `call`, which takes an input
//! and returns an output. The trait provides a wide range of combinators for chaining operations together.
//!
//! One can think of a pipeline as a DAG (Directed Acyclic Graph) where each node is an operation and
//! the edges represent the data flow between operations. When invoking the pipeline on some input,
//! the input is passed to the root node of the DAG (i.e.: the first op defined in the pipeline).
//! The output of each op is then passed to the next op in the pipeline until the output reaches the
//! leaf node (i.e.: the last op defined in the pipeline). The output of the leaf node is then returned
//! as the result of the pipeline.
//!
//! ## Basic Example
//! For example, the pipeline below takes a tuple of two integers, adds them together and then formats
//! the result as a string using the [map](Op::map) combinator method, which applies a simple function
//! op to the output of the previous op:
//! ```rust
//! use rig::pipeline::{self, Op};
//!
//! let pipeline = pipeline::new()
//! // op1: add two numbers
//! .map(|(x, y)| x + y)
//! // op2: format result
//! .map(|z| format!("Result: {z}!"));
//!
//! let result = pipeline.call((1, 2)).await;
//! assert_eq!(result, "Result: 3!");
//! ```
//!
//! This pipeline can be visualized as the following DAG:
//! ```text
//! ┌─────────┐ ┌─────────┐
//! Input───►│ op1 ├──►│ op2 ├──►Output
//! └─────────┘ └─────────┘
//! ```
//!
//! ## Parallel Operations
//! The pipeline API also provides a [parallel!](crate::parallel!) and macro for running operations in parallel.
//! The macro takes a list of ops and turns them into a single op that will duplicate the input
//! and run each op in concurrently. The results of each op are then collected and returned as a tuple.
//!
//! For example, the pipeline below runs two operations concurrently:
//! ```rust
//! use rig::{pipeline::{self, Op, map}, parallel};
//!
//! let pipeline = pipeline::new()
//! .chain(parallel!(
//! // op1: add 1 to input
//! map(|x| x + 1),
//! // op2: subtract 1 from input
//! map(|x| x - 1),
//! ))
//! // op3: format results
//! .map(|(a, b)| format!("Results: {a}, {b}"));
//!
//! let result = pipeline.call(1).await;
//! assert_eq!(result, "Result: 2, 0");
//! ```
//!
//! Notes:
//! - The [chain](Op::chain) method is similar to the [map](Op::map) method but it allows
//! for chaining arbitrary operations, as long as they implement the [Op] trait.
//! - [map] is a function that initializes a standalone [Map](self::op::Map) op without an existing pipeline/op.
//!
//! The pipeline above can be visualized as the following DAG:
//! ```text
//! Input
//! │
//! ┌──────┴──────┐
//! ▼ ▼
//! ┌─────────┐ ┌─────────┐
//! │ op1 │ │ op2 │
//! └────┬────┘ └────┬────┘
//! └──────┬──────┘
//! ▼
//! ┌─────────┐
//! │ op3 │
//! └────┬────┘
//! │
//! ▼
//! Output
//! ```
pub mod agent_ops;
pub mod op;
pub mod try_op;
#[macro_use]
pub mod parallel;
#[macro_use]
pub mod conditional;
use std::future::Future;
pub use op::{map, passthrough, then, Op};
pub use try_op::TryOp;
use crate::{completion, extractor::Extractor, vector_store};
pub struct PipelineBuilder<E> {
_error: std::marker::PhantomData<E>,
}
impl<E> PipelineBuilder<E> {
/// Add a function to the current pipeline
///
/// # Example
/// ```rust
/// use rig::pipeline::{self, Op};
///
/// let pipeline = pipeline::new()
/// .map(|(x, y)| x + y)
/// .map(|z| format!("Result: {z}!"));
///
/// let result = pipeline.call((1, 2)).await;
/// assert_eq!(result, "Result: 3!");
/// ```
pub fn map<F, Input, Output>(self, f: F) -> op::Map<F, Input>
where
F: Fn(Input) -> Output + Send + Sync,
Input: Send + Sync,
Output: Send + Sync,
Self: Sized,
{
op::Map::new(f)
}
/// Same as `map` but for asynchronous functions
///
/// # Example
/// ```rust
/// use rig::pipeline::{self, Op};
///
/// let pipeline = pipeline::new()
/// .then(|email: String| async move {
/// email.split('@').next().unwrap().to_string()
/// })
/// .then(|username: String| async move {
/// format!("Hello, {}!", username)
/// });
///
/// let result = pipeline.call("bob@gmail.com".to_string()).await;
/// assert_eq!(result, "Hello, bob!");
/// ```
pub fn then<F, Input, Fut>(self, f: F) -> op::Then<F, Input>
where
F: Fn(Input) -> Fut + Send + Sync,
Input: Send + Sync,
Fut: Future + Send + Sync,
Fut::Output: Send + Sync,
Self: Sized,
{
op::Then::new(f)
}
/// Add an arbitrary operation to the current pipeline.
///
/// # Example
/// ```rust
/// use rig::pipeline::{self, Op};
///
/// struct MyOp;
///
/// impl Op for MyOp {
/// type Input = i32;
/// type Output = i32;
///
/// async fn call(&self, input: Self::Input) -> Self::Output {
/// input + 1
/// }
/// }
///
/// let pipeline = pipeline::new()
/// .chain(MyOp);
///
/// let result = pipeline.call(1).await;
/// assert_eq!(result, 2);
/// ```
pub fn chain<T>(self, op: T) -> T
where
T: Op,
Self: Sized,
{
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::pipeline::{self, Op};
///
/// let pipeline = pipeline::new()
/// .lookup(index, 2)
/// .pipeline(|(query, docs): (_, Vec<String>)| async move {
/// format!("User query: {}\n\nTop documents:\n{}", query, docs.join("\n"))
/// });
///
/// let result = pipeline.call("What is a flurbo?".to_string()).await;
/// ```
pub fn lookup<I, Input, Output>(self, index: I, n: usize) -> agent_ops::Lookup<I, Input, Output>
where
I: vector_store::VectorStoreIndex,
Output: Send + Sync + for<'a> serde::Deserialize<'a>,
Input: Into<String> + Send + Sync,
// E: From<vector_store::VectorStoreError> + Send + Sync,
Self: Sized,
{
agent_ops::Lookup::new(index, n)
}
/// Add a prompt operation to the current pipeline/op. The prompt operation expects the
/// current pipeline to output a string. The prompt operation will use the string to prompt
/// the given `agent`, which must implements the [Prompt](completion::Prompt) trait and return
/// the response.
///
/// # Example
/// ```rust
/// use rig::pipeline::{self, Op};
///
/// let agent = &openai_client.agent("gpt-4").build();
///
/// let pipeline = pipeline::new()
/// .map(|name| format!("Find funny nicknames for the following name: {name}!"))
/// .prompt(agent);
///
/// let result = pipeline.call("Alice".to_string()).await;
/// ```
pub fn prompt<P, Input>(self, agent: P) -> agent_ops::Prompt<P, Input>
where
P: completion::Prompt,
Input: Into<String> + Send + Sync,
// E: From<completion::PromptError> + Send + Sync,
Self: Sized,
{
agent_ops::Prompt::new(agent)
}
/// Add an extract operation to the current pipeline/op. The extract operation expects the
/// current pipeline to output a string. The extract operation will use the given `extractor`
/// to extract information from the string in the form of the type `T` and return it.
///
/// # Example
/// ```rust
/// use rig::pipeline::{self, Op};
///
/// #[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
/// struct Sentiment {
/// /// The sentiment score of the text (0.0 = negative, 1.0 = positive)
/// score: f64,
/// }
///
/// let extractor = &openai_client.extractor::<Sentiment>("gpt-4").build();
///
/// let pipeline = pipeline::new()
/// .map(|text| format!("Analyze the sentiment of the following text: {text}!"))
/// .extract(extractor);
///
/// let result: Sentiment = pipeline.call("I love ice cream!".to_string()).await?;
/// assert!(result.score > 0.5);
/// ```
pub fn extract<M, Input, Output>(
self,
extractor: Extractor<M, Output>,
) -> agent_ops::Extract<M, Input, Output>
where
M: completion::CompletionModel,
Output: schemars::JsonSchema + for<'a> serde::Deserialize<'a> + Send + Sync,
Input: Into<String> + Send + Sync,
{
agent_ops::Extract::new(extractor)
}
}
#[derive(Debug, thiserror::Error)]
pub enum ChainError {
#[error("Failed to prompt agent: {0}")]
PromptError(#[from] completion::PromptError),
#[error("Failed to lookup documents: {0}")]
LookupError(#[from] vector_store::VectorStoreError),
}
pub fn new() -> PipelineBuilder<ChainError> {
PipelineBuilder {
_error: std::marker::PhantomData,
}
}
pub fn with_error<E>() -> PipelineBuilder<E> {
PipelineBuilder {
_error: std::marker::PhantomData,
}
}
#[cfg(test)]
mod tests {
use super::*;
use agent_ops::tests::{Foo, MockIndex, MockModel};
use parallel::parallel;
#[tokio::test]
async fn test_prompt_pipeline() {
let model = MockModel;
let chain = super::new()
.map(|input| format!("User query: {}", input))
.prompt(model);
let result = chain
.call("What is a flurbo?")
.await
.expect("Failed to run chain");
assert_eq!(result, "Mock response: User query: What is a flurbo?");
}
#[tokio::test]
async fn test_prompt_pipeline_error() {
let model = MockModel;
let chain = super::with_error::<()>()
.map(|input| format!("User query: {}", input))
.prompt(model);
let result = chain
.try_call("What is a flurbo?")
.await
.expect("Failed to run chain");
assert_eq!(result, "Mock response: User query: What is a flurbo?");
}
#[tokio::test]
async fn test_lookup_pipeline() {
let index = MockIndex;
let chain = super::new()
.lookup::<_, _, Foo>(index, 1)
.map_ok(|docs| format!("Top documents:\n{}", docs[0].2.foo));
let result = chain
.try_call("What is a flurbo?")
.await
.expect("Failed to run chain");
assert_eq!(result, "Top documents:\nbar");
}
#[tokio::test]
async fn test_rag_pipeline() {
let index = MockIndex;
let chain = super::new()
.chain(parallel!(
passthrough(),
agent_ops::lookup::<_, _, Foo>(index, 1),
))
.map(|(query, maybe_docs)| match maybe_docs {
Ok(docs) => format!("User query: {}\n\nTop documents:\n{}", query, docs[0].2.foo),
Err(err) => format!("Error: {}", err),
})
.prompt(MockModel);
let result = chain
.call("What is a flurbo?")
.await
.expect("Failed to run chain");
assert_eq!(
result,
"Mock response: User query: What is a flurbo?\n\nTop documents:\nbar"
);
}
}