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(aroleand somecontent) andRequest(amodelname and aVecof messages) are only ever written out, so they deriveSerialize.Response,ChoiceandApiReplyare only ever read, so they deriveDeserialize. Together they spell the pathchoices, thenmessage, thencontent.
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 aResponse, 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.
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.
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.
src/command.rsunchanged
src/message.rsunchanged
src/store.rsunchanged
Sam hello model and again /quit
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.)
Sam hello /quit
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.
Sam /model real /quit
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.
Say it out loud, then reveal
Where does the model's reply text sit in a chat-completions response?Reveal
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
What does <code>error_for_status()</code> add?Reveal
That is lesson 9.2. Tick it off so the course remembers where you are.
Go deeper
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.