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.2 · 18 min

One HTTP call to a model

This is the lesson the whole course has been walking toward: Chatterbox sends the conversation to a model over the internet and prints what comes back. It is one request and one reply, and almost every piece of it is something you already know: a struct, JSON, a Result, a trait. The few new words are listed below.

Adds to Chatterbox/model real: Chatterbox calls a real model.

What goes over the wire

Most hosted models, and many that run on your own computer, speak the same small dialect called chat completions. You send an HTTP POST (HTTP is how programs talk over the web, and a POST is a request that carries some data with it) with a JSON body: a model name and a list of messages. You get back JSON with a list called choices, and the reply sits in choices[0].message.content. That is the whole conversation.

Each message in that list has a role (user for you, assistant for the model) and some content. Chatterbox's own Message says author and text, with you and bot, so on the way out the names are translated. The request and the reply are written down as a few small structs, and serde (lesson 9.1) does the JSON.

The shapes, as structs

All of this goes in replier.rs, next to Echo and Pretend. Five small structs describe the JSON:

  • ApiMessage (a role and some content) and Request (a model name and a Vec of messages) are only ever written out, so they derive Serialize.
  • Response, Choice and ApiReply are only ever read, so they derive Deserialize. Together they spell the path choices, then message, then content.

A real reply has many more fields than this (an id, token counts and more). serde quietly ignores any field your struct does not name, so you write down only what you use.

More things that can fail

