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.1 · 9 min

Messages become JSON

Chatterbox saves its history in a format only Chatterbox understands. JSON is a plain-text format that every language can read, and it is also how programs talk to a model. This lesson saves the history as JSON, using a crate called serde and the traits from lesson 8.4, and Chatterbox writes no translating code by hand.

Adds to ChatterboxThe history is saved as JSON.

Why JSON

Since lesson 8.2, chatterbox.log holds lines like you: hello. It works, but it is a format we made up. No other program knows it. Every new thing we want to store (a time, say) means new splitting code in from_lines. And one awkward character, such as a colon-and-space inside an author name, would split a line in the wrong place.

Almost every program that stores or sends data as text uses JSON instead: curly braces for a record, square brackets for a list, quoted names for fields. A Chatterbox message as JSON looks like {"author":"you","text":"hi"}, and the whole history is a list of those in square brackets. It is also the format a model's service speaks, which matters in the very next lesson.

Writing a value down as text is called serializing. Reading text back into a value is deserializing.

Crates: code other people wrote

Rust's standard library does not know JSON. A crate is a package of Rust code someone else wrote, and you ask for it by name in Cargo.toml, the file you met in lesson 1.2. Two crates do the work here: serde knows how to turn Rust values into and out of formats, and serde_json teaches it the JSON format.

From inside your project folder, cargo add serde --features derive and cargo add serde_json add both lines to Cargo.toml for you. The derive feature is the one that lets you write one line above a struct and get all the parsing code written for you.

One line above the struct

Here is a small example first, apart from Chatterbox. Its struct has two new words on it: Serialize and Deserialize. They are traits, exactly like Replier in lesson 8.4: Serialize promises "I can be written out", Deserialize promises "I can be read back in". Writing the impl blocks by hand would mean a method that visits every field. Putting the trait names in #[derive(...)] (lesson 5.5) asks serde to write those impl blocks for you while the program compiles. You do not write any of it.

And serde_json::to_string is a generic function with a trait bound, the shape from lesson 8.4: it accepts any T as long as T: Serialize. Hand it something that never made the promise and you get the same E0277 you met there.

The field names become the JSON keys. The examples on this page call the fields role and content, the names a model's service expects (its API: the list of requests it accepts, and their exact shape). Chatterbox's own Message keeps author and text, so its JSON uses those names.

A small example: a struct to JSON text and back
use serde::{Deserialize, Serialize};
 
#[derive(Serialize, Deserialize, Debug)]
struct Message {
role: String,
content: String,
}
 
fn main() {
let m = Message { role: "user".to_string(), content: "hi".to_string() };
let text = serde_json::to_string(&m).unwrap();
println!("{text}");
 
let back: Message = serde_json::from_str(&text).unwrap();
println!("{back:?}");
}
$ cargo run
{"role":"user","content":"hi"}
Message { role: "user", content: "hi" }
PredictWhat does the JSON look like?
use serde::Serialize;
 
#[derive(Serialize)]
struct Message {
role: String,
content: String,
}
 
fn main() {
let m = Message { role: "assistant".to_string(), content: "Hello!".to_string() };
println!("{}", serde_json::to_string(&m).unwrap());
}

Which text does this program print?

  • {"role":"assistant","content":"Hello!"}
  • {"content":"Hello!","role":"assistant"}
  • Message { role: "assistant", content: "Hello!" }
Reveal the answer

The program prints: {"role":"assistant","content":"Hello!"} serde writes the fields in the order the struct declares them, with the field names as quoted keys. It is JSON text, not the debug form of the struct.

Reading can fail

Writing a value as JSON practically always works: the struct is already shaped correctly. Reading is different, because the text came from outside. It might be missing a field, or not be JSON at all. That is why from_str returns a Result, the type from chapter 7. The example above used unwrap() to stay short. A real program matches on it, or uses ?, so bad text becomes an error message instead of a crash.

This is where Rust earns its keep. If the text is {"role":"assistant"} with no content, you find out right there, at the edge. You never carry a half-filled value through the rest of the program.

Try itYour turn: write it down, read it back

Fill in to_json so it returns the JSON text for a Message, and from_json so it returns Some(message) for good JSON and None for text that does not fit. .ok() on a Result gives an Option: Ok(v) becomes Some(v) and Err(_) becomes None.

Fill in to_json so it returns the JSON text for a Message, and from_json so it returns Some(message) for good JSON and None for text that does not fit. .ok() on a Result gives an Option: Ok(v) becomes Some(v) and Err(_) becomes None.

use serde::{Deserialize, Serialize};
 
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Message {
role: String,
content: String,
}
 
fn to_json(m: &Message) -> String {
// return the JSON text for m
String::new()
}
 
fn from_json(text: &str) -> Option<Message> {
// Some(message) if the text fits, None if it does not
None
}
 
fn main() {
let m = Message { role: "user".to_string(), content: "hi".to_string() };
let text = to_json(&m);
println!("{text}");
println!("{:?}", from_json(&text));
}

Hidden tests (4): not_json_is_none writes_expected_json round_trip_gives_same_message missing_field_is_none

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

Chatterbox saves JSON

Now the real program. Three files change in earnest, and the green lines show each one:

  • Cargo.toml gains the two crates, exactly what the two cargo add commands write.
  • message.rs gains the use serde::... line and #[derive(Serialize, Deserialize)] above Message. That is the whole change to the type.
  • store.rs gets shorter. to_lines and from_lines are gone: serde does their job now, for every field, with no splitting code. FILE becomes chatterbox.json. save calls serde_json::to_string_pretty, which writes the same JSON with line breaks and indents so a person can read the file. load calls serde_json::from_str(&text)?.

