mod map_reduce;
mod map_rerank;
mod prompts;
mod refine;
mod retrieval_qa;
pub use map_reduce::MapReduceDocuments;
pub use map_rerank::{
MapRerankDocuments, RankedAnswer, MAP_RERANK_INTERMEDIATE_STEPS_KEY, MAP_RERANK_SCORE_KEY,
};
pub use refine::RefineDocuments;
pub use retrieval_qa::{RetrievalQA, RETRIEVAL_QA_SOURCE_DOCUMENTS_KEY};
pub(crate) use prompts::STUFF_QA_TEMPLATE;
use crate::{
chain::{LLMChain, LLMChainBuilder, StuffDocument},
language_models::llm::LLM,
prompt::{PromptTemplate, TemplateFormat},
};
fn llm_chain(llm: Box<dyn LLM>, template: &str, variables: &[&str]) -> LLMChain {
let prompt = PromptTemplate::new(
template.to_string(),
variables.iter().map(|v| v.to_string()).collect(),
TemplateFormat::Jinja2,
);
LLMChainBuilder::new()
.prompt(prompt)
.llm(llm)
.build()
.expect("prompt and llm are set")
}
impl StuffDocument {
pub fn load_summarize<L: Into<Box<dyn LLM>>>(llm: L) -> Self {
StuffDocument::new(llm_chain(
llm.into(),
prompts::SUMMARIZE_TEMPLATE,
&["context"],
))
}
}
impl RefineDocuments {
pub fn load_qa<L: Into<Box<dyn LLM>>>(llm: L) -> Self {
let llm = llm.into();
RefineDocuments::new(
llm_chain(
llm.clone_box(),
prompts::STUFF_QA_TEMPLATE,
&["context", "question"],
),
llm_chain(
llm,
prompts::REFINE_QA_TEMPLATE,
&["question", "existing_answer", "context"],
),
)
}
pub fn load_summarize<L: Into<Box<dyn LLM>>>(llm: L) -> Self {
let llm = llm.into();
RefineDocuments::new(
llm_chain(llm.clone_box(), prompts::SUMMARIZE_TEMPLATE, &["context"]),
llm_chain(
llm,
prompts::REFINE_SUMMARIZE_TEMPLATE,
&["existing_answer", "context"],
),
)
}
}
impl MapReduceDocuments {
pub fn load_qa<L: Into<Box<dyn LLM>>>(llm: L) -> Self {
let llm = llm.into();
MapReduceDocuments::new(
llm_chain(
llm.clone_box(),
prompts::MAP_REDUCE_MAP_QA_TEMPLATE,
&["context", "question"],
),
StuffDocument::new(llm_chain(
llm,
prompts::MAP_REDUCE_COMBINE_QA_TEMPLATE,
&["context", "question"],
)),
)
}
pub fn load_summarize<L: Into<Box<dyn LLM>>>(llm: L) -> Self {
let llm = llm.into();
MapReduceDocuments::new(
llm_chain(llm.clone_box(), prompts::SUMMARIZE_TEMPLATE, &["context"]),
StuffDocument::load_summarize(llm),
)
}
}
impl MapRerankDocuments {
pub fn load_qa<L: Into<Box<dyn LLM>>>(llm: L) -> Self {
MapRerankDocuments::new(llm_chain(
llm.into(),
prompts::MAP_RERANK_QA_TEMPLATE,
&["context", "question"],
))
}
}
#[cfg(test)]
mod tests;