Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 9: The real model

Lesson 9.3 · 10 min

Ship Chatterbox

The program works on your machine, from inside the project folder. Shipping means three more things: running the tests that prove the important parts still work, a single file you can run from anywhere, and a few lines of text so someone else knows how. Then v1.0 is done: the whole program, tested and installed.

Adds to ChatterboxVersion 1.0: a README and cargo install.

Eleven tests, one command

Since lesson 7.3, Chatterbox has carried its own tests, run with cargo test, and since lesson 7.4 clippy and rustfmt have kept it tidy. Before you hand a program to anyone, run them one last time. Chatterbox v1.0 has eleven, each a #[test] function inside a #[cfg(test)] mod tests block, so none of them is in the program you ship:

  • Six in command.rs pin down what parse promises: plain text is chat, /help has the short form /h, /say needs text, /last two is not a count, /dance is unknown, and /remember takes a name and a fact.
  • Four in replier.rs pin down Echo and Pretend, including the Err for an empty history from lesson 9.2.
  • One in main.rs pins down last_n from lesson 8.3, with numbers and with text, because it is generic.

The real model is left out on purpose: a test that needs the internet and a key fails for reasons that have nothing to do with your code. Here is the run:

cargo test on Chatterbox v1.0, from a fresh download (a real run; the folder path is shortened to ~/chatterbox, and 112 of the lines naming each crate as it compiles are cut)
$ cargo test
   Compiling libc v0.2.191
   … 112 more lines like this one, one per crate …
   Compiling chatterbox v1.0.0 (~/chatterbox)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 31.96s
     Running unittests src/main.rs (target/debug/deps/chatterbox-d0bf917cd8e453db)

running 11 tests
test command::tests::help_has_a_short_form ... ok
test command::tests::last_needs_a_number ... ok
test command::tests::remember_takes_a_name_and_a_fact ... ok
test command::tests::plain_text_is_chat ... ok
test command::tests::say_needs_text ... ok
test command::tests::unknown_commands_are_errors ... ok
test replier::tests::echo_refuses_long_messages ... ok
test replier::tests::echo_repeats_you ... ok
test replier::tests::nothing_to_reply_to_is_an_error ... ok
test replier::tests::pretend_reads_the_whole_history ... ok
test tests::last_n_takes_from_the_end ... ok

test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

The tests run in any order (cargo runs them side by side), which is why the list above is not in file order. Keep running cargo test after every change. When you add a /clear command next week and accidentally break /last, a test tells you in a second, before anyone else finds out.

Debug build, release build

Until now you used cargo run. That makes a debug build: it compiles fast and runs slowly, with extra checks switched on, and the file lives in target/debug/. When you are ready to hand the program to someone, you ask for the release build, which takes longer to compile and runs faster. Either way the result is a binary: the finished program as a single file the computer can run.

Build the optimised binary (a real first release build; the folder path is shortened to ~/chatterbox, 107 of the crate lines are cut, and the user name is replaced by you)
$ cargo build --release
   Compiling libc v0.2.191
   Compiling proc-macro2 v1.0.107
   Compiling quote v1.0.47
   Compiling unicode-ident v1.0.27
   … 107 more lines like these, one per crate …
   Compiling hyper-rustls v0.27.10
   Compiling reqwest v0.13.5
   Compiling chatterbox v1.0.0 (~/chatterbox)
    Finished `release` profile [optimized] target(s) in 53.61s
$ ls -lh target/release/chatterbox
-rwxr-xr-x@ 1 you  wheel   6.4M Oct 21 15:28 target/release/chatterbox

That one file, target/release/chatterbox, is the whole program. You can copy it to another machine of the same kind and run it there with nothing else installed: no Rust, no cargo, no crates. It is a few megabytes because the HTTP client, the code for secure connections and the JSON code are all inside it. Those Compiling lines are the crates Chatterbox uses and the crates they use, each compiled once.

The v1.0.0 in the output is the version field in Cargo.toml. The "v1.0" Chatterbox prints in its banner is a separate string in main. This lesson changes both, and keeping them in step is your job: nothing checks it.

Install it

