Repository navigation
Description
Found in a design read-through. Line numbers are as of commit 1c8ba37. #NNN in code comments are the parent repository's numbers, not this one's.
Three changes to how src/ai.rs talks to a model, in order of value. Each is its own PR. Part A is worth doing now. Parts B and C each start with a question to answer before any code.
Before writing request code, read the provider's current documentation for the feature. The request shapes below were checked against Anthropic's documentation in November 2026 but API details move; do not rely on memory or on this issue for field names.
Part A: let the provider cache the course format reference
The problem
Every generation request embeds docs/course-format.md (ai::FORMAT_DOC, 44,740 bytes, roughly 11,000 tokens) in full. A six-lesson course sends it at least seven times.
Provider caches match on the prefix of a request: the part that is byte-identical from the start. Today the reference is at the end of the user message, after the text that changes per lesson:
src/ai.rs:448,:536,:813,:959src/ai/edit.rs:81,:256src/ai/edit_lesson.rs:59
all build format!("{varying}{rules}\n\n----- Course format reference -----\n\n{FORMAT_DOC}"). So nothing can be cached: not by Anthropic (which also needs to be asked: nothing in src/ai/ sends cache_control), and not by providers that cache prefixes on their own.
The code already expects cached tokens: anthropic_usage (src/ai.rs:1465) reads cache_read_input_tokens, Usage has a cached field, and SKRONGLE_AI_PRICES has a cached rate. They are always zero.
Suggested solution
- Give the prompt builders two parts instead of one string: a stable part (the reference, then the kind's rules) and a varying part (everything else). Stable first. The simplest carrier is a new optional field on the call (for example
stable: &strpassed next to the prompt down tocomplete), not a change toChatMessage, which the tutor also uses. - Anthropic (
anthropic_body,src/ai.rs:1388): send the first user message'scontentas two text blocks, the stable one first with"cache_control": {"type": "ephemeral"}, then the varying one. Order in the request issystem, thenmessages; the system prompt is the same for a whole job, so it does not break the prefix. - OpenAI-compatible (
openai_bodyinsrc/ai/providers.rs): send stable + varying as one string in that order. No new fields. - Things to check while doing it:
- The dev AI provider parses the request (
src/routes/dev_ai.rs:212readscontentas a string). It must accept the two-block form. It picks its fixture by thex-skrongle-callheader, not the body, so fixtures should not need to change; confirm that. - The default cache lifetime is five minutes, refreshed on each read. A slow lesson at the highest effort can take longer than that, and then the next request pays for a cache write again. The documentation describes a longer lifetime at a higher write price; decide from a real run's numbers, not up front.
budget.rs:22androutes/courses/generate.rs:143estimate cost fromFORMAT_DOC.len()per request at the full input rate. Leave the estimate alone in this PR (it stays an upper bound); note in the PR that it could price repeats at the cached rate later.
- The dev AI provider parses the request (
How to know it is done
- A unit test on
anthropic_body: stable text is the first block and carriescache_control; the varying text follows. - A unit test that for two different lessons of one job the bytes up to the end of the stable block are identical.
- The dev generation tests in
src/ai/tests.rsand the e2e generation spec pass. - For the owner, with a real key (an agent should not spend the owner's money): generate a three-lesson course and look at the job's logged usage. The second and third lesson requests should show cached tokens above zero. If they show zero, something before the stable block differs between requests.
Part B: stream long replies (decide first)
The question to answer first
Requests are sent whole and read whole with one 900 s timeout (GENERATE_TIMEOUT, src/ai.rs:1326; agent(), :1196; send, :1471). A long reply means minutes on a connection with no bytes moving, which is where proxies and providers tend to cut. Has this install seen it? Look for timed out after or request failed in the Pi's log for generations at the highest effort. If there are none, close Part B as not needed and say so here.
If it is needed
- Send
"stream": trueand read the body as server-sent events, accumulating the text deltas; the last events carry the stop reason and the usage. Read the streaming page of the documentation for the event names and for how a refusal and an error arrive mid-stream (the app sends thefallbacksbeta, which has its own mid-stream behaviour). - Keep
MAX_REPLY_BYTESon the accumulated text. - The timeout becomes "no bytes for N seconds" instead of 900 s for the whole request, and the cancel flag can be checked between chunks, so Cancel takes effect in seconds instead of at the next request.
- The dev AI provider (
src/routes/dev_ai.rs) has to answer in the same form. That is most of the work. - Anthropic first. The OpenAI-compatible providers stream too, with a different event format; do them only if their logs show the same problem.
- No new dependency: an event stream is lines of
event:/data:text.
Part C: ask for JSON by schema where the reply is small (decide first)
The question to answer first
Replies are free text that ai::parse_json (src/ai.rs:1179) digs JSON out of, with up to three attempts per lesson. How often does a retry happen because the text was not JSON, as opposed to JSON that broke a course rule? Count it in the dev tests' logs and, better, in a few real generations. A schema fixes only the first kind. If it is rare, close Part C.
If it is needed
- Anthropic takes a JSON schema for the reply under
output_config(the documentation's "structured outputs"). The app already sendsoutput_config.effort(src/ai/budget.rs:86); add to that object, do not replace it. - Start with the small, fixed shapes: the plans (
edit-plan,revise-plan), the outline, and the{"lesson", "why", "check"}wrapper. Do not try to express the whole lesson format as a schema: it is defined in prose bydocs/course-format.mdand checked byContentStore, and the schema feature has limits on what it accepts. - Keep
parse_jsonand the validation retry for every provider. The other providers' support for schemas varies, and a reply that is valid JSON can still break a course rule.
Do not (all parts)
- No SDK and no new HTTP or JSON crates;
ureqandserde_jsonstay (CLAUDE.md: no new heavy dependencies). - No code path for a provider nobody has configured (CLAUDE.md "One shape").
- Model calls stay on their own OS thread, never the Tokio blocking pool.
Activity