Two things about that load line. How does from_str know to build a list of messages? From the type load promises to return: Rust works it out, and serde builds a Vec<Message> because that is what is asked for. And the ? is doing a little extra. from_str fails with a serde_json error, but load promises an io::Error. serde_json ships a conversion from its error into an io::Error, and ? uses such a conversion by itself when the two types differ. That conversion is itself a trait, From, which serde_json implements for its error, and ? looks for exactly that. One more trait is quietly at work in save: a slice of Messages is Serialize because each Message is, so to_string_pretty(history) needs no extra code. main changes only its version number, to v0.9.

Chatterbox v0.9 after lesson 9.1: 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, 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>, /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".
let mut replier: Box<dyn Replier> = 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) => println!("bot: {}", replier.reply(&[Message::new("you", text)])),
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: Option<Box<dyn Replier>> = match choice.as_str() {
"echo" => Some(Box::new(Echo { max_len: MAX_LEN })),
"pretend" => Some(Box::new(Pretend)),
_ => None,
};
match next {
Some(r) => {
replier = r;
println!("bot: replies now come from {}", replier.name());
}
None => {
println!("bot: I don't know a model called {choice}. Try echo or pretend")
}
}
}
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);
let answer = replier.reply(&history);
println!("bot: {answer}");
history.push(Message::new("bot", &answer));
}
}
}
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.rs2 new lines
//! 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;
 
/// A promise with a name: any type that implements Replier can answer a
/// conversation. The chat loop only ever talks to this promise.
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]) -> String;
}
 
/// 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]) -> String {
let message = match history.last() {
Some(m) => &m.text,
None => return String::from("(nothing to reply to)"),
};
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 for now. Ask me again in chapter 9.")
} else {
format!("you said: {message}")
}
}
}
 
/// A stand-in for a real model: it shows that it was handed the WHOLE
/// conversation, which is exactly what the real one will need.
pub struct Pretend;
 
impl Replier for Pretend {
fn name(&self) -> &str {
"pretend"
}
 
fn reply(&self, history: &[Message]) -> String {
match history.last() {
Some(m) => format!(
"(pretend model) I read all {} message{}. You last said: {}",
history.len(),
if history.len() == 1 { "" } else { "s" },
m.text
),
None => String::from("(pretend model) nothing to read yet"),
}
}
}
 
#[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")), "you said: hi");
}
 
#[test]
fn echo_refuses_long_messages() {
assert!(
Echo { max_len: 5 }
.reply(&said("far too long"))
.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),
"(pretend model) I read all 3 messages. You last said: c"
);
}
}
src/store.rs7 new lines
//! 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.toml3 new lines
[package]
name = "chatterbox"
version = "0.9.0"
edition = "2024"
 
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
You type
Sam
hello json
/quit
(run it again)
Sam
/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: you said: hello json
bot: bye, Sam!
messages so far: 1
saved 2 messages to chatterbox.json

--- next run ---
Chatterbox v0.9 (replies by: echo)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
(I remember 2 messages from last time. /history shows them.)
bot: bye, Sam!
messages so far: 0
saved 2 messages to chatterbox.json

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

Run it on your own machine and open the file it leaves behind. This is a real run of the program above, in an empty folder, followed by a look at the file and then by what happens when the file holds something that is not JSON.

The saved file, then a broken one (real runs of Chatterbox v0.9 after lesson 9.1)
$ printf 'Sam\nhello json\n/quit\n' | cargo run -q
Chatterbox v0.9 (replies by: echo)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hello json
bot: bye, Sam!
messages so far: 1
saved 2 messages to chatterbox.json
$ cat chatterbox.json
[
  {
    "author": "you",
    "text": "hello json"
  },
  {
    "author": "bot",
    "text": "you said: hello json"
  }
]
$ echo 'not json' > chatterbox.json

$ printf 'Sam\n/quit\n' | cargo run -q
Error: Custom { kind: InvalidData, error: Error("expected ident", line: 1, column: 2) }

The last run is the ? chain from chapter 7 doing its job: from_str failed, load passed the error up, main passed it out, and Rust printed it and stopped before the chat began, without overwriting the file. That message is written for programmers, not for people; a friendlier one would be a nice change to make yourself. One more honest note: the old chatterbox.log is not read any more, so a history saved before this lesson stays in that file.

If you have coded before

json.dumps(msg) and json.loads(text) do the same two jobs, and loads gives you a dict that may be missing keys, which you find out about later when you index it. Here the struct is the check: a reply that does not fit is rejected at the door.

What you have now

Chatterbox saves its whole history as JSON and reads it back, with serde writing the translation. That is also half of talking to a model: a request goes out as JSON and the reply comes back as JSON. Next lesson, the other half: a third Replier that sends the conversation to a real model as JSON and reads its JSON answer.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What are serializing and deserializing?Reveal
Serializing writes a Rust value as text (here JSON). Deserializing reads text back into a Rust value.
Why does <code>from_str</code> return a Result when <code>to_string</code> practically never fails?Reveal
The text comes from outside the program, so it can be missing fields or not be JSON at all. The struct you write out is already shaped correctly.
What does <code>#[derive(Serialize, Deserialize)]</code> do?Reveal
It asks serde to write the conversion code for your struct at compile time, so you do not write it by hand.

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

Next: 9.2 One HTTP call →

Questions people ask

What is JSON?

A plain-text format for data: curly braces for records, square brackets for lists, and quoted field names. Nearly every web API, including model APIs, uses it.

What is a crate in Rust?

A package of Rust code. You list the crates your project needs in Cargo.toml and cargo downloads and builds them.

Do I need serde to use JSON in Rust?

In practice yes. The standard library has no JSON support, and serde with serde_json is the common choice.

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