Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
fix: rank keyword search in SQL before limiting (common words buried real matches), add keyword mode + auto fallback to the agent search tool, embedding-API failure cooldown, and align citation chips with the text line
Murtaza Nasiref3a4f6c1a3e
diff --git a/src/services/embeddings.py b/src/services/embeddings.pyindex 325e14e5..840dc46f 100644--- a/src/services/embeddings.py+++ b/src/services/embeddings.py@@ -3,6 +3,7 @@ Embedding generation and semantic search services."""import os+import reimport timeimport randomimport numpy as np@@ -118,6 +119,10 @@ def get_embedding_api_client():_API_EMBED_MAX_ATTEMPTS = int(os.environ.get('EMBEDDING_API_MAX_RETRIES', '3'))+# After a full retry cycle fails, skip the embedding API for this long so+# every search doesn't pay the retry latency while the provider is down.+_API_EMBED_COOLDOWN_SECONDS = int(os.environ.get('EMBEDDING_API_COOLDOWN_SECONDS', '120'))+_api_embed_down_until = 0.0_API_EMBED_BASE_BACKOFF_SECONDS = float(os.environ.get('EMBEDDING_API_BACKOFF_SECONDS', '1.5'))# Substrings of error messages that suggest the failure is transient and@@ -167,12 +172,21 @@ def _api_embed(texts, user_id=None):When ``user_id`` is provided and the response includes a ``usage``block, record the call against the daily token-usage aggregate."""- global _dimensions_rejected+ global _dimensions_rejected, _api_embed_down_untilclient = get_embedding_api_client()if client is None or not texts:return []+ # Circuit breaker: after a full retry cycle fails, skip the API entirely+ # for a cooldown window instead of burning ~9s of retries on every call+ # (searches fall back to keyword matching immediately; indexing fails+ # fast with the usual empty-list sentinel and is retried later).+ if time.time() < _api_embed_down_until:+ current_app.logger.debug(+ "Embedding API in failure cooldown; skipping call and using fallback")+ return []+# encoding_format='float' explicitly: OpenAI SDK v2 defaults to base64,# which some OpenAI-compatible providers cannot produce; float is the# format every compatible provider accepts.@@ -208,6 +222,7 @@ def _api_embed(texts, user_id=None):except Exception as track_err:current_app.logger.warning(f"Failed to record embedding usage: {track_err}")+ _api_embed_down_until = 0return [np.array(d.embedding, dtype=np.float32) for d in response.data]except Exception as e:@@ -228,6 +243,7 @@ def _api_embed(texts, user_id=None):f"Embedding API call failed (attempt {attempt}/{_API_EMBED_MAX_ATTEMPTS}, "f"transient={transient}): {e}")+ _api_embed_down_until = time.time() + _API_EMBED_COOLDOWN_SECONDSreturn []# Exponential backoff with light jitter so concurrent retries# do not all hit the provider at the same instant.@@ -521,7 +537,7 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):query_words = [w for w in query.lower().split() if len(w) > 1]if query_words:- from sqlalchemy import or_, func, case, literal+ from sqlalchemy import or_, case# Filter: match ANY keyword (OR) to get candidatestext_conditions = []@@ -529,15 +545,45 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):text_conditions.append(TranscriptChunk.content.ilike(f'%{word}%'))chunks_query = chunks_query.filter(or_(*text_conditions))- # Fetch more candidates than needed so we can rank them- chunks = chunks_query.limit(top_k * 5).all()-- # Rank by how many query words each chunk matches+ # Rank IN SQL before limiting. The previous code applied+ # LIMIT before any ranking, so with a common word in the query+ # ("rate", "team") the candidate set filled up with arbitrary+ # low-id chunks and the actually-relevant chunks never entered+ # the ranking at all. Score = number of matched words, with the+ # full phrase counting double so exact-phrase hits always+ # outrank scattered single-word matches.+ score_expr = sum(+ case((TranscriptChunk.content.ilike(f'%{word}%'), 1), else_=0)+ for word in query_words+ )+ phrase = query.lower().strip()+ if len(query_words) > 1 and len(phrase) >= 5:+ score_expr = score_expr + case(+ (TranscriptChunk.content.ilike(f'%{phrase}%'), len(query_words)),+ else_=0,+ )+ chunks = (chunks_query+ .order_by(score_expr.desc(), TranscriptChunk.id.desc())+ .limit(top_k * 5)+ .all())++ # Refine in Python over the now well-chosen candidates: exact+ # word-boundary matches beat substring matches ("rate" inside+ # "separate"), and phrase presence keeps its bonus.scored_chunks = []for chunk in chunks:content_lower = chunk.content.lower()- match_count = sum(1 for word in query_words if word in content_lower)- score = match_count / len(query_words) # 0.0 to 1.0+ match_count = 0.0+ for word in query_words:+ if re.search(r'\b' + re.escape(word) + r'\b', content_lower):+ match_count += 1.0+ elif word in content_lower:+ match_count += 0.5+ if len(query_words) > 1 and phrase in content_lower:+ match_count += len(query_words)+ # Full word-boundary matches on every word score 1.0; the+ # phrase bonus only breaks ties above, capped back to 1.0.+ score = min(match_count / len(query_words), 1.0)scored_chunks.append((chunk, score))# Sort by score descending, take top_kdiff --git a/src/services/inquire_agent.py b/src/services/inquire_agent.pyindex 26a209e4..c91e4148 100644--- a/src/services/inquire_agent.py+++ b/src/services/inquire_agent.py@@ -27,7 +27,11 @@ from datetime import datetime, time as dtimefrom src.database import dbfrom src.models import Recording, RecordingTag, Tag, User-from src.services.embeddings import get_accessible_recording_ids, semantic_search_chunks+from src.services.embeddings import (+ get_accessible_recording_ids,+ semantic_search_chunks,+ basic_text_search_chunks,+)from src.services.llm import call_chat_completion, TokenBudgetExceeded, get_chat_config# ---------------------------------------------------------------------------@@ -225,7 +229,10 @@ def tool_search_transcripts(ctx, args):query = (args.get('query') or '').strip()if not query:return {'error': "query is required"}- top_k = min(max(int(args.get('top_k', 8) or 8), 1), 20)+ top_k = min(max(int(args.get('top_k', 8) or 8), 1), 40)+ mode = str(args.get('mode', 'auto') or 'auto').lower()+ if mode not in ('auto', 'semantic', 'keyword'):+ mode = 'auto'# Narrow within the UI filters: tool args can only tighten, never widen.filters = dict(ctx.filters)@@ -245,9 +252,25 @@ def tool_search_transcripts(ctx, args):except ValueError:return {'error': f"{arg} must be an ISO date (YYYY-MM-DD)"}- results = semantic_search_chunks(ctx.user_id, query, filters, top_k)+ if mode == 'keyword':+ results = basic_text_search_chunks(ctx.user_id, query, filters, top_k)+ search_type = 'keyword'+ else:+ results = semantic_search_chunks(ctx.user_id, query, filters, top_k)+ search_type = 'semantic'+ # Semantic misses are not proof of absence: exact terms, acronyms and+ # rare tokens ("MR rate") can rank poorly in embedding space (and the+ # embedding API may be degraded). In auto mode, back an empty or thin+ # semantic result with a literal keyword pass over the same scope.+ if mode == 'auto' and len(results) < 2:+ keyword_results = basic_text_search_chunks(ctx.user_id, query, filters, top_k)+ if keyword_results:+ seen = {c.id for c, _s in results if c}+ results = list(results) + [(c, s) for c, s in keyword_results if c and c.id not in seen]+ search_type = 'semantic+keyword'+hits = []- for chunk, similarity in results:+ for chunk, similarity in results[:top_k]:if not chunk or not chunk.recording or chunk.recording_id not in ctx.allowed_ids:continuehits.append({@@ -260,7 +283,7 @@ def tool_search_transcripts(ctx, args):'snippet': chunk.content,'similarity': round(float(similarity), 3),})- return {'query': query, 'result_count': len(hits), 'results': hits}+ return {'query': query, 'search_type': search_type, 'result_count': len(hits), 'results': hits}def tool_list_recordings(ctx, args):@@ -384,13 +407,19 @@ def build_toolbox(availability):"""tools = [('search_transcripts', tool_search_transcripts,- 'Semantic search across the transcripts of the recordings in scope. '- 'Returns matching snippets with recording ids, titles, speakers and timestamps. '- 'Use short, content-bearing queries; call multiple times with different phrasings if needed.',+ 'Search the transcripts of the recordings in scope. Default mode combines semantic search '+ 'with a literal keyword fallback when semantic results are thin. Returns matching snippets '+ 'with recording ids, titles, speakers and timestamps. Use short, content-bearing queries; '+ 'call multiple times with different phrasings. For exact terms, acronyms or jargon '+ '(project names, metric names), also try mode="keyword" with just that term. Raise top_k '+ 'when surveying a topic broadly.',{'type': 'object','properties': {'query': {'type': 'string', 'description': 'Search phrase'},- 'top_k': {'type': 'integer', 'description': 'Max results, 1-20 (default 8)'},+ 'top_k': {'type': 'integer', 'description': 'Max results, 1-40 (default 8)'},+ 'mode': {'type': 'string', 'enum': ['auto', 'semantic', 'keyword'],+ 'description': 'auto (default): semantic with keyword fallback; '+ 'keyword: literal word/phrase matching only'},'speakers': {'type': 'array', 'items': {'type': 'string'},'description': 'Restrict to recordings whose participants include these names'},**_DATE_PROPS,@@ -482,7 +511,11 @@ def _activity_result(tool, result):if not n:return 'empty', 'no matches'recs = {r['recording_id'] for r in result.get('results', [])}- return 'done', f"{n} match{'es' if n != 1 else ''} in {len(recs)} recording{'s' if len(recs) != 1 else ''}"+ detail = f"{n} match{'es' if n != 1 else ''} in {len(recs)} recording{'s' if len(recs) != 1 else ''}"+ stype = result.get('search_type')+ if stype and stype != 'semantic':+ detail += f" ({stype.replace('semantic+keyword', 'incl. keyword')})"+ return 'done', detailif tool == 'list_recordings':return 'done', f"{result.get('returned', 0)} of {result.get('total_in_scope', 0)} recordings"if tool == 'get_transcript':diff --git a/templates/inquire.html b/templates/inquire.htmlindex 2082152c..89727482 100644--- a/templates/inquire.html+++ b/templates/inquire.html@@ -152,9 +152,14 @@border-radius: 9999px;padding: 0 0.55em;font-size: 0.78em;- line-height: 1.6;+ line-height: 1.55;text-decoration: none;- vertical-align: baseline;+ /* Sit on the text line instead of riding above it: an+ inline-block chip aligned to baseline extends mostly upward+ because of its padding, so nudge it down to visually centre+ against the surrounding line. */+ vertical-align: -0.35em;+ margin: 0 0.1em;max-width: 100%;overflow: hidden;text-overflow: ellipsis;diff --git a/tests/test_inquire_agent.py b/tests/test_inquire_agent.pyindex 555d39a4..18a13b3c 100644--- a/tests/test_inquire_agent.py+++ b/tests/test_inquire_agent.py@@ -278,6 +278,92 @@ def test_search_tool_scopes_and_shapes(data, monkeypatch):assert hit['recording_id'] == data['r1'] and hit['time'] == '1:03'+def test_search_tool_modes_and_keyword_fallback(data, monkeypatch):+ with app.app_context():+ r1 = db.session.get(Recording, data['r1'])+ kw_chunk = NS(id=990001, recording_id=r1.id, recording=r1, speaker_name='Bob',+ start_time=10.0, chunk_index=1, content='the MR rate improved')+ sem_calls, kw_calls = [], []+ monkeypatch.setattr(ia, 'semantic_search_chunks',+ lambda uid, q, f, k: sem_calls.append(q) or [])+ monkeypatch.setattr(ia, 'basic_text_search_chunks',+ lambda uid, q, f, k: kw_calls.append(q) or [(kw_chunk, 0.9)])+ ctx = ia.ToolContext(data['owner'], {}, {data['r1']}, {'summaries': True, 'notes': False})++ # auto: semantic empty -> keyword fallback kicks in+ res = ia.tool_search_transcripts(ctx, {'query': 'MR rate'})+ assert res['search_type'] == 'semantic+keyword'+ assert res['result_count'] == 1 and sem_calls and kw_calls++ # keyword mode: semantic never called+ sem_calls.clear(); kw_calls.clear()+ res = ia.tool_search_transcripts(ctx, {'query': 'MR rate', 'mode': 'keyword'})+ assert res['search_type'] == 'keyword'+ assert not sem_calls and kw_calls++ # semantic mode: no fallback even when empty+ sem_calls.clear(); kw_calls.clear()+ res = ia.tool_search_transcripts(ctx, {'query': 'MR rate', 'mode': 'semantic'})+ assert res['search_type'] == 'semantic' and res['result_count'] == 0+ assert sem_calls and not kw_calls+++def test_basic_text_search_ranks_before_limiting(data):+ """The pre-fix code applied LIMIT before ranking, so a rare phrase in a+ high-id chunk lost to arbitrary low-id chunks matching one common word."""+ from src.services.embeddings import basic_text_search_chunks+ from src.models import TranscriptChunk+ with app.app_context():+ made = []+ # 60 decoys that only match the common word "rate", created FIRST so+ # they occupy the low-id region the old code's LIMIT would grab.+ for i in range(60):+ c = TranscriptChunk(recording_id=data['r2'], user_id=data['owner'],+ chunk_index=1000 + i,+ content=f'the interest rate discussion item {i}')+ db.session.add(c)+ made.append(c)+ target = TranscriptChunk(recording_id=data['r1'], user_id=data['owner'],+ chunk_index=2000,+ content='we reviewed the MR rate for the SEC team')+ db.session.add(target)+ made.append(target)+ db.session.commit()+ try:+ results = basic_text_search_chunks(data['owner'], 'MR rate', None, 8)+ assert results, 'expected matches'+ top_chunk, top_score = results[0]+ assert top_chunk.id == target.id, 'phrase match must outrank single-word decoys'+ assert top_score > results[-1][1] or len(results) == 1+ finally:+ for c in made:+ db.session.delete(c)+ db.session.commit()+++def test_api_embed_cooldown(monkeypatch):+ from src.services import embeddings as emb+ with app.app_context():+ calls = []+ class BoomClient:+ class embeddings:+ @staticmethod+ def create(**kw):+ calls.append(1)+ raise RuntimeError('auth failure') # non-transient: fails fast+ monkeypatch.setattr(emb, 'get_embedding_api_client', lambda: BoomClient)+ emb._api_embed_down_until = 0+ try:+ assert emb._api_embed(['x']) == []+ assert len(calls) == 1+ assert emb._api_embed_down_until > 0+ # During cooldown the client is not touched at all+ assert emb._api_embed(['y']) == []+ assert len(calls) == 1+ finally:+ emb._api_embed_down_until = 0++def test_truncation_marker():text = 'x' * 100000out = ia._truncate_to_tokens(text, 100, 'More available.')