Running ./target/release/chatterbox works, but only from this folder. cargo install --path . --locked builds the release binary and copies it into cargo's own bin folder, ~/.cargo/bin, which rustup already added to your PATH (the list of folders your terminal searches when you type a command). After that, chatterbox is a command like any other, in any folder. The --locked tells cargo to use the exact crate versions written in Cargo.lock, the ones your tests just passed with, instead of looking up the newest ones again. Without it, cargo install ignores that file and may build with crate versions your tests never saw.

The session below adds --root ../inst, which installs into a scratch folder instead, so the recording did not touch a real ~/.cargo/bin. That is also why cargo warns about PATH and why the program is run by its path. Without --root, you would type just chatterbox.

Install, then run it from another folder (real runs; folder paths shortened to ~; the echo answers because no model is set)
$ cargo install --path . --locked --root ../inst
  Installing chatterbox v1.0.0 (~/chatterbox)
    Updating crates.io index
    Finished `release` profile [optimized] target(s) in 0.35s
  Installing ~/inst/bin/chatterbox
   Installed package `chatterbox v1.0.0 (~/chatterbox)` (executable `chatterbox`)
warning: be sure to add `~/inst/bin` to your PATH to be able to run the installed binaries
$ cd ../elsewhere

$ printf 'Sam\nhello!\n/quit\n' | ../inst/bin/chatterbox
Chatterbox v1.0 (replies by: echo)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hello!
bot: bye, Sam!
messages so far: 1
saved 2 messages to chatterbox.json
$ ls
chatterbox.json

The install took under a second because the release build from the step before was reused: same code, same crate versions, so there was nothing to compile. And notice where chatterbox.json landed: in the folder the program was run from, as store.rs promised. Each folder you run it in has its own history.

Write it down

A program nobody knows how to use is half shipped. A README is a plain text file named README.md in the project folder. It answers: what is it, how do I run it, what can it do, and what does it need? Chatterbox's is README.md in the listing further down (all green, because it is new). It has a title and one sentence on what the program is, then five short sections:

  • Run it: cargo run, and that it asks your name, then echoes you if no model is set.
  • Commands: one line per command, the same list HELP prints, and where the history is saved (chatterbox.json, in the folder you run it from).
  • Talk to a real model: the three export lines from lesson 9.2.
  • Install it and Test it: the commands from this page.

In the file, the # lines are headings and the indented lines are shown as code: that is the Markdown format, which sites like GitHub display nicely. The README is also where you keep a promise you cannot check with a test: if you add a command, add its line here.

Chatterbox v1.0

Here is Chatterbox v1.0, every file exactly as the download has it; files this lesson did not touch are folded. The green lines are this lesson’s changes: the version in Cargo.toml (0.9.0 to 1.0.0), the VERSION pair in main.rs and the new README.md. No code changed: v1.0 is the program from lesson 9.2, tested, documented and installed.

Press Play with it yourself to run these same files in the page, compiled to WebAssembly. One swap: a page cannot open a network connection, so a stand-in replaces reqwest and /model real reports the missing setting. /quit saves chatterbox.json in the page, so the next run remembers you.

Chatterbox v1.0 after lesson 9.3: the whole program (green lines are new in this lesson)
src/main.rs1 new line
// Chatterbox: a small chat program, built one lesson at a time.
mod command;
mod message;
mod replier;
mod store;
 
use command::{Command, parse};
use message::Message;
use replier::{Echo, Model, Pretend, Replier};
use std::collections::HashMap;
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (1, 0);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /count, /stats, /remember <name> <fact>, /recall <name>, /find <word>, /last <n>, /model <echo|pretend|real>, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)";
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {name}! I'm {BOT}.");
text.push_str(" Ask me anything.");
text
}
 
/// The last `n` items of any slice: messages, numbers, words, anything.
/// `<T>` says "for any type T"; the body never needs to know which one.
fn last_n<T>(items: &[T], n: usize) -> &[T] {
let start = items.len().saturating_sub(n);
&items[start..]
}
 
