This example demonstrates how to initialize an OpenAI model, define a prompt template using macros like message_formatter!, fmt_message!, and fmt_template!, and build an LLMChain using LLMChainBuilder. It also shows how to handle conversation history using the fmt_placeholder! macro and prompt_args! for input injection.
use langchain_rust::{
chain::{Chain, LLMChainBuilder},
fmt_message, fmt_placeholder, fmt_template,
language_models::llm::LLM,
llm::openai::{OpenAI, OpenAIModel},
message_formatter,
prompt::HumanMessagePromptTemplate,
prompt_args,
schemas::messages::Message,
template_fstring,
};
#[tokio::main]
async fn main() {
// Initialize the model
let open_ai = OpenAI::default().with_model(OpenAIModel::Gpt4oMini.to_string());
// Define a prompt template with a system message and a human message template
let prompt = message_formatter![
fmt_message!(Message::new_system_message(
"You are world class technical documentation writer."
)),
fmt_template!(HumanMessagePromptTemplate::new(template_fstring!(
"{input}", "input"
)))
];
// Build the LLM chain
let chain = LLMChainBuilder::new()
.prompt(prompt.clone())
.llm(open_ai.clone())
.build()
.unwrap();
// Invoke the chain with arguments
match chain
.invoke(prompt_args! {
"input" => "Quien es el escritor de 20000 millas de viaje submarino",
})
.await
{
Ok(result) => println!("Result: {:?}", result),
Err(e) => panic!("Error invoking LLMChain: {:?}", e),
}
// Example with conversation history using fmt_placeholder!
let prompt_with_history = message_formatter![
fmt_message!(Message::new_system_message(
"You are world class technical documentation writer."
)),
fmt_placeholder!("history"),
fmt_template!(HumanMessagePromptTemplate::new(template_fstring!(
"{input}", "input"
))),
];
let chain_with_history = LLMChainBuilder::new()
.prompt(prompt_with_history.clone())
.llm(open_ai)
.build()
.unwrap();
match chain_with_history
.invoke(prompt_args! {
"input" => "Who is the writer of 20,000 Leagues Under the Sea, and what is my name?”,
"history" => vec![
Message::new_human_message("My name is: luis"),
Message::new_ai_message("Hi luis"),
],
})
.await
{
Ok(result) => println!("Result: {:?}", result),
Err(e) => panic!("Error invoking LLMChain: {:?}", e),
}
}