Skip to content

Model calls: make the format reference cacheable; decide on streaming and schema output #87

Open

Description

@alexbeeken

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, :959
  • src/ai/edit.rs:81, :256
  • src/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

  1. 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: &str passed next to the prompt down to complete), not a change to ChatMessage, which the tutor also uses.
  2. Anthropic (anthropic_body, src/ai.rs:1388): send the first user message's content as two text blocks, the stable one first with "cache_control": {"type": "ephemeral"}, then the varying one. Order in the request is system, then messages; the system prompt is the same for a whole job, so it does not break the prefix.
  3. OpenAI-compatible (openai_body in src/ai/providers.rs): send stable + varying as one string in that order. No new fields.
  4. Things to check while doing it:
    • The dev AI provider parses the request (src/routes/dev_ai.rs:212 reads content as a string). It must accept the two-block form. It picks its fixture by the x-skrongle-call header, 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:22 and routes/courses/generate.rs:143 estimate cost from FORMAT_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.

How to know it is done

  • A unit test on anthropic_body: stable text is the first block and carries cache_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.rs and 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": true and 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 the fallbacks beta, which has its own mid-stream behaviour).
  • Keep MAX_REPLY_BYTES on 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 sends output_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 by docs/course-format.md and checked by ContentStore, and the schema feature has limits on what it accepts.
  • Keep parse_json and 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; ureq and serde_json stay (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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions