Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

TEXT_MODEL_CACHE_BREAKPOINTS: with prefix-cache prompts, mark the shared transcript block with cache_control so Anthropic models reuse it between the title and summary calls (#488)

Murtaza Nasirf4352e4a2e5b
diff --git a/config/env.transcription.example b/config/env.transcription.example
index 7b889035..6932cafe 100644
--- a/config/env.transcription.example
+++ b/config/env.transcription.example
@@ -55,6 +55,12 @@ TEXT_MODEL_NAME=openai/gpt-4o-mini
# cache hits in the admin Token Usage dashboard). See
# docs/admin-guide/model-configuration.md for details.
# PREFIX_CACHE_OPTIMIZED_PROMPTS=false
+# Anthropic models (directly or through OpenRouter) cache only up to an
+# explicit cache_control breakpoint. With this and the setting above both
+# true, the shared transcript block is marked with one, so the summary call
+# reads the transcript from the title call's cache. Only for providers that
+# accept a list of text parts in a message (see the documentation).
+# TEXT_MODEL_CACHE_BREAKPOINTS=false
# --- GPT-5 Specific Settings (only used with OpenAI API and GPT-5 models) ---
# By default GPT-5 parameter handling (reasoning_effort/verbosity,
diff --git a/docs/admin-guide/model-configuration.md b/docs/admin-guide/model-configuration.md
index 993a96d1..e43a028a 100644
--- a/docs/admin-guide/model-configuration.md
+++ b/docs/admin-guide/model-configuration.md
@@ -428,9 +428,10 @@ TITLE_MAX_TOKENS=200
# Optional: Maximum tokens for event extraction from transcripts (default: 4000)
EVENT_MAX_TOKENS=4000
-# Optional: Prefix-cache-friendly title/summary prompts (default: false)
-# Only useful on self-hosted backends with automatic prefix caching. See below.
+# Optional: Prefix-cache-friendly title/summary prompts (default: false). See below.
PREFIX_CACHE_OPTIMIZED_PROMPTS=false
+# Optional: cache breakpoints for Anthropic models (default: false). See below.
+TEXT_MODEL_CACHE_BREAKPOINTS=false
# GPT-5 specific (only used with GPT-5 models and OpenAI API)
GPT5_REASONING_EFFORT=medium # minimal, low, medium, high
@@ -453,7 +454,7 @@ CHAT_MODEL_EXTRA_BODY={"reasoning": {"effort": "low"}}
## Prefix-Cache-Friendly Prompts (`PREFIX_CACHE_OPTIMIZED_PROMPTS`)
-**Default: `false`. Opt-in. Only relevant for self-hosted text-generation backends.**
+**Default: `false`. Opt-in.**
For each recording, Speakr makes two LLM calls over the same transcript
back-to-back: title generation, then summary generation. By default these two
@@ -475,14 +476,15 @@ trailing instructions.
**When to enable it:**
-- You self-host the text model on a backend with automatic prefix caching, and
-- Your transcripts are large (long diarized meetings), so prefill dominates the
- title+summary cost.
+- You self-host the text model on a backend with automatic prefix caching, or
+ you use a hosted model with prompt caching (OpenAI models cache a shared
+ prefix automatically; Anthropic models also need
+ `TEXT_MODEL_CACHE_BREAKPOINTS`, described below), and
+- Your transcripts are large (long diarized meetings), so the transcript
+ dominates the title and summary cost.
**When to leave it off (the default):**
-- You use a hosted API (OpenRouter, OpenAI, etc.) — prefix caching there is
- opaque/automatic and this flag gives no benefit.
- You want the exact upstream prompt wording. With the flag off, prompts are
unchanged.
@@ -524,6 +526,39 @@ A note on what to expect: the very first call over a transcript is always a cach
miss and reports zero cached tokens; the saving appears on the second call that
reuses the prefix.
+### Cache breakpoints for Anthropic models (`TEXT_MODEL_CACHE_BREAKPOINTS`)
+
+**Default: `false`. Used only together with `PREFIX_CACHE_OPTIMIZED_PROMPTS=true`.**
+
+Anthropic models, called directly or through OpenRouter, cache a prompt only up
+to an explicit `cache_control` breakpoint. Without one, the transcript is billed
+in full on both the title and the summary call.
+
+```bash
+PREFIX_CACHE_OPTIMIZED_PROMPTS=true
+TEXT_MODEL_CACHE_BREAKPOINTS=true
+```
+
+With both settings on, the user message of the title and summary calls is sent
+as two text parts: the shared transcript block, marked with
+`"cache_control": {"type": "ephemeral"}`, and the task instructions. The text of
+the prompt is unchanged. The title call writes the transcript to the cache, and
+the summary call a few seconds later reads it at a tenth of the input price.
+Anthropic charges 1.25 times the input price for a cache write, so a call with
+no second call within five minutes, such as a summary regenerated on its own,
+costs slightly more on its transcript part. Prompts shorter than the model's
+minimum cacheable length (about 1,000 to 4,000 tokens, depending on the model)
+are not cached.
+
+The cache reads and writes are recorded and shown under **System Statistics →
+Usage and Cost**.
+
+Enable this setting only for a provider that accepts a list of text parts in a
+message and the `cache_control` field. Through OpenRouter, other models accept
+the request and ignore the field. Some local and OpenAI-compatible servers
+reject it; with such a server, the title and summary calls fail until the
+setting is turned off.
+
## Per-Upload, Per-Tag, Per-Folder Transcription Models
By default Speakr uses the single `TRANSCRIPTION_MODEL` set in `.env` for every recording. If your users transcribe different kinds of recordings (calls, meetings, dictations, multi-speaker interviews) you can publish a list of models they're allowed to choose from at upload time.
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 0ca5112d..c9e21129 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -67,6 +67,15 @@ PREFIX_CACHE_OPTIMIZED_PROMPTS = os.environ.get(
'PREFIX_CACHE_OPTIMIZED_PROMPTS', 'false'
).lower() == 'true'
+# Anthropic models (directly or through OpenRouter) cache only up to an
+# explicit cache_control breakpoint (#488). With this on, the shared prefix is
+# sent as its own text part carrying the breakpoint; the text is unchanged, so
+# automatic prefix caching elsewhere still applies. Only used together with
+# PREFIX_CACHE_OPTIMIZED_PROMPTS.
+TEXT_MODEL_CACHE_BREAKPOINTS = os.environ.get(
+ 'TEXT_MODEL_CACHE_BREAKPOINTS', 'false'
+).lower() == 'true'
+
# Longest notes text given to the summarizer (#440)
SUMMARY_NOTES_LIMIT = 8000
@@ -89,6 +98,24 @@ def _shared_user_prefix(transcript_text):
return f'Transcript:\n"""\n{transcript_text}\n"""\n\n'
+def _user_content(prompt_text, transcript_text):
+ """User-message content for a prompt that may start with the shared prefix.
+
+ A plain string, except with PREFIX_CACHE_OPTIMIZED_PROMPTS and
+ TEXT_MODEL_CACHE_BREAKPOINTS both on: then two text parts, the shared
+ prefix marked with cache_control and the rest of the prompt (#488).
+ """
+ if not (PREFIX_CACHE_OPTIMIZED_PROMPTS and TEXT_MODEL_CACHE_BREAKPOINTS):
+ return prompt_text
+ prefix = _shared_user_prefix(transcript_text)
+ if not prompt_text.startswith(prefix):
+ return prompt_text
+ return [
+ {"type": "text", "text": prefix, "cache_control": {"type": "ephemeral"}},
+ {"type": "text", "text": prompt_text[len(prefix):]},
+ ]
+
+
# Maximum length for user-visible error_message text. The Recording.error_message
# column is TEXT (unbounded) but the UI shows the value verbatim; capping avoids
# scrolling-banner text from a runaway ffmpeg traceback or pathological provider
@@ -563,7 +590,7 @@ Title:"""
completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
- {"role": "user", "content": prompt_text}
+ {"role": "user", "content": _user_content(prompt_text, transcript_text)}
],
temperature=llm_temperature,
# TITLE_MAX_TOKENS lets reasoning-model users (e.g. Kimi K2) raise
@@ -834,7 +861,7 @@ Summarization Instructions:
completion = call_llm_completion(
messages=[
{"role": "system", "content": system_message_content},
- {"role": "user", "content": prompt_text}
+ {"role": "user", "content": _user_content(prompt_text, transcript_text)}
],
temperature=llm_temperature,
max_tokens=int(os.environ.get("SUMMARY_MAX_TOKENS", "3000")),
diff --git a/tests/test_prefix_cache_prompts.py b/tests/test_prefix_cache_prompts.py
index 83c3d3ca..e111f2d9 100644
--- a/tests/test_prefix_cache_prompts.py
+++ b/tests/test_prefix_cache_prompts.py
@@ -207,3 +207,85 @@ def test_flag_off_keeps_upstream_prompts(app_with_recording):
# And they do NOT share the transcript-first prefix.
assert _shared_region(title_msgs["user"]) is None
+
+
+# ---------------------------------------------------------------------------
+# Cache breakpoints (TEXT_MODEL_CACHE_BREAKPOINTS, #488)
+# ---------------------------------------------------------------------------
+
+def _joined(content):
+ """The text of a user message, whether a string or a list of text parts."""
+ if isinstance(content, str):
+ return content
+ return "".join(part["text"] for part in content)
+
+
+def test_breakpoints_split_shared_prefix_into_marked_part(app_with_recording):
+ """Both flags on: title and summary send the shared prefix as their first
+ text part, marked with cache_control, and the same text as without the
+ breakpoints."""
+ app, db, user, recording, created_user = app_with_recording
+
+ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", True), \
+ patch.object(processing, "TEXT_MODEL_CACHE_BREAKPOINTS", False):
+ plain_title, plain_summary = _run_both_calls(app, recording, user)
+ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", True), \
+ patch.object(processing, "TEXT_MODEL_CACHE_BREAKPOINTS", True):
+ title_msgs, summary_msgs = _run_both_calls(app, recording, user)
+
+ for msgs, plain in ((title_msgs, plain_title), (summary_msgs, plain_summary)):
+ content = msgs["user"]
+ assert isinstance(content, list) and len(content) == 2
+ assert content[0]["cache_control"] == {"type": "ephemeral"}
+ assert "cache_control" not in content[1]
+ assert content[0]["text"] == _shared_region(plain["user"])
+ assert _joined(content) == plain["user"]
+ assert msgs["system"] == plain["system"]
+
+ assert title_msgs["user"][0] == summary_msgs["user"][0]
+
+
+def test_breakpoints_without_prefix_layout_change_nothing(app_with_recording):
+ """TEXT_MODEL_CACHE_BREAKPOINTS alone leaves the upstream string prompts."""
+ app, db, user, recording, created_user = app_with_recording
+
+ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", False), \
+ patch.object(processing, "TEXT_MODEL_CACHE_BREAKPOINTS", False):
+ plain_title, plain_summary = _run_both_calls(app, recording, user)
+ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", False), \
+ patch.object(processing, "TEXT_MODEL_CACHE_BREAKPOINTS", True):
+ title_msgs, summary_msgs = _run_both_calls(app, recording, user)
+
+ assert title_msgs == plain_title
+ assert summary_msgs == plain_summary
+ assert isinstance(title_msgs["user"], str) and isinstance(summary_msgs["user"], str)
+
+
+def test_breakpoint_request_body_through_openai_sdk():
+ """The text parts reach the server as written, with cache_control on the
+ first part only."""
+ import json
+ import httpx
+ from openai import OpenAI
+ import src.services.llm as llm
+
+ bodies = []
+
+ def handle(request):
+ bodies.append(json.loads(request.content))
+ return httpx.Response(200, json={
+ "id": "x", "object": "chat.completion", "created": 0, "model": "m",
+ "choices": [{"index": 0, "finish_reason": "stop",
+ "message": {"role": "assistant", "content": "ok"}}],
+ })
+
+ fake = OpenAI(api_key="test-only", base_url="https://openrouter.example/api/v1", max_retries=0,
+ http_client=httpx.Client(transport=httpx.MockTransport(handle)))
+ content = [
+ {"type": "text", "text": "Transcript:\n\"\"\"\nhello\n\"\"\"\n\n", "cache_control": {"type": "ephemeral"}},
+ {"type": "text", "text": "Task: produce ONE title."},
+ ]
+ with patch.object(llm, "client", fake):
+ llm.call_llm_completion([{"role": "system", "content": "s"}, {"role": "user", "content": content}])
+
+ assert bodies[0]["messages"][1]["content"] == content