A real model can fail in ways an echo never could: the network is down, the key is wrong, the reply comes back empty, or the settings were never given. So reply changes its promise. In the trait it now returns Result<String, ChatError>, and Echo and Pretend change to match: they wrap their answers in Ok(...), and an empty history is now an Err. (The echo's answer to a question changed too: it now suggests /model real.) This is normal. You wrote the trait before you knew what the real implementor needed, and the compiler walks you to every place that has to change.

ChatError has one variant per problem: Http carries reqwest's own error, Empty means there was nothing to reply with (an empty conversation, or a model answer with no choices in it), and NotSet names the setting that is missing. Its Display block gives each a sentence, the same shape as CommandError's in lesson 7.2.

Then one new kind of block: impl From<reqwest::Error> for ChatError. From is a trait from the standard library, and this block keeps its promise for ChatError exactly the way impl Replier for Echo did in lesson 8.4. impl From<X> for Y says how to build a Y out of an X, and ? looks for exactly that: when a function returns ChatError and something inside fails with a reqwest::Error, ? converts it on the way out. It is the same mechanism that turned a serde_json error into an io::Error in lesson 9.1.

The call itself

The real replier is a struct called Model with three fields: the url to send to, the key, and the model name. None of them is written in the code.

Model::from_env reads them from three environment variables, CHATTERBOX_API_KEY, CHATTERBOX_URL and CHATTERBOX_MODEL. Each line is env::var(...), then map_err to turn "not there" into ChatError::NotSet with the variable's name, then ? to stop at the first missing one. All three are required; there is no built-in default URL or model, because those depend on which service you use.

reply reads like a sentence. First it builds the list of ApiMessages from the history, turning you into user and anything else into assistant. Then it puts the model name and that list in a Request, and makes the call:

  • .post(&self.url) starts a POST to the URL, .bearer_auth(&self.key) attaches the key the way these services expect, and .json(&body) sends the request as JSON.
  • .send()? fails if the request never reaches the server.
  • .error_for_status()? turns an HTTP error status, such as 401 ("wrong key") or 500 ("the server broke"), into an error, instead of a reply you then try to read.
  • .json()? reads the body into a Response, and fails if it does not fit.

Each ? can end the function early with a ChatError, thanks to the From block. Last, it takes the first choice, or returns Empty if there is none. blocking means the call simply waits there until the reply arrives.

Try itYour turn: the two halves around the call

The call itself needs the network, which the Rust Playground does not have. But the two halves on either side of it are plain serde (lesson 9.1), and they run right here. Fill in request_json, which turns a history into the JSON body Chatterbox sends, and reply_text, which digs the answer out of the JSON that comes back. The structs are the same ones as in replier.rs. In main, r#"…"# is a raw string: text in quotes in which a " needs no backslash, handy for JSON.

The call itself needs the network, which the Rust Playground does not have. But the two halves on either side of it are plain serde (lesson 9.1), and they run right here. Fill in request_json, which turns a history into the JSON body Chatterbox sends, and reply_text, which digs the answer out of the JSON that comes back. The structs are the same ones as in replier.rs. In main, r#"…"# is a raw string: text in quotes in which a " needs no backslash, handy for JSON.

use serde::{Deserialize, Serialize};
 
// Chatterbox's own message, as in message.rs.
struct Message {
author: String,
text: String,
}
 
impl Message {
fn new(author: &str, text: &str) -> Message {
Message { author: String::from(author), text: String::from(text) }
}
}
 
// What goes out.
#[derive(Serialize)]
struct ApiMessage {
role: String,
content: String,
}
 
#[derive(Serialize)]
struct Request {
model: String,
messages: Vec<ApiMessage>,
}
 
// What comes back (only the parts we read).
#[derive(Deserialize)]
struct Response {
choices: Vec<Choice>,
}
 
#[derive(Deserialize)]
struct Choice {
message: ApiReply,
}
 
#[derive(Deserialize)]
struct ApiReply {
content: String,
}
 
/// The JSON body for a chat-completions request: the model name, then every
/// message in order, with "you" as "user" and anyone else as "assistant".
fn request_json(model: &str, history: &[Message]) -> String {
// build a Request, then write it as JSON text
String::new()
}
 
/// The reply text inside a chat-completions answer: the first choice's
/// message content. None if the text does not fit, or there are no choices.
fn reply_text(json: &str) -> Option<String> {
// read the text into a Response, then take the first choice
None
}
 
fn main() {
let history = vec![Message::new("you", "hi"), Message::new("bot", "you said: hi")];
println!("{}", request_json("mock-model", &history));
let canned = r#"{"choices":[{"message":{"role":"assistant","content":"Hello!"}}]}"#;
println!("{:?}", reply_text(canned));
}

Hidden tests (6): an_empty_history_sends_an_empty_list no_choices_is_none an_error_page_is_none reads_the_content_and_ignores_the_rest you_is_user_and_the_bot_is_assistant takes_the_first_choice

This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.

Wiring it into Chatterbox

In main.rs, three places change. At the start, Model::from_env() is tried: if all three settings are there, Chatterbox starts with the real model, and if not, with the echo, so a missing key is never a crash. /model real tries the same thing in the middle of a chat, and HELP lists it. Because that can now fail for a reason worth saying, the /model arm builds a Result<Box<dyn Replier>, String> instead of an Option, so the Err carries the sentence to print. And wherever an answer is asked for (a chat line and /again), a match prints the answer on Ok, or (that went wrong: …) with the reason on Err, and the chat carries on. A failed answer is not added to the history.

The Cargo.toml line for reqwest is what cargo add reqwest --features blocking,json writes.

Chatterbox v0.9 after lesson 9.2: the whole program (green lines are new in this lesson). The run had the three settings pointing at a local stand-in server.
src/main.rs30 new lines
// 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) = (0, 9);
/// 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.rs137 new lines
//! 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 = "0.9.0"
edition = "2024"
 
[dependencies]
reqwest = { version = "0.13", features = ["blocking", "json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
You type
Sam
hello model
and again
/quit
Chatterbox prints (a real run)
Chatterbox v0.9 (replies by: real)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: mock model saw 1 message; last: hello model
bot: mock model saw 3 messages; last: and again
bot: bye, Sam!
messages so far: 2
saved 4 messages to chatterbox.json

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

Be honest about where this runs

The call itself cannot run in your browser (the exercise above ran only the parts around it): the page has no way to reach a model and no safe place to keep a secret. So here is exactly what the run above is. The course build compiles this program and starts a tiny stand-in server on the same computer. The server checks for the key test-key and answers in the chat-completions shape with how many messages it received and what the last one said. Then the build runs Chatterbox with CHATTERBOX_URL pointing at that server, CHATTERBOX_MODEL=mock-model and CHATTERBOX_API_KEY=test-key. Everything but the model is real.

Look at the second answer: the server saw 3 messages. The history held your first message, the first answer and your second message, and reply sent all of it. That is how a model "remembers" a chat: it is sent the whole thing every time.

Two failures, from the same build. First the wrong key: the server says 401, error_for_status turns it into a ChatError, and Chatterbox prints it and carries on. (The number after 127.0.0.1: is whatever port the stand-in server got that time.)

CHATTERBOX_API_KEY=wrong, the same stand-in server (a real run)
You type
Sam
hello
/quit
Chatterbox prints (a real run)
Chatterbox v0.9 (replies by: real)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: (that went wrong: the model call failed: HTTP status client error (401 Unauthorized) for url (http://127.0.0.1:60608/v1/chat/completions))
bot: bye, Sam!
messages so far: 1
saved 1 message to chatterbox.json

Then no settings at all. Chatterbox starts with the echo, and /model real says which setting is missing first.

None of the three settings set (a real run)
You type
Sam
/model real
/quit
Chatterbox prints (a real run)
Chatterbox v0.9 (replies by: echo)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: set CHATTERBOX_API_KEY first (see lesson 9.2)
bot: bye, Sam!
messages so far: 0
saved 0 messages to chatterbox.json

No unwrap() sat in the path of either failure. That is the payoff of chapter 7: a network error is an ordinary value to handle, and the chat loop prints it and keeps going.

Running it against a real model

Download the project above, then set the three variables for a service that speaks chat completions and run it. The URL, model name and key all come from that service's own documentation and account page:

export CHATTERBOX_URL=https://your-provider.example/v1/chat/completions
export CHATTERBOX_MODEL=your-model-name
export CHATTERBOX_API_KEY=your-key
cargo run

The banner should then say replies by: real. A paid service charges for each call, so check its prices first.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
Where does the model's reply text sit in a chat-completions response?Reveal
In choices[0].message.content: the first choice, its message, its content.
Why does the key come from <code>env::var</code> and not a string in the code?Reveal
A string in the code ends up in version control and logs. An environment variable stays outside the program.
What does <code>error_for_status()</code> add?Reveal
It turns an HTTP error status such as 401 or 500 into a Rust error, so you do not try to parse an error page as a reply.

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

Next: 9.3 Ship it →

Questions people ask

What does reqwest::blocking do?

It is the simple, non-async interface of the reqwest crate. A call waits until the reply arrives, which is fine for a small command-line program.

Can I use a model other than OpenAI?

Yes. Many providers and local servers accept the same chat-completions shape. Change CHATTERBOX_URL and CHATTERBOX_MODEL and the code stays the same.

Which environment variables does Chatterbox need for a real model?

All three of CHATTERBOX_URL, CHATTERBOX_MODEL and CHATTERBOX_API_KEY. If any is missing it starts with the echo, and /model real says which one to set.

Why does the reply struct only list a few fields?

serde ignores fields in the JSON that your struct does not name, so you only declare the ones you use.

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