fn main() -> Result<(), io::Error> {
let mut messages_seen: u32 = 0;
let quiet = false;
let mut last: Option<String> = None; // the last thing you said, for /again
let mut history: Vec<Message> = store::load(store::FILE)?; // last time's conversation, if any
let mut facts: HashMap<String, String> = HashMap::new(); // name -> fact, for /recall
// Box<dyn Replier>: "some Replier, decided while the program runs".
// With a key in the environment, start with the real model.
let mut replier: Box<dyn Replier> = match Model::from_env() {
Ok(model) => Box::new(model),
Err(_) => Box::new(Echo { max_len: MAX_LEN }),
};
 
println!("{} (replies by: {})", banner(), replier.name());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line)?;
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
if !history.is_empty() {
println!(
"(I remember {} messages from last time. /history shows them.)",
history.len()
);
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line)?;
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
let cmd = match parse(message) {
Ok(cmd) => cmd,
Err(e) => {
println!("bot: {e}");
continue;
}
};
match cmd {
Command::Empty => {} // nothing typed: nothing to answer
Command::Quit => {
println!("bot: bye, {name}!");
break;
}
Command::Help => println!("bot: {HELP}"),
Command::Again => match &last {
Some(text) => match replier.reply(&[Message::new("you", text)]) {
Ok(answer) => println!("bot: {answer}"),
Err(e) => println!("bot: (that went wrong: {e})"),
},
None => println!("bot: nothing to repeat yet"),
},
Command::History => {
if history.is_empty() {
println!("bot: nothing said yet");
} else {
for (i, m) in history.iter().enumerate() {
println!("{}. {}", i + 1, m.to_line());
}
}
}
Command::Count => {
let bytes: usize = history.iter().map(|m| m.text.len()).sum();
println!("bot: {} messages, {} bytes of text", history.len(), bytes);
}
Command::Stats => {
// One chain of steps: your messages -> their words -> a count per word.
let mut counts: HashMap<String, u32> = HashMap::new();
for word in history
.iter()
.filter(|m| m.author == "you")
.flat_map(|m| m.text.split_whitespace())
{
*counts.entry(word.to_lowercase()).or_insert(0) += 1;
}
let mut top: Vec<(String, u32)> = counts.into_iter().collect();
// most used first; ties in alphabetical order, so the answer never changes
top.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let words: Vec<String> = top
.iter()
.take(3)
.map(|(word, n)| format!("{word} ({n})"))
.collect();
if words.is_empty() {
println!("bot: nothing said yet");
} else {
println!("bot: your top words: {}", words.join(", "));
}
}
Command::Remember(key, fact) => {
println!("bot: got it: {key} is {fact}");
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {key} is {fact}"),
None => println!("bot: I don't know anything about {key}"),
},
Command::Recall(None) => {
if facts.is_empty() {
println!("bot: I don't remember anything yet. Try /remember");
} else {
// A HashMap has no order, so sort the names before printing them.
let mut names = Vec::new();
for name in facts.keys() {
names.push(name.as_str());
}
names.sort();
println!("bot: I remember: {}", names.join(", "));
}
}
Command::Find(word) => {
// The closure borrows `word` from here: a small function made on the spot.
let hits: Vec<&Message> = history
.iter()
.filter(|m| m.author == "you" && m.text.contains(&word))
.collect();
if hits.is_empty() {
println!("bot: you never said {word}");
} else {
for m in hits {
println!("{}", m.to_line());
}
}
}
Command::Last(n) => {
for m in last_n(&history, n) {
println!("{}", m.to_line());
}
}
Command::Model(choice) => {
let next: Result<Box<dyn Replier>, String> = match choice.as_str() {
"echo" => Ok(Box::new(Echo { max_len: MAX_LEN })),
"pretend" => Ok(Box::new(Pretend)),
"real" => match Model::from_env() {
Ok(model) => Ok(Box::new(model)),
Err(e) => Err(e.to_string()),
},
_ => Err(format!(
"I don't know a model called {choice}. Try echo, pretend or real"
)),
};
match next {
Ok(r) => {
replier = r;
println!("bot: replies now come from {}", replier.name());
}
Err(why) => println!("bot: {why}"),
}
}
Command::Say(text) => println!("bot: {text}"),
Command::Shout(text) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Debug(text) => println!("bot: {:?}", parse(&text)),
Command::Chat(text) => {
messages_seen += 1;
history.push(Message::new("you", &text));
// the history holds its own copy, so `text` can move into `last`
last = Some(text);
match replier.reply(&history) {
Ok(answer) => {
println!("bot: {answer}");
history.push(Message::new("bot", &answer));
}
Err(e) => println!("bot: (that went wrong: {e})"),
}
}
}
}
println!("messages so far: {messages_seen}");
store::save(store::FILE, &history)?;
let s = if history.len() == 1 { "" } else { "s" };
println!("saved {} message{s} to {}", history.len(), store::FILE);
Ok(())
}
 
