Capstone: Build a Command-Line LLM Assistant
ChatSession ideas from the first. It closes the core path of the track.After this lesson, you will be able to:
- Plan a multi-file project as checkpoints, each with a definition of done that a test file checks
- Build a command-line program from settings, a session class, a retry helper, a mock client and a real-client switch
- Keep history bounded, retry only what is worth retrying, stream a reply, and return JSON that a Pydantic model has validated
- Show token use and cost on every run, log without leaking prompts or keys, and keep secrets out of Git
- Run acceptance tests that inject a mock client, and review your own project against a checklist before you call it finished
Before you start
#What You Are Building
ask sends one question and prints the answer. chat holds a conversation and streams each reply as it arrives. extract turns some text into JSON that has been checked against a schema. After every command it prints a line with the tokens used and the cost. You then choose a domain for it in the next section, which changes what the assistant is for and nothing about how it works.ChatSession from the LLM lesson, grown into a program.| Piece | What it does | Taught in |
|---|---|---|
| Settings | Reads the model, limits and key from environment variables and checks them once | Environment Variables & Secrets |
| Session | Holds the system prompt and history, sends a trimmed copy, records a turn only after success | Calling an LLM API from Python |
| Retry | Waits as the server asks, backs off with jitter, never retries your own bug | Calling an LLM API from Python |
| Streaming | Prints a reply piece by piece | Generators & Context Managers |
| Structured output | Asks for JSON, validates it with Pydantic, repairs a bad reply once | Building APIs with FastAPI |
| Tokens and cost | Adds up usage and multiplies by prices you supply | Calling an LLM API from Python |
| Logging | One line per call with the model and the token counts, never the prompt | Production Python |
| Tests | An acceptance test file that injects a mock client | Testing with pytest |
| Git | Small commits, a .gitignore written before the first commit | Git Basics |
ANTHROPIC_API_KEY set it uses the mock from the LLM lesson, so the whole project and all its tests run with no key and no network. With a key set it builds the real anthropic client. Everything between the switch and the screen is the same code.#How long this takes
estimatedMinutes of this lesson counts both: the reading plus a build allowance of 4 hours.The reference version used to write the tests is about 370 lines in eleven small files. Yours will be different and about as long.
anthropic package (version 1.11.0) pointed at a local stub server that speaks the documented Messages API, covering requests, a 429 with retry-after, 5xx errors, a dropped connection, a 400 and a 401, and streaming. It was not run against the live service, so the first real call with your key is a check nobody has made for you. Section "Self-Review Before You Call It Done" has a smoke test for it.#Choose a Domain
The spine does not care what the assistant is for. A domain is the small part that changes: the system prompt, the shape of the structured result, and an optional extra command. Pick one you would actually use. The acceptance tests are written to pass for any of them, and the reference passed them with two different domains.
| Domain | System prompt | Result schema for extract | Extra command |
|---|---|---|---|
| Study buddy | A tutor that explains briefly and asks you a question back | question, choices (a list of four), answer_index | quiz TOPIC asks for one multiple-choice question and checks your answer |
| Log summariser | An assistant that summarises application logs for someone on call | headline, severity (low, medium or high), key_points | summarise FILE reads a text file and prints its summary |
| Dataset labeller | A careful labeller that never invents facts | label (one of your classes), confidence between 0 and 1 | label FILE reads a JSON Lines file of texts and writes a labelled one |
| Persona chat | A character with a voice and rules you write | mood (one of a short list), wants | /persona NAME inside chat switches character |
assistant/domain.py. The labeller's version, which the reference uses, looks like this.# assistant/domain.py (the dataset labeller)
from typing import Literal
from pydantic import BaseModel, Field
SYSTEM_PROMPT = "You are a careful text labeller. Answer briefly and never invent facts."
EXTRACT_INSTRUCTION = (
'Classify the sentiment of the text below. Reply with JSON only, like {"label": "positive", "confidence": 0.9}. '
"The label is positive or negative and the confidence is a number from 0 to 1."
)
class Result(BaseModel):
label: Literal["positive", "negative"]
confidence: float = Field(ge=0, le=1)extract offline works only if one canned reply is valid JSON for your Result. The checkpoint for the client says where to add it.#The Repository and First Commit
tests/, the program in a package called assistant.llm-assistant/
assistant/
__init__.py
__main__.py # python -m assistant ...
cli.py # argparse, the chat loop, exit codes
clients.py # make_client: mock without a key, real SDK with one
config.py # Settings
domain.py # the only file that changes per domain
history.py # count_tokens, trim_history
mock.py # the mock client from the LLM lesson
retry.py # call_with_retry and helpers
schemas.py # reply text to a validated Pydantic object
session.py # ChatSession
tests/
conftest.py # shared fakes: copy it, do not edit it
test_1_config.py ... test_6_cli.py
.env.example
.gitignore
pyproject.toml # only pytest settings
README.md
requirements.txt
requirements.txt has two lines, pydantic>=2 and pytest. pyproject.toml has the three lines that let the tests import your package from the project root.[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
.gitignore and .env.example first. The .gitignore keeps the environment, your real .env, caches and any saved conversations out of the history. .env.example lists the variable names with no values, so a reader knows what to set.# .gitignore
.env
.venv/
__pycache__/
.pytest_cache/
*.egg-info/
transcripts/
# .env.example
ANTHROPIC_API_KEY=
ANTHROPIC_MODEL=claude-sonnet-5-5
ASSISTANT_PRICE_INPUT=
ASSISTANT_PRICE_OUTPUT=
.env.example is a default to replace: check the provider's current model list. The two price variables are per million tokens, and you fill them in from the provider's pricing page. This project never contains a price, because prices change..env present, git status before the first commit and a check of one ignored file look like this. The file contents and the output below are from a scratch repository.$ git status --short
?? .env.example
?? .gitignore
?? assistant/
?? tests/
$ git check-ignore -v .env .env.example transcripts/chat1.jsonl
.gitignore:1:.env .env
.gitignore:6:transcripts/ transcripts/chat1.jsonl
.env and the transcripts do not appear, and .env.example does, which is what you want. check-ignore printed no line for .env.example because no rule hides it. Commit now, before any code: git commit -m "chore: project skeleton, gitignore and env example". Git Basics explains why the rule must exist before the first commit.#The Contract: What Each Module Provides
The tests import your code by name, so the names and signatures are fixed. Anything else is yours to design. The block below lists only what the tests call. It is a list of signatures, not a program.
# assistant/config.py
class Settings(BaseModel):
model: str = "claude-sonnet-5-5"
max_tokens: int = 300 # > 0
history_budget: int = 200 # >= 0, counted in tokens
attempts: int = 4 # >= 1
price_input: float | None = None # per million tokens
price_output: float | None = None
api_key: SecretStr | None = None # must never appear in repr or str
@classmethod
def from_env(cls, env=None) -> "Settings": ... # env defaults to os.environ; raises ValueError
# assistant/clients.py
def make_client(settings): ... # mock if settings.api_key is None, else the real client
# assistant/history.py
def count_tokens(text: str) -> int: ... # len(text.split()) is the stand-in
def trim_history(history: list, budget: int) -> list: ... # returns a copy
# assistant/retry.py
def is_transient(err) -> bool: ...
def call_with_retry(fn, attempts=4, base=0.5, sleep=time.sleep): ...
# assistant/session.py
class ChatSession:
def __init__(self, client, settings=None, system="", sleep=time.sleep): ...
history: list # the full transcript
tokens: dict # {"input": int, "output": int}
def send(self, prompt) -> str: ...
def stream(self, prompt): ... # a generator of text pieces
def ask_json(self, prompt, schema): ... # returns a schema instance or raises ValueError
def reset(self) -> None: ...
def cost(self, prices) -> float: ... # prices = {"input": ..., "output": ...}
# assistant/cli.py
def main(argv=None, *, client=None, env=None, schema=None, input_fn=input) -> int: ...Read the rules the tests rely on before you write anything. They come straight from the LLM lesson, with a few that the program adds.
- The settings come from
ANTHROPIC_MODEL,ASSISTANT_MAX_TOKENS,ASSISTANT_HISTORY_BUDGET,ASSISTANT_ATTEMPTS,ASSISTANT_PRICE_INPUT,ASSISTANT_PRICE_OUTPUTandANTHROPIC_API_KEY. An empty value counts as unset. - A bad setting raises
ValueErrorwhose message names the field. The command line turns it into a message and exit code 2, before any call. is_transientdecides by what an error carries: astatus_codeof 429 or 500 and up, or a connection or timeout problem. It never imports the SDK, so it works for the mock's errors, the SDK's and the tests' fakes.- The wait before a retry is the server's
retry_after(an attribute, or theretry-afterresponse header) if there is one, otherwisebase * 2 ** (n - 1)times a random number from 0.5 to 1. No wait is longer than 60 seconds. ChatSessioncalls the client asclient.messages.create(model=..., max_tokens=..., system=..., messages=...)andclient.messages.stream(...)with the same keywords. The history is recorded only after a call succeeds.- Each call logs one line at INFO with
model,input_tokens=andoutput_tokens=, and a warning whenstop_reasonismax_tokens. No prompt, no key. mainprints the answer on stdout and the usage linetokens: in=N out=N cost=0.000000on stderr, so a pipe sees only the answer.cost=n/awhen no prices are set. It returns 0, 1 for an API or validation failure, 2 for bad settings.
#The Acceptance Tests
conftest.py of shared fakes. Copy them as they are into tests/. Do not edit them to make your code pass: if a test seems wrong, read the contract again first. They use a FakeClient with the shape of the real client, so they run with no key, no network and no real waiting.Here is the whole set. First the shared file.
# tests/conftest.py
"""Shared fakes for the acceptance tests. Copy this file unchanged; do not edit it to make your code pass."""
from contextlib import contextmanager
from types import SimpleNamespace
from typing import Literal
import pytest
from pydantic import BaseModel, Field
class APIStatusError(Exception):
def __init__(self, status_code, retry_after=None):
super().__init__(f"status {status_code}")
self.status_code = status_code
if retry_after is not None:
self.retry_after = retry_after
class APIConnectionError(Exception):
"""No answer at all. Named like the SDK's class, and it has no status_code."""
class FakeClient:
"""Same shape as the real SDK client. `errors` are raised one per call, in order; None means that call succeeds."""
def __init__(self, replies=("ok",), errors=(), usage=(10, 5), stop_reason="end_turn"):
self.calls = []
self.replies, self.errors = list(replies), list(errors)
self.usage, self.stop_reason = usage, stop_reason
self.messages = SimpleNamespace(create=self._create, stream=self._stream)
def _create(self, *, model, max_tokens, messages, system=""):
self.calls.append({"model": model, "max_tokens": max_tokens, "system": system, "messages": list(messages)})
error = self.errors.pop(0) if self.errors else None
if error is not None:
raise error
index = min(len(self.calls) - 1, len(self.replies) - 1)
text = self.replies[index]
return SimpleNamespace(
content=[SimpleNamespace(text=text, type="text")],
usage=SimpleNamespace(input_tokens=self.usage[0], output_tokens=self.usage[1]),
stop_reason=self.stop_reason, model=model, role="assistant",
)
@contextmanager
def _stream(self, **kwargs):
message = self._create(**kwargs)
words = message.content[0].text.split()
pieces = (w if i == 0 else " " + w for i, w in enumerate(words))
yield SimpleNamespace(text_stream=pieces, get_final_message=lambda: message)
@pytest.fixture
def waits():
return [] # filled by the fake sleep, so no test ever waits
class Verdict(BaseModel): # a schema of the test's own, so these tests work for every domain
label: Literal["pass", "fail"]
score: float = Field(ge=0, le=1)
GOOD = '{"label": "pass", "score": 0.8}'
PRICES = {"input": 2.0, "output": 10.0}
def pair(user, assistant):
return [{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]
@pytest.fixture
def session_for(waits):
"""session_for(client, **settings) builds a ChatSession whose sleep only records the wait."""
def build(client, **settings):
from assistant.config import Settings
from assistant.session import ChatSession
return ChatSession(client, Settings(**settings), system="You are terse.", sleep=waits.append)
return buildCheckpoint 1, configuration.
# tests/test_1_config.py
"""Checkpoint 1: configuration from the environment. No network, no API key, no real waiting."""
import pytest
from assistant.config import Settings
def test_defaults_when_the_environment_is_empty():
s = Settings.from_env({})
assert (s.model, s.max_tokens, s.history_budget, s.attempts) == ("claude-sonnet-5-5", 300, 200, 4)
assert s.api_key is None
def test_environment_overrides_the_defaults():
s = Settings.from_env({"ANTHROPIC_MODEL": "m-1", "ASSISTANT_MAX_TOKENS": "150", "ASSISTANT_HISTORY_BUDGET": "50",
"ASSISTANT_ATTEMPTS": "2", "ANTHROPIC_API_KEY": "sk-test-key"})
assert (s.model, s.max_tokens, s.history_budget, s.attempts) == ("m-1", 150, 50, 2)
assert s.api_key is not None
@pytest.mark.parametrize("name, value", [("ASSISTANT_MAX_TOKENS", "lots"), ("ASSISTANT_MAX_TOKENS", "0"),
("ASSISTANT_ATTEMPTS", "-1")])
def test_a_bad_value_raises_value_error_that_names_the_setting(name, value):
with pytest.raises(ValueError) as caught:
Settings.from_env({name: value})
assert name.removeprefix("ASSISTANT_").lower() in str(caught.value).lower()
def test_the_key_never_shows_up_in_repr_or_str():
s = Settings.from_env({"ANTHROPIC_API_KEY": "sk-test-secret-123"})
assert "sk-test-secret-123" not in repr(s) and "sk-test-secret-123" not in str(s)anthropic package is not installed.# tests/test_2_client.py
"""Checkpoint 2: the client switch. No network, no API key, no real waiting."""
import pytest
from assistant.clients import make_client
from assistant.config import Settings
def test_without_a_key_the_client_is_offline_and_works():
client = make_client(Settings())
reply = client.messages.create(model="m", max_tokens=50, system="", messages=[{"role": "user", "content": "hello"}])
assert isinstance(reply.content[0].text, str) and reply.usage.input_tokens > 0
def test_with_a_key_the_real_sdk_client_is_built_without_retries_of_its_own():
pytest.importorskip("anthropic")
client = make_client(Settings(api_key="sk-test-not-a-real-key"))
assert type(client).__name__ == "Anthropic" and client.max_retries == 0Checkpoint 3, history and retries.
# tests/test_3_history_retry.py
"""Checkpoint 3: history and retries. No network, no API key, no real waiting."""
import pytest
from assistant.history import count_tokens, trim_history
from assistant.retry import call_with_retry, is_transient
from conftest import APIConnectionError, APIStatusError, FakeClient, pair
def test_trim_drops_the_oldest_pairs_and_leaves_the_callers_list_alone():
history = pair("one two three", "four five") + pair("six", "seven")
assert trim_history(history, budget=3) == history[2:]
assert trim_history(history, budget=100) == history
assert trim_history(history, budget=0) == []
assert len(history) == 4
def test_the_system_prompt_and_whole_history_are_sent_every_time(session_for):
client = FakeClient(replies=["first answer", "second answer"])
chat = session_for(client)
chat.send("one")
chat.send("two")
second = client.calls[1]
assert [m["role"] for m in second["messages"]] == ["user", "assistant", "user"]
assert second["system"] == "You are terse."
def test_the_request_uses_the_settings(session_for):
client = FakeClient()
session_for(client, model="m-9", max_tokens=77).send("hi")
assert (client.calls[0]["model"], client.calls[0]["max_tokens"]) == ("m-9", 77)
def test_the_history_that_is_sent_stays_within_the_budget(session_for):
client = FakeClient(replies=["one two three four five six"]) # 6 tokens
chat = session_for(client, history_budget=20)
for _ in range(12):
chat.send("a b c d") # 4 tokens
sent = client.calls[-1]["messages"]
assert sum(count_tokens(m["content"]) for m in sent[:-1]) <= 20
assert sent[0]["role"] == "user" and sent[-1]["role"] == "user"
assert len(chat.history) == 24 # the full transcript is still kept
def test_a_429_is_retried_and_the_servers_wait_is_honoured(waits, session_for):
client = FakeClient(errors=[APIStatusError(429, retry_after=2.0), APIStatusError(429, retry_after=2.0), None])
assert session_for(client).send("hi") == "ok"
assert len(client.calls) == 3 and waits == [2.0, 2.0]
def test_without_retry_after_the_wait_backs_off_with_jitter():
calls = []
errors = [APIConnectionError("down"), APIStatusError(503), None]
def flaky():
calls.append(1)
error = errors[len(calls) - 1]
if error:
raise error
return "done"
waits = [] # a fake sleep that records instead of waiting
assert call_with_retry(flaky, attempts=4, base=0.5, sleep=waits.append) == "done"
assert 0.25 <= waits[0] <= 0.5 and 0.5 <= waits[1] <= 1.0
def test_a_400_and_a_401_are_not_retried(waits, session_for):
for status in (400, 401):
client = FakeClient(errors=[APIStatusError(status)] * 5)
with pytest.raises(APIStatusError):
session_for(client).send("hi")
assert len(client.calls) == 1
assert waits == []
def test_it_gives_up_after_the_last_attempt_and_raises_the_real_error(session_for):
client = FakeClient(errors=[APIStatusError(429, retry_after=1.0)] * 10)
with pytest.raises(APIStatusError) as caught:
session_for(client, attempts=3).send("hi")
assert caught.value.status_code == 429 and len(client.calls) == 3
def test_a_server_that_asks_for_a_very_long_wait_is_capped(waits, session_for):
client = FakeClient(errors=[APIStatusError(429, retry_after=500.0), None])
session_for(client).send("hi")
assert waits == [60]
def test_is_transient_sorts_the_failures():
assert is_transient(APIStatusError(429)) and is_transient(APIStatusError(500)) and is_transient(APIConnectionError())
assert not is_transient(APIStatusError(400)) and not is_transient(ValueError("my bug"))
def test_a_failed_call_leaves_no_half_turn(waits, session_for):
chat = session_for(FakeClient(errors=[APIConnectionError("down")] * 5), attempts=2)
with pytest.raises(APIConnectionError):
chat.send("hi")
assert chat.history == [] and chat.tokens == {"input": 0, "output": 0}Checkpoint 4, streaming and structured output.
# tests/test_4_stream_json.py
"""Checkpoint 4: streaming and structured output. No network, no API key, no real waiting."""
import pytest
from conftest import GOOD, FakeClient, Verdict
def test_stream_yields_pieces_that_join_to_the_reply_and_records_the_turn(session_for):
chat = session_for(FakeClient(replies=["Loss measures the error"]))
pieces = list(chat.stream("What is loss?"))
assert len(pieces) > 1 and "".join(pieces) == "Loss measures the error"
assert [m["role"] for m in chat.history] == ["user", "assistant"]
assert chat.tokens == {"input": 10, "output": 5}
def test_an_abandoned_stream_leaves_no_half_turn(session_for):
chat = session_for(FakeClient(replies=["one two three"]))
pieces = chat.stream("hi")
next(pieces)
pieces.close()
assert chat.history == []
def test_ask_json_returns_a_validated_object_even_when_the_reply_has_chatter(session_for):
client = FakeClient(replies=["Sure, here you go: " + GOOD + " Hope that helps."])
result = session_for(client).ask_json("judge this", Verdict)
assert isinstance(result, Verdict) and result.label == "pass" and len(client.calls) == 1
def test_a_bad_reply_is_repaired_once_with_the_error_sent_back(session_for):
client = FakeClient(replies=['{"label": "maybe", "score": 0.5}', GOOD])
result = session_for(client).ask_json("judge this", Verdict)
assert result.label == "pass" and len(client.calls) == 2
repair = client.calls[1]["messages"][-1]["content"]
assert "label" in repair # the validation error names the bad field
def test_a_reply_that_stays_bad_raises_value_error_after_one_repair(session_for):
client = FakeClient(replies=["I cannot decide.", '{"label": "pass", "score": 7}'])
with pytest.raises(ValueError):
session_for(client).ask_json("judge this", Verdict)
assert len(client.calls) == 2Checkpoint 5, tokens, cost and logs.
# tests/test_5_tokens_logs.py
"""Checkpoint 5: tokens, cost and logs. No network, no API key, no real waiting."""
import logging
import pytest
from conftest import PRICES, FakeClient
def test_tokens_and_cost_add_up_from_the_usage_of_each_call(session_for):
chat = session_for(FakeClient(usage=(10, 5)))
chat.send("one")
chat.send("two")
assert chat.tokens == {"input": 20, "output": 10}
assert chat.cost(PRICES) == pytest.approx((20 * 2.0 + 10 * 10.0) / 1_000_000)
def test_each_call_is_logged_with_tokens_and_without_the_prompt(caplog, session_for):
caplog.set_level(logging.INFO)
session_for(FakeClient(), model="m-9").send("my private question")
assert "m-9" in caplog.text and "input_tokens=10" in caplog.text and "output_tokens=5" in caplog.text
assert "my private question" not in caplog.text
def test_a_cut_off_reply_is_logged_as_a_warning(caplog, session_for):
caplog.set_level(logging.INFO)
session_for(FakeClient(stop_reason="max_tokens")).send("hi")
assert any(r.levelno == logging.WARNING and "max_tokens" in r.getMessage() for r in caplog.records)Checkpoint 6, the command line.
# tests/test_6_cli.py
"""Checkpoint 6: the command line. No network, no API key, no real waiting."""
import json
from assistant.cli import main
from conftest import GOOD, APIStatusError, FakeClient, Verdict
def test_ask_prints_the_answer_and_a_usage_line_with_the_cost(capsys):
env = {"ASSISTANT_PRICE_INPUT": "2.0", "ASSISTANT_PRICE_OUTPUT": "10.0"}
code = main(["ask", "hello"], client=FakeClient(replies=["Hi there"]), env=env)
out, err = capsys.readouterr()
assert code == 0 and out.strip() == "Hi there" # stdout carries the answer and nothing else
assert "tokens: in=10 out=5 cost=0.000070" in err
def test_the_usage_line_says_so_when_no_prices_are_set(capsys):
main(["ask", "hello"], client=FakeClient(), env={})
assert "cost=n/a" in capsys.readouterr().err
def test_with_no_key_and_no_client_the_command_runs_offline_on_the_mock(capsys):
code = main(["ask", "hello"], env={})
out, err = capsys.readouterr()
assert code == 0 and out.strip() != "" and "mock" in err.lower()
def test_extract_prints_validated_json_and_nothing_else_on_stdout(capsys):
client = FakeClient(replies=["Here: " + GOOD])
code = main(["extract", "some text"], client=client, env={}, schema=Verdict)
assert code == 0 and json.loads(capsys.readouterr().out) == {"label": "pass", "score": 0.8}
def test_chat_streams_replies_ignores_blank_lines_and_reset_forgets_the_past(capsys):
lines = iter(["hello", "", "again", "/reset", "third", "/quit"])
client = FakeClient(replies=["Hello there friend"])
code = main(["chat"], client=client, env={}, input_fn=lambda prompt="": next(lines))
assert code == 0 and capsys.readouterr().out.count("Hello there friend") == 3
assert [len(c["messages"]) for c in client.calls] == [1, 3, 1]
def test_chat_ends_cleanly_at_end_of_input():
def no_more(prompt=""):
raise EOFError
assert main(["chat"], client=FakeClient(), env={}, input_fn=no_more) == 0
def test_chat_survives_a_failed_turn(capsys):
lines = iter(["first", "second", "/quit"])
client = FakeClient(replies=["fine"], errors=[APIStatusError(400), None])
code = main(["chat"], client=client, env={}, input_fn=lambda prompt="": next(lines))
out, err = capsys.readouterr()
assert code == 0 and "fine" in out and "error" in err.lower()
def test_an_api_error_is_a_message_and_exit_code_1_never_a_traceback_or_the_key(capsys):
env = {"ANTHROPIC_API_KEY": "sk-test-secret-123"}
client = FakeClient(errors=[APIStatusError(401)])
code = main(["ask", "hello"], client=client, env=env)
out, err = capsys.readouterr()
assert code == 1 and "401" in err and "Traceback" not in out + err
assert "sk-test-secret-123" not in out + err and len(client.calls) == 1
def test_a_bad_setting_stops_the_command_with_exit_code_2_before_any_call(capsys):
client = FakeClient()
code = main(["ask", "hello"], client=client, env={"ASSISTANT_MAX_TOKENS": "lots"})
assert code == 2 and "max_tokens" in capsys.readouterr().err.lower() and client.calls == []assistant package, which is where you start.$ pytest -q tests/test_1_config.py
tests/test_1_config.py:4: in <module>
from assistant.config import Settings
E ModuleNotFoundError: No module named 'assistant.config'
=========================== short test summary info ============================
ERROR tests/test_1_config.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.08s
Each test file imports only what its checkpoint needs, so you can run one file at a time. Red, then green, then commit is the rhythm of the whole project.
#The Six Checkpoints
Work in this order. Each checkpoint names what to write, how you know you are done, and the commit that records it. Run the whole suite at the end of each one, not just its own file, so an earlier checkpoint cannot break unseen.
#Checkpoint 1: Settings
config.py. A Pydantic model holds the settings, and from_env builds it from a mapping of environment variables, ignoring unset and empty ones so the defaults apply. A bad value must raise ValueError with the field name in the message, and the key must stay out of repr. You are done when pytest tests/test_1_config.py reports 6 passed. Commit with feat: settings read from the environment.The first browser exercise below practises this checkpoint with a standard-library version, because the browser cell has no Pydantic.
#Checkpoint 2: Mock, real client and the switch
mock.py by copying the mock from the LLM lesson, then write clients.py. The mock needs one change for your domain: add a keyword to its REPLIES so that the instruction your extract command sends gets back valid JSON for your Result. Then make_client returns the mock when there is no key and the real client when there is. Import the SDK inside the branch that needs it, so the project runs without the package.max_retries=0 and a timeout, so your retry loop is the only one.pytest tests/test_2_client.py passes (one test skips if anthropic is not installed). Commit with feat: mock client and the real-client switch.#Checkpoint 3: History and retries
history.py, retry.py and the first version of session.py with send. The history that is sent is a trimmed copy of the transcript, in whole user and assistant pairs. The retry loop decides by attributes, waits as told, and gives up by raising the real error. A failed call must leave history and tokens untouched. You are done when pytest tests/test_3_history_retry.py reports 11 passed. Commit with feat: bounded history and retry with backoff.The second browser exercise practises the trimming rule with one twist the tests do not check but a real program needs.
#Checkpoint 4: Streaming and structured output
stream and ask_json to the session and write schemas.py. stream is a generator that records the turn only when the stream finishes. ask_json finds the JSON object in the reply, validates it with the schema and, if that fails, sends the error back once and tries again. A second failure raises ValueError. You are done when pytest tests/test_4_stream_json.py reports 5 passed. Commit with feat: streaming and validated JSON with one repair.#Checkpoint 5: Tokens, cost and logs
cost, and the log line to session.py. Tokens come from each reply's usage, and only a successful call adds to them. You are done when pytest tests/test_5_tokens_logs.py reports 3 passed. Commit with feat: token and cost tracking with a log line per call.#Checkpoint 6: The command line
cli.py and __main__.py with ask, chat and extract, and your domain's extra command if you chose one. main takes its client, environment and input function as arguments so the tests can inject them. In __main__.py set up logging and call sys.exit(main()). You are done when the whole suite passes: 36 tests, or 35 plus one skip without the SDK. Commit with feat: command line with ask, chat and extract, then write the README.#Checkpoint Exercises in the Browser
The browser cannot run a project of many files, so it practises two pieces of it. Each cell is a small version of a checkpoint that you can finish in a few minutes, and what you learn goes straight into the real files.
#Checkpoint 1 in miniature: settings from a dict
parse_settings so it builds Settings from a dict of environment variables. An empty or missing variable keeps its default, the three numeric settings must be positive whole numbers or the function raises ValueError naming the variable, and the key must not appear when the object is printed.Tests: With the TODOs left in, the second line still shows max_tokens=300, nothing is raised for the bad values, and the last line says key in repr: True. With a correct solution the output is: Settings(model='claude-sonnet-5-5', max_tokens=300, history_budget=200, attempts=4), then Settings(model='m-1', max_tokens=150, history_budget=200, attempts=4), then ASSISTANT_MAX_TOKENS must be a positive whole number, got 'lots', then ASSISTANT_ATTEMPTS must be a positive whole number, got '0', then key kept: True | key in repr: False.
str.isdigit() is false for '-1', 'lots' and '', so one test covers all three bad shapes, but '0' needs the second check. dataclasses.field(repr=False) is the same idea as Pydantic's SecretStr: the value is stored and the printout hides it.#Checkpoint 3 in miniature: trim to fit a whole request
trim_history in the project trims the stored history to a budget. A real request also carries the system prompt and the new question, and a budget that ignores them can still send too much. Write trim_to_fit so the budget covers the system prompt, the history that is kept and the new prompt together. Drop whole oldest pairs until the request fits. If it still does not fit with no history at all, raise ValueError that says what is needed.Tests: With the TODOs left in, nothing is trimmed: all three budgets keep 4 messages and no error is raised. With a correct solution the output is: 40 -> 4 messages kept, first: what is loss, then 20 -> 2 messages kept, first: and a gradient, then 12 -> 0 messages kept, first: None, then system prompt and question alone need 11 tokens, the budget is 6, then caller's history untouched: 4.
while loop and the final check use the same total(), so compute it in one place. Deleting history[:2] removes the oldest pair.#When You Are Stuck
These hints come in stages. Open one stage at a time and stop as soon as you can move. None of them is a finished function.
No module named assistant means you ran pytest from the wrong folder, or pythonpath = ["."] is missing from pyproject.toml. A test that hangs means something called the real time.sleep: pass the sleep argument through, as the contract says.#What Your Terminal Should Show
These runs come from the reference project in mock mode, with prices set for the cost line. Your wording will differ, and the numbers differ with your domain, but the shape should match: the answer on stdout, a notice and a usage line on stderr.
$ python -m assistant ask "What is a loss function?"
[mock mode: no ANTHROPIC_API_KEY set, replies are canned]
Loss measures how far a prediction is from the true answer.
tokens: in=17 out=11 cost=0.000144
The cost in this run is computed from invented prices of 2 and 10 per million tokens, set in the environment so the arithmetic is checkable. Use the real prices from your provider's pricing page.
$ python -m assistant extract "I loved this film."
[mock mode: no ANTHROPIC_API_KEY set, replies are canned]
{
"label": "positive",
"confidence": 0.93
}
tokens: in=48 out=8 cost=0.000176
The mock's reply to this request has chat in front of the JSON, and the output is still clean, which is the repair and extraction code working. A conversation, with the input piped in so the typed lines do not echo:
$ printf 'What is a loss function?\nSay more.\n/reset\n/quit\n' | python -m assistant chat
[mock mode: no ANTHROPIC_API_KEY set, replies are canned]
Type /reset to start over, /quit to leave.
you> Loss measures how far a prediction is from the true answer.
you> I am a mock model, so I only know a few canned answers.
you> history cleared
you> tokens: in=47 out=24 cost=0.000334
A bad setting stops the program before any call, with exit code 2, and the log line appears when you raise the level.
$ ASSISTANT_MAX_TOKENS=lots python -m assistant ask hi
configuration error: bad configuration: max_tokens: Input should be a valid integer, unable to parse string as an integer
$ echo $?
2
$ ASSISTANT_LOG_LEVEL=INFO python -m assistant ask "What is a loss function?"
[mock mode: no ANTHROPIC_API_KEY set, replies are canned]
INFO assistant.session: llm call model=claude-sonnet-5-5 input_tokens=17 output_tokens=11 seconds=0.00
Loss measures how far a prediction is from the true answer.
tokens: in=17 out=11 cost=n/a
And the finished suite, from the reference on Python 3.12:
$ pytest -q
.................................... [100%]
36 passed in 0.70s
anthropic package the same suite reports 35 passed, 1 skipped.#The README
Write the README last, when the program works, and write it for someone who has never seen the project. Use this template and fill every section with facts about your program. The honest sections are the useful ones: what the mock hides, and what you have not run.
# Project name
One sentence: what the assistant does and for whom.
## What it does
Three to five sentences in plain words. Name the domain, the three commands and
what `extract` returns.
## Setup
```bash
uv venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
uv pip install -r requirements.txt
cp .env.example .env # then edit .env; it is ignored by git
```
With no `ANTHROPIC_API_KEY` the program runs on a built-in mock with canned
replies. To use a real model: `uv pip install anthropic`, set the key and a
model name from the provider's current list, and set the two price variables
from the pricing page.
## Usage
```bash
python -m assistant ask "..."
python -m assistant extract "..."
python -m assistant chat
```
Paste one real run here, including the usage line.
## How it works
One paragraph: the files and the path of a request from the command to the
screen. Name the three decisions you made: how history is trimmed, what is
retried, and how bad JSON is repaired.
## Tests
`pytest` runs the acceptance tests with a fake client: no key, no network.
State how many pass and what they do not cover.
## Limits and what I have not run
Say plainly what the mock hides, whether you have run it against a real key,
and the known problems.
## What I would add next
Two or three concrete ideas.
Keep the README short and true. A claim you did not check, such as "handles rate limits", should be a sentence about what a test shows, or be left out.
#Self-Review Before You Call It Done
Go through the list with the project open, and fix what you find before the last commit. Every item is something you can check, not an opinion.
- Testing: the whole suite passes from a fresh clone and a new virtual environment, with no key set. You have added at least three tests of your own for your domain, such as your
Resultschema rejecting a bad value. - Secrets:
git log -pandgit grep -i "sk-"show no key..envis ignored..env.examplehas names only. PrintingSettings(...)does not show the key. - Errors: an unplugged network, a 401 and a 400 each give one clear message and exit code 1, never a traceback. A failed chat turn does not end the conversation.
- History: a long chat sends about the same number of tokens on turn thirty as on turn ten.
- Cost: every command prints tokens and cost, and
cost=n/ais honest when no prices are set. - Logs: nothing at INFO or above prints a prompt, a reply or a key.
- Real client: run one real call yourself if you have a key. Set the key and model, run
askwith a short question, check the answer, the token counts and the cost line, then runchatfor three turns. If you have no key, say so in the README. - Git: the history reads as the six checkpoints, in small commits with plain messages.
For a second pair of eyes, open the AI tutor and paste this with the file you are least sure about. Treat the answer as a lead to check, because a review can be wrong.
Review this file from my command-line LLM assistant. Tell me three concrete bugs
or risks (cite lines), three things done well, and the one change that would
improve it most. The project has retries, a bounded history, streaming, JSON
validation with Pydantic and token cost tracking. Be direct.
[paste the file]
#Common Mistakes
#Going Further
SYSTEM_PROMPT and EXTRACT_INSTRUCTION are for. None of those is taught here.pathlib and datetime, in a folder the .gitignore already hides. Retry the opening of a stream. Make the history budget a ceiling on cost instead of tokens. Wrap ChatSession in a FastAPI endpoint. Send several extract requests at once with asyncio, and see what the rate limit does to them.#Recap
The capstone is one program with a shape: settings from the environment, a session that keeps and trims history, a retry helper that waits as the server asks, a stream, a validated JSON command, token and cost tracking, logging, and a client switch between a mock and the real SDK. Everything depends on passing the client in, because that is what lets the tests run with no key and no network.
You built it in six checkpoints, each with a definition of done in a test file, and committed after each. A domain is only a system prompt, a schema and an extra command. Before calling it finished you check it against a list: secrets out of Git, errors as messages, cost visible, a real call made if you have a key, and a README that says what you did not run.
Why does the `extract` command print its token and cost line on stderr and not on stdout?