To use llama_cpp-rs, you need to create a LlamaModel to hold the weights and a LlamaSession to manage the context and generation. A LlamaModel is large and shared, while a LlamaSession is relatively small and used for individual interactions.
To generate text, you can use ctx.start_completing_with which returns an iterator of strings. Note that the completion process runs in a worker thread and will stop automatically when the completion handle is dropped.
use llama_cpp::{LlamaModel, LlamaParams, SessionParams};
use llama_cpp::standard_sampler::StandardSampler;
use std::io::{self, Write};
// 1. Load the model
let model = LlamaModel::load_from_file("path_to_model.gguf", LlamaParams::default()).expect("Could not load model");
// 2. Create a session
let mut ctx = model.create_session(SessionParams::default()).expect("Failed to create session");
// 3. Feed context
ctx.advance_context("This is the story of a man named Stanley.").unwrap();
// 4. Generate tokens using a sampler
let max_tokens = 1024;
let mut decoded_tokens = 0;
let mut completions = ctx.start_completing_with(StandardSampler::default(), 1024).into_strings();
for completion in completions {
print!("{completion}");
let _ = io::stdout().flush();
decoded_tokens += 1;
if decoded_tokens > max_tokens {
break;
}
}