// Tests: `cargo test` builds and runs them; the program itself never sees them.
#[cfg(test)]
mod tests {
use super::*;
 
#[test]
fn last_n_takes_from_the_end() {
assert_eq!(last_n(&[1, 2, 3, 4], 2), &[3, 4]);
assert_eq!(last_n(&["a", "b"], 5), &["a", "b"]);
assert!(last_n(&[1, 2, 3], 0).is_empty());
}
}
src/command.rsunchanged
//! Commands: what a line of input means, and what can be wrong with it.
use std::fmt;
 
/// Everything a line of input can mean. One enum, so a `match` on it must
/// handle every kind of line: the compiler checks that nothing is forgotten.
#[derive(Debug)]
pub enum Command {
Empty,
Help,
Quit,
Again,
History,
Count,
Stats,
Remember(String, String),
Recall(Option<String>),
Find(String),
Last(usize),
Model(String),
Say(String),
Shout(String),
Debug(String),
Chat(String),
}
 
/// Everything that can be wrong with a line of input. parse() returns one of
/// these instead of a Command, and main prints it.
#[derive(Debug)]
pub enum CommandError {
Unknown(String),
Missing(String, String),
Usage(String),
NotACount(String),
}
 
/// How a CommandError reads when printed with {}.
impl fmt::Display for CommandError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CommandError::Unknown(word) => {
write!(f, "I don't know the command {word}. Try /help.")
}
CommandError::Missing(verb, example) => {
write!(f, "{verb} what? Try /{verb} {example}")
}
CommandError::Usage(form) => write!(f, "try {form}"),
CommandError::NotACount(text) => write!(f, "'{text}' is not a count. Try /last 3"),
}
}
}
 
/// The text after a command word, or the error that says it is missing.
fn need(line: &str, verb: &str, example: &str) -> Result<String, CommandError> {
match arg(line) {
Some(text) => Ok(String::from(text)),
None => Err(CommandError::Missing(
String::from(verb),
String::from(example),
)),
}
}
 
/// How many messages /last should show. "two" or "-1" is an error.
fn parse_count(text: &str) -> Result<usize, CommandError> {
match text.parse::<usize>() {
Ok(n) => Ok(n),
Err(_) => Err(CommandError::NotACount(String::from(text))),
}
}
 
/// Turn one line of input into a Command, or say what is wrong with it.
/// Each `?` means: if this step failed, return its error right here.
pub fn parse(line: &str) -> Result<Command, CommandError> {
let cmd = match first_word(line) {
"" => Command::Empty,
"/help" | "/h" => Command::Help,
"/quit" | "/q" | "/exit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/count" => Command::Count,
"/stats" => Command::Stats,
"/remember" => {
let usage = CommandError::Usage(String::from("/remember <name> <fact>"));
let rest = match arg(line) {
Some(rest) => rest,
None => return Err(usage),
};
match arg(rest) {
Some(fact) => Command::Remember(String::from(first_word(rest)), String::from(fact)),
None => return Err(usage),
}
}
"/recall" => match arg(line) {
Some(name) => Command::Recall(Some(String::from(name))),
None => Command::Recall(None),
},
"/find" => Command::Find(need(line, "find", "hello")?),
"/last" => Command::Last(parse_count(&need(line, "last", "3")?)?),
"/model" => Command::Model(need(line, "model", "pretend")?),
"/debug" => Command::Debug(need(line, "debug", "/say hi")?),
"/say" => Command::Say(need(line, "say", "hello")?),
"/shout" => Command::Shout(need(line, "shout", "hello")?),
word => {
if is_command(word) {
return Err(CommandError::Unknown(String::from(word)));
}
Command::Chat(String::from(line))
}
};
Ok(cmd)
}
 
