Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
feat: opt-in prefix-cache-friendly title/summary prompts
fcatuhe166b5a212b44
diff --git a/config/env.transcription.example b/config/env.transcription.exampleindex cd3749cc..fa701f69 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -34,6 +34,15 @@ TEXT_MODEL_NAME=openai/gpt-4o-mini# TEXT_MODEL_API_KEY=sk-your_openai_api_key# TEXT_MODEL_NAME=gpt-4o-mini+# --- Prefix-Cache-Friendly Prompts (Optional, default: false) ---+# Opt-in. Only useful on self-hosted text backends with automatic prefix+# caching (vLLM APC, llama.cpp/Ollama, SGLang, TGI). When true, the title and+# summary calls share a byte-identical system message + transcript-first prefix+# so the backend prefills the transcript once and reuses it on the second call.+# Leave false for hosted APIs (OpenRouter/OpenAI) or to keep upstream prompts.+# See docs/admin-guide/model-configuration.md for details.+# PREFIX_CACHE_OPTIMIZED_PROMPTS=false+# --- GPT-5 Specific Settings (only used with OpenAI API and GPT-5 models) ---# Reasoning effort: minimal, low, medium, high (default: medium)GPT5_REASONING_EFFORT=mediumdiff --git a/docs/admin-guide/model-configuration.md b/docs/admin-guide/model-configuration.mdindex 94ce6fb2..d3de5fc8 100644--- a/docs/admin-guide/model-configuration.md+++ b/docs/admin-guide/model-configuration.md@@ -383,6 +383,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.+PREFIX_CACHE_OPTIMIZED_PROMPTS=false+# GPT-5 specific (only used with GPT-5 models and OpenAI API)GPT5_REASONING_EFFORT=medium # minimal, low, medium, highGPT5_VERBOSITY=medium # low, medium, high@@ -397,6 +401,44 @@ CHAT_GPT5_REASONING_EFFORT=medium # minimal, low, medium, highCHAT_GPT5_VERBOSITY=medium # low, medium, high```+## Prefix-Cache-Friendly Prompts (`PREFIX_CACHE_OPTIMIZED_PROMPTS`)++**Default: `false`. Opt-in. Only relevant for self-hosted text-generation backends.**++For each recording, Speakr makes two LLM calls over the same transcript+back-to-back: title generation, then summary generation. By default these two+calls use different system messages and different text before the transcript, so+they share no common prefix.++Self-hosted, OpenAI-compatible inference servers that implement **Automatic+Prefix Caching** — vLLM (APC), llama.cpp / Ollama (KV reuse), SGLang+(RadixAttention), TGI — can skip recomputing a prompt's KV cache when a new+request shares a prefix with a recent one. Because the title and summary prompts+don't share a prefix today, the expensive transcript prefill is computed twice.++When `PREFIX_CACHE_OPTIMIZED_PROMPTS=true`, Speakr rewrites the title and summary+prompts so they use a byte-identical system message and a byte-identical+transcript-first user block, pushing all per-task instructions into the suffix+after the transcript. The backend then prefills the transcript once (on the+title call) and reuses it on the summary call, prefilling only the short+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.++**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.++Scope is title + summary only. The flag has no effect on chat, event extraction,+or other calls.+## Per-Upload, Per-Tag, Per-Folder Transcription ModelsBy 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.pyindex 22401513..96c9ed3b 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -44,6 +44,46 @@ ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').low# Video retention - when enabled, video files keep their video stream for playbackVIDEO_RETENTION = os.environ.get('VIDEO_RETENTION', 'false').lower() == 'true'+# Prefix-cache-friendly prompts (opt-in, default off).+#+# Title generation and summary generation run over the SAME transcript+# back-to-back. By default they use different system messages and different+# text before the transcript, so an OpenAI-compatible backend with Automatic+# Prefix Caching (vLLM APC, llama.cpp/Ollama KV reuse, SGLang, TGI) cannot reuse+# the (expensive) transcript prefill across the two calls.+#+# When this flag is true we rewrite both prompts so that:+# - the system message is byte-identical between the two calls, and+# - the user message starts with a fixed, byte-identical transcript-first+# block, with all per-task variability (task instructions, language,+# context, user info) pushed into the SUFFIX after the transcript.+# The backend then prefills the transcript once (on the title call) and reuses+# its KV cache on the summary call, prefilling only the short trailing suffix.+#+# Default off so existing deployments and prompt-quality behaviour are unchanged+# unless explicitly opted in. Scope is title + summary only.+PREFIX_CACHE_OPTIMIZED_PROMPTS = os.environ.get(+ 'PREFIX_CACHE_OPTIMIZED_PROMPTS', 'false'+).lower() == 'true'++# Must be byte-identical between the title and summary calls. Keep it short and+# generic; per-task guidance belongs in the user-message suffix.+_SHARED_LLM_SYSTEM_MSG = (+ "You assist with meeting transcripts. Follow the user's specific "+ "instruction precisely and output only what is requested."+)+++def _shared_user_prefix(transcript_text):+ """Byte-identical user-message prefix shared by the title and summary calls.++ DO NOT insert any conditional content (language, date, context, user info)+ before the closing triple-quote. Any byte that differs between the two calls+ past the first divergence kills KV-cache reuse for everything that follows --+ including the transcript itself, which is the expensive part.+ """+ return f'Transcript:\n"""\n{transcript_text}\n"""\n\n'+# 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@@ -376,7 +416,26 @@ def _generate_ai_title(recording):language_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""- prompt_text = f"""Create a short title for this conversation:+ if PREFIX_CACHE_OPTIMIZED_PROMPTS:+ # Shared-prefix layout: identical system message + identical user prefix+ # (including the transcript) between this call and the summary call, so+ # a prefix-caching backend can reuse the transcript KV cache. Everything+ # task-specific goes in the SUFFIX after the transcript block. This+ # prefix MUST stay byte-identical to the one in generate_summary_only_task.+ system_message_content = _SHARED_LLM_SYSTEM_MSG+ prompt_text = (+ _shared_user_prefix(transcript_text)+ + "Task: produce ONE short title for the conversation above.\n"+ + "Requirements:\n"+ + "- Maximum 8 words\n"+ + "- No phrases like \"Discussion about\" or \"Meeting on\"\n"+ + "- Just the main topic\n"+ + "- Output ONLY the title text, nothing else (no quotes, no prefix)\n"+ + (f"- Respond in {user_output_language}\n" if user_output_language else "")+ + "\nTitle:"+ )+ else:+ prompt_text = f"""Create a short title for this conversation:{transcript_text}@@ -389,9 +448,9 @@ Requirements:Title:"""- system_message_content = "You are an AI assistant that generates concise titles for audio transcriptions. Respond only with the title."- if user_output_language:- system_message_content += f" Ensure your response is in {user_output_language}."+ system_message_content = "You are an AI assistant that generates concise titles for audio transcriptions. Respond only with the title."+ if user_output_language:+ system_message_content += f" Ensure your response is in {user_output_language}."try:completion = call_llm_completion(@@ -663,14 +722,39 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_overridecontext_section = "Context:\n" + "\n".join(f"- {part}" for part in context_parts)- # Build SYSTEM message: Initial instructions + Context + Language- system_message_content = "You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly."- system_message_content += f"\n\n{context_section}"- if user_output_language:- system_message_content += f"\n\nLanguage Requirement: You MUST generate the entire summary in {user_output_language}. This is mandatory."-- # Build USER message: Transcription + Summarization Instructions + Language Directive- prompt_text = f"""Transcription:+ if PREFIX_CACHE_OPTIMIZED_PROMPTS:+ # Shared-prefix layout: the system message and the user-message bytes+ # up to and including the transcript block MUST match _generate_ai_title+ # byte-for-byte, so the transcript KV cache built by the title call is+ # reusable here. All variability (role guidance, context, instructions,+ # language) goes in the SUFFIX after the transcript block.+ system_message_content = _SHARED_LLM_SYSTEM_MSG+ suffix_parts = [+ "Task: produce a comprehensive Markdown summary of the "+ "transcript above. Output raw Markdown only -- no code fences, "+ "no preamble, no commentary.",+ "",+ context_section,+ "",+ "Summarization Instructions:",+ summarization_instructions,+ ]+ if user_output_language:+ suffix_parts.append("")+ suffix_parts.append(+ f"Language Requirement: You MUST write the entire summary "+ f"in {user_output_language}. This is mandatory."+ )+ prompt_text = _shared_user_prefix(transcript_text) + "\n".join(suffix_parts)+ else:+ # Build SYSTEM message: Initial instructions + Context + Language+ system_message_content = "You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly."+ system_message_content += f"\n\n{context_section}"+ if user_output_language:+ system_message_content += f"\n\nLanguage Requirement: You MUST generate the entire summary in {user_output_language}. This is mandatory."++ # Build USER message: Transcription + Summarization Instructions + Language Directive+ prompt_text = f"""Transcription:\"\"\"{transcript_text}\"\"\"diff --git a/tests/test_prefix_cache_prompts.py b/tests/test_prefix_cache_prompts.pynew file mode 100644index 00000000..08557e47--- /dev/null+++ b/tests/test_prefix_cache_prompts.py@@ -0,0 +1,173 @@+"""+Tests for the opt-in prefix-cache-friendly prompt layout+(PREFIX_CACHE_OPTIMIZED_PROMPTS).++The title-generation and summary-generation calls run over the same transcript+back-to-back. When the flag is ON, both calls must use a byte-identical system+message AND a byte-identical user-message prefix up to and including the+transcript block, so a prefix-caching inference backend can reuse the transcript+KV cache across the two calls. Everything task-specific must live in the suffix+AFTER the transcript.++When the flag is OFF, the prompts must be exactly the upstream prompts (no+behavioural change). These tests assert both guarantees.+"""++import pytest+from unittest.mock import patch, MagicMock++import src.tasks.processing as processing+++# Marker that ends the byte-identical shared region. _shared_user_prefix wraps+# the transcript as: Transcript:\n"""\n{transcript}\n"""\n\n — so everything up+# to and including the closing """ + blank line must match between the calls.+def _shared_region(user_prompt):+ """Return the substring of a user prompt up to and including the closing+ transcript fence produced by _shared_user_prefix, or None if not present."""+ marker = '"""\n\n'+ idx = user_prompt.find(marker)+ if idx == -1:+ return None+ return user_prompt[: idx + len(marker)]+++def app_with_recording():+ """A Flask app context with a single recording owned by a test user."""+ from src.app import app, db+ from src.models import User, Recording++ with app.app_context():+ user = User.query.filter_by(username="prefix_cache_test_user").first()+ created_user = False+ if not user:+ user = User(username="prefix_cache_test_user", email="[email protected]")+ user.password = "unused"+ db.session.add(user)+ db.session.commit()+ created_user = True++ recording = Recording(+ user_id=user.id,+ title="Prefix Cache Test",+ original_filename="test_prefix_cache.wav",+ transcription=(+ "Alice: Let's lock the launch date. "+ "Bob: I propose the 14th. "+ "Alice: Agreed, the 14th it is. This is long enough to summarise."+ ),+ status="COMPLETED",+ )+ db.session.add(recording)+ db.session.commit()++ try:+ yield app, db, user, recording, created_user+ finally:+ try:+ db.session.delete(recording)+ if created_user:+ db.session.delete(user)+ db.session.commit()+ except Exception:+ db.session.rollback()+++def _capture_messages():+ """Patch target for call_llm_completion: records the messages of every call+ and returns a stub completion so the caller proceeds normally."""+ calls = []++ def _fake_completion(messages=None, **kwargs):+ calls.append(messages or [])+ stub = MagicMock()+ stub.choices = [MagicMock()]+ # A short, single-line response works for both title and summary.+ stub.choices[0].message.content = "Launch date locked"+ stub.choices[0].message.reasoning = None+ stub.usage = MagicMock()+ stub.usage.prompt_tokens = 1+ stub.usage.completion_tokens = 1+ stub.usage.total_tokens = 2+ return stub++ return calls, _fake_completion+++def _run_both_calls(app, recording, user):+ """Run the title call then the summary call, returning (title_messages,+ summary_messages) as {role: content} dicts."""+ calls, fake_completion = _capture_messages()+ with patch("src.tasks.processing.call_llm_completion", side_effect=fake_completion), \+ patch("src.tasks.processing.client", new=MagicMock()):+ processing._generate_ai_title(recording)+ title_messages = dict((m["role"], m["content"]) for m in calls[-1])++ calls.clear()+ processing.generate_summary_only_task(app.app_context(), recording.id, user_id=user.id)+ # The first captured call in the summary task is the summary itself.+ summary_messages = dict((m["role"], m["content"]) for m in calls[0])++ return title_messages, summary_messages+++def test_flag_on_shares_system_and_transcript_prefix(app_with_recording):+ """With the flag ON, title and summary share a byte-identical system message+ and a byte-identical user-message prefix through the transcript block."""+ app, db, user, recording, created_user = app_with_recording++ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", True):+ title_msgs, summary_msgs = _run_both_calls(app, recording, user)++ # System message identical.+ assert title_msgs["system"] == summary_msgs["system"], (+ "system messages diverge with the flag ON:\n"+ f"title: {title_msgs['system']!r}\n"+ f"summary: {summary_msgs['system']!r}"+ )++ # Shared transcript-first prefix present and identical.+ title_prefix = _shared_region(title_msgs["user"])+ summary_prefix = _shared_region(summary_msgs["user"])+ assert title_prefix is not None, "transcript fence missing from title user prompt"+ assert summary_prefix is not None, "transcript fence missing from summary user prompt"+ assert title_prefix == summary_prefix, (+ "user-message prefix (through the transcript block) diverges with flag ON:\n"+ f"title: {title_prefix!r}\n"+ f"summary: {summary_prefix!r}"+ )++ # The transcript must actually be inside the shared region (sanity).+ assert "This is long enough to summarise." in title_prefix+ # Per-task wording must be in the SUFFIX, not the shared prefix.+ assert "Title:" not in title_prefix+ assert "Summarization Instructions:" not in summary_prefix+++def test_flag_off_keeps_upstream_prompts(app_with_recording):+ """With the flag OFF, the prompts are the original upstream prompts: distinct+ system messages and the original transcript wrappers."""+ app, db, user, recording, created_user = app_with_recording++ with patch.object(processing, "PREFIX_CACHE_OPTIMIZED_PROMPTS", False):+ title_msgs, summary_msgs = _run_both_calls(app, recording, user)++ # Upstream system messages are distinct and use the original wording.+ assert title_msgs["system"] == (+ "You are an AI assistant that generates concise titles for audio "+ "transcriptions. Respond only with the title."+ )+ assert summary_msgs["system"].startswith(+ "You are an AI assistant that generates comprehensive summaries for "+ "meeting transcripts."+ )+ assert title_msgs["system"] != summary_msgs["system"]++ # Upstream user-message wrappers.+ assert title_msgs["user"].startswith("Create a short title for this conversation:")+ assert summary_msgs["user"].startswith('Transcription:\n"""')+ assert "Summarization Instructions:" in summary_msgs["user"]++ # And they do NOT share the transcript-first prefix.+ assert _shared_region(title_msgs["user"]) is None