/// True when the text is a command: it starts with a slash.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// The first word of the text: a slice (&str) pointing into it, not a copy.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
/// The text after the command word, if there is any: Some("hello") for
/// "/say hello", None for a bare "/say". No more "" standing in for nothing.
fn arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => {
let rest = line[i + 1..].trim();
if rest.is_empty() { None } else { Some(rest) }
}
None => None,
}
}
 
#[cfg(test)]
mod tests {
use super::*;
 
#[test]
fn plain_text_is_chat() {
assert!(matches!(parse("hello there"), Ok(Command::Chat(t)) if t == "hello there"));
}
 
#[test]
fn help_has_a_short_form() {
assert!(matches!(parse("/help"), Ok(Command::Help)));
assert!(matches!(parse("/h"), Ok(Command::Help)));
}
 
#[test]
fn say_needs_text() {
assert_eq!(
parse("/say").unwrap_err().to_string(),
"say what? Try /say hello"
);
}
 
#[test]
fn last_needs_a_number() {
assert!(matches!(parse("/last 3"), Ok(Command::Last(3))));
assert_eq!(
parse("/last two").unwrap_err().to_string(),
"'two' is not a count. Try /last 3"
);
}
 
#[test]
fn unknown_commands_are_errors() {
assert_eq!(
parse("/dance").unwrap_err().to_string(),
"I don't know the command /dance. Try /help."
);
}
 
#[test]
fn remember_takes_a_name_and_a_fact() {
assert!(
matches!(parse("/remember pizza extra cheese"), Ok(Command::Remember(k, v)) if k == "pizza" && v == "extra cheese")
);
assert!(parse("/remember pizza").is_err());
}
}
src/message.rsunchanged
//! A Message: one line of the conversation.
use serde::{Deserialize, Serialize};
 
/// One line of the conversation: who said it, and what they said.
#[derive(Serialize, Deserialize)]
pub struct Message {
pub author: String,
pub text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
pub fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
pub fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
pub fn shout(&self) -> String {
self.text.to_uppercase()
}
}
src/replier.rsunchanged
//! Who answers: anything that can reply, behind one trait.
use crate::message::Message;
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt;
 
/// What can go wrong while getting a reply.
#[derive(Debug)]
pub enum ChatError {
/// The request did not get a good answer (no network, bad key, server error).
Http(reqwest::Error),
/// The model answered, but with nothing in it.
Empty,
/// /model real was asked for, but a setting is missing.
NotSet(&'static str),
}
 
impl fmt::Display for ChatError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ChatError::Http(e) => write!(f, "the model call failed: {e}"),
ChatError::Empty => write!(
f,
"there was nothing to reply with (an empty conversation or an empty answer)"
),
ChatError::NotSet(name) => write!(f, "set {name} first (see lesson 9.2)"),
}
}
}
 
/// Lets `?` turn a reqwest error into a ChatError on its own.
impl From<reqwest::Error> for ChatError {
fn from(e: reqwest::Error) -> Self {
ChatError::Http(e)
}
}
 
/// A promise with a name: any type that implements Replier can answer a
/// conversation. A real model can fail, so the answer is a Result.
pub trait Replier {
/// A short name, for "/model" and the banner.
fn name(&self) -> &str;
/// The answer to the conversation so far (the last message is the newest).
fn reply(&self, history: &[Message]) -> Result<String, ChatError>;
}
 
/// The echo Chatterbox has had since chapter 3, now as one kind of Replier.
pub struct Echo {
pub max_len: usize,
}
 
impl Replier for Echo {
fn name(&self) -> &str {
"echo"
}
 
fn reply(&self, history: &[Message]) -> Result<String, ChatError> {
let message = match history.last() {
Some(m) => &m.text,
None => return Err(ChatError::Empty),
};
let text = if message.len() > self.max_len {
format!("that is too long (the limit is {} bytes)", self.max_len)
} else if message.ends_with('?') {
String::from("Good question! I can only echo. Try /model real to ask a real model.")
} else {
format!("you said: {message}")
};
Ok(text)
}
}
 
/// A stand-in for a real model: it shows it was handed the whole conversation.
pub struct Pretend;
 
impl Replier for Pretend {
fn name(&self) -> &str {
"pretend"
}
 
fn reply(&self, history: &[Message]) -> Result<String, ChatError> {
match history.last() {
Some(m) => Ok(format!(
"(pretend model) I read all {} message{}. You last said: {}",
history.len(),
if history.len() == 1 { "" } else { "s" },
m.text
)),
None => Err(ChatError::Empty),
}
}
}
 
/// One message as a chat API expects it: a role and some content.
#[derive(Serialize)]
struct ApiMessage {
role: String,
content: String,
}
 
/// The body we send: which model, and the whole conversation.
#[derive(Serialize)]
struct Request {
model: String,
messages: Vec<ApiMessage>,
}
 
/// The parts of the answer we read. serde ignores every other field.
#[derive(Deserialize)]
struct Response {
choices: Vec<Choice>,
}
 
#[derive(Deserialize)]
struct Choice {
message: ApiReply,
}
 
#[derive(Deserialize)]
struct ApiReply {
content: String,
}
 
/// A real model behind an OpenAI-style chat endpoint, configured from
/// environment variables so the key never sits in the code.
pub struct Model {
url: String,
key: String,
model: String,
}
 
impl Model {
/// Read the three settings, or say which one is missing.
pub fn from_env() -> Result<Model, ChatError> {
let key =
env::var("CHATTERBOX_API_KEY").map_err(|_| ChatError::NotSet("CHATTERBOX_API_KEY"))?;
let url = env::var("CHATTERBOX_URL").map_err(|_| ChatError::NotSet("CHATTERBOX_URL"))?;
let model =
env::var("CHATTERBOX_MODEL").map_err(|_| ChatError::NotSet("CHATTERBOX_MODEL"))?;
Ok(Model { url, key, model })
}
}
 
impl Replier for Model {
fn name(&self) -> &str {
"real"
}
 
fn reply(&self, history: &[Message]) -> Result<String, ChatError> {
// Our names ("you", "bot") become the API's ("user", "assistant").
let mut messages = Vec::new();
for m in history {
let role = if m.author == "you" {
"user"
} else {
"assistant"
};
messages.push(ApiMessage {
role: String::from(role),
content: m.text.clone(),
});
}
let body = Request {
model: self.model.clone(),
messages,
};
let answer: Response = reqwest::blocking::Client::new()
.post(&self.url)
.bearer_auth(&self.key)
.json(&body)
.send()?
.error_for_status()?
.json()?;
match answer.choices.into_iter().next() {
Some(choice) => Ok(choice.message.content),
None => Err(ChatError::Empty),
}
}
}
 
#[cfg(test)]
mod tests {
use super::*;
 
fn said(text: &str) -> Vec<Message> {
vec![Message::new("you", text)]
}
 
#[test]
fn echo_repeats_you() {
assert_eq!(
Echo { max_len: 200 }.reply(&said("hi")).unwrap(),
"you said: hi"
);
}
 
#[test]
fn echo_refuses_long_messages() {
let long = "x".repeat(10);
assert!(
Echo { max_len: 5 }
.reply(&said(&long))
.unwrap()
.starts_with("that is too long")
);
}
 
#[test]
fn pretend_reads_the_whole_history() {
let history = vec![
Message::new("you", "a"),
Message::new("bot", "b"),
Message::new("you", "c"),
];
assert_eq!(
Pretend.reply(&history).unwrap(),
"(pretend model) I read all 3 messages. You last said: c"
);
}
 
#[test]
fn nothing_to_reply_to_is_an_error() {
assert!(matches!(
Echo { max_len: 200 }.reply(&[]),
Err(ChatError::Empty)
));
}
}
src/store.rsunchanged
//! Saving the conversation to a file and reading it back, as JSON.
use crate::message::Message;
use std::fs;
use std::io;
 
/// Where the history is kept, next to wherever you run Chatterbox.
pub const FILE: &str = "chatterbox.json";
 
/// The saved history, or an empty one the very first time (no file yet).
pub fn load(path: &str) -> Result<Vec<Message>, io::Error> {
match fs::read_to_string(path) {
// `?` turns a JSON error into an io::Error for us (serde_json says how).
Ok(text) => Ok(serde_json::from_str(&text)?),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
Err(e) => Err(e),
}
}
 
/// Write the whole history to the file as pretty-printed JSON.
pub fn save(path: &str, history: &[Message]) -> Result<(), io::Error> {
let text = serde_json::to_string_pretty(history)?;
fs::write(path, text)
}
Cargo.toml1 new line
[package]
name = "chatterbox"
version = "1.0.0"
edition = "2024"
 
[dependencies]
reqwest = { version = "0.13", features = ["blocking", "json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
You type
Sam
hello!
/remember pizza extra cheese
/recall pizza
/model pretend
can you hear me?
/stats
/history
/quit
Chatterbox prints (a real run)
Chatterbox v1.0 (replies by: echo)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hello!
bot: got it: pizza is extra cheese
bot: pizza is extra cheese
bot: replies now come from pretend
bot: (pretend model) I read all 3 messages. You last said: can you hear me?
bot: your top words: can (1), hear (1), hello! (1)
1. you: hello!
2. bot: you said: hello!
3. you: can you hear me?
4. bot: (pretend model) I read all 3 messages. You last said: can you hear me?
bot: bye, Sam!
messages so far: 2
saved 4 messages to chatterbox.json

Download this version (zip)Unzip, then cargo run inside the folder.

Five files, one job each:

  • message.rs: the Message struct from chapter 5, with its methods, and the serde derive from lesson 9.1.
  • command.rs: what a line of input means (Command, an enum from chapter 5, with the /h, /q and /exit aliases from lesson 5.5) and what can be wrong with it (CommandError and ?, chapter 7), plus six tests.
  • replier.rs: who answers. The Replier trait from lesson 8.4, the echo, the pretend model and the real one with its HTTP call from lesson 9.2, plus four tests.
  • store.rs: the history on disk (lesson 8.2), as JSON (lesson 9.1).
  • main.rs: the conversation. It reads a line, asks parse what it means, and does it, from remembering facts in a HashMap to asking the replier. When the loop ends it saves.

Swap the replier and nothing else moves. Add a command and only command.rs, one arm in main, HELP and the README change. That is the point of everything since chapter 4: small pieces with clear owners and clear promises.

Next: chapter 10

That is the end of chapter 9, and v1.0 is shipped. Use it with a real model for a while and two things start to grate: a long answer appears all at once, after a wait with nothing on screen, and the only way to stop one is Ctrl-C, which ends the whole program without saving. Chapter 10 fixes both: answers that stream in as the model writes them, and a Ctrl-C that stops the answer instead of Chatterbox.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What is the difference between <code>cargo run</code> and <code>cargo build --release</code>?Reveal
cargo run makes a debug build that compiles quickly and runs slowly. --release takes longer to compile and produces a faster binary in target/release/.
What does <code>cargo install --path . --locked</code> do?Reveal
It builds the project in release mode with the exact crate versions in Cargo.lock (that is the --locked part) and copies the binary into cargo's bin folder, so you can run it by name from any folder.
Which part of the final program would change if you wanted a different model provider?Reveal
None of the code. Only the three environment variables that feed Model (URL, model name and key) change, as long as the provider speaks chat completions.
What does <code>#[cfg(test)]</code> do?Reveal
It builds the block after it only when you run cargo test, so the tests are not part of the program you ship.

That is lesson 9.3. Tick it off so the course remembers where you are.

Questions people ask

How do I build a Rust program for release?

Run cargo build --release in the project folder. The optimised binary is written to target/release/.

How do I install my own Rust program?

Run cargo install --path . --locked in the project folder. The program is built with the crate versions in Cargo.lock and copied into the cargo bin folder, which is normally already on your PATH.

How do I run the tests in a Rust project?

Run cargo test in the project folder. It builds a test version of the program and runs every function marked #[test], then prints which passed and which failed.

Can I give the binary to someone else?

Yes, as long as they use the same kind of machine (same operating system and processor). The file needs no Rust installation to run.

Learn Rust by building a chat app · Lesson 9.3 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026