Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Chat sources and a v1 Inquire (mailr spec G9); one chat prompt for the web app and API v1 (#412 C1)
Murtaza Nasir8d456538d015
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex 6c601bce..7fc5080b 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -1357,6 +1357,68 @@ Ask questions about a recording's content using AI.}```+**Sources.** With `"with_sources": true`, the transcript goes to the model with segment markers and the answer cites segments with short quotes. Citations in `response` become `[1]`, `[2]`, and `sources` lists them:++```json+{+ "response": "The freeze covers travel only [1].",+ "sources": [{"n": 1, "segment_index": 12, "start_time": 754.2, "end_time": 761.0,+ "speaker": "Dana", "quote": "the budget freeze applies to travel only", "verified": true}]+}+```++`verified` is `true` when the quote appears in that segment (ignoring case and spacing). A citation of a segment that does not exist has `segment_index: null` and `verified: false`.++The notes in the chat context are the ones you can see: your own for your recordings, your personal notes for a recording shared with you. Chat sends the transcript to the chat model of the instance; `GET /api/v1/capabilities` reports `models_local`.++---++## Inquire++### Ask Across Recordings++```http+POST /api/v1/inquire+```++**Scope:** `process`++Answers a question from the recordings you can read, with Inquire's search (and the Inquire agent when the administrator turned it on). Needs Inquire mode on the instance (`403 feature_disabled` otherwise).++```json+{+ "question": "What did we decide about the course redesign?",+ "filters": {"recording_ids": [412, 398], "tag_ids": [], "speakers": [], "date_from": "2026-09-01", "date_to": null},+ "scope": "own",+ "mode": "auto",+ "stream": false,+ "history": []+}+```++- `mode`: `rag`, `agent` (`403 feature_disabled` when the agent is off) or `auto` (the agent when it is on).+- `scope`: `own`, `shared` or `all`, as on [List Recordings](#list-recordings).+- `stream: true` returns the server-sent events of the web app's Inquire (`delta`, `status`, `agent_step`, `agent_summary`, `error`).++**Response** (`stream: false`):++```json+{+ "answer": "The redesign moves the project to week 6 [1] and drops the midterm [2].",+ "citations": [+ {"n": 1, "recording_id": 412, "title": "Weekly sync", "start_time": 754, "quote": null,+ "url": "/recordings/412?t=754"},+ {"n": 2, "recording_id": 398, "title": "Budget review", "start_time": null, "quote": null,+ "url": "/recordings/398"}+ ],+ "mode_used": "agent",+ "steps": 4,+ "usage": null+}+```++Every citation names a recording you can read. The question and the matching transcript passages go to the instance's chat model.+---## Eventsdiff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 296fd4c7..b3f017dc 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -924,6 +924,7 @@ CAPABILITY_FEATURES = {'external_refs': True,'upload_idempotency': True,'share_links': True,+ 'chat_sources': True,}# search: {'keyword': True, 'semantic': <Inquire on>} is filled in get_capabilities.@@ -3133,10 +3134,10 @@ def start_summarization(recording_id):@require_scope('process')@login_requireddef chat_with_recording(recording_id):- """Chat about a recording's content."""+ """Chat about a recording's content. with_sources: true returns numbered+ sources with segment, time, speaker and a checked quote (mailr spec G9)."""from src.services.llm import chat_client, call_chat_completion- from src.tasks.processing import format_transcription_for_llm, _resolve_timestamp_template_format- from src.models import SystemSetting+ from src.services.recording_chat import build_chat_messages, parse_sourcesrecording = db.session.get(Recording, recording_id)if not recording:@@ -3152,61 +3153,125 @@ def chat_with_recording(recording_id):if not data or not data.get('message'):return jsonify({'error': 'message is required'}), 400- user_message = data['message']- conversation_history = data.get('conversation_history', [])+ with_sources = data.get('with_sources', False)+ if not isinstance(with_sources, bool):+ return jsonify({'error': 'with_sources must be true or false', 'code': 'invalid_parameter'}), 400# Check if chat client is availableif chat_client is None:return jsonify({'error': 'Chat service not available'}), 503- # Format transcription (optionally with timestamps per the user's setting, #304)- _chat_ts = bool(current_user.chat_include_timestamps)- formatted_transcription = format_transcription_for_llm(- recording.transcription,- include_timestamps=_chat_ts,- template_format=_resolve_timestamp_template_format(- current_user, current_user.chat_timestamp_template_id) if _chat_ts else None,- )-- # Get transcript limit- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)- if transcript_limit != -1:- formatted_transcription = formatted_transcription[:transcript_limit]-- # Build system prompt- system_prompt = f"""You are a helpful assistant analyzing a recording. Answer questions based on the transcript below.--Meeting: {recording.title}-Participants: {recording.participants or 'Not specified'}--Transcript:-{formatted_transcription}--Notes: {recording.notes or 'None'}-"""- # Same output language as web chat (#412 audit S8).- if current_user.output_language:- system_prompt += f"\nPlease provide all your responses in {current_user.output_language}.\n"-- # Build messages- messages = [{"role": "system", "content": system_prompt}]- messages.extend(conversation_history)- messages.append({"role": "user", "content": user_message})-+ messages, segments = build_chat_messages(recording, current_user, data['message'],+ data.get('conversation_history', []), with_sources=with_sources)try:- # Same admin chat temperature as web chat (#412 audit S8).from src.services.llm_settings import get_temperaturecompletion = call_chat_completion(messages, temperature=get_temperature('chat'), user_id=current_user.id)reply = completion.choices[0].message.content-- return jsonify({- 'response': reply,- 'sources': [] # Could be enhanced to extract relevant segments- })except Exception as e:current_app.logger.error(f"Chat error: {e}")return jsonify({'error': 'Chat failed'}), 500+ sources = []+ if with_sources and segments:+ reply, sources = parse_sources(reply, segments)+ return jsonify({'response': reply, 'sources': sources})+++@api_v1_bp.route('/inquire', methods=['POST'])+@require_scope('process')+@login_required+def inquire_v1():+ """Ask a question across recordings (mailr spec G9).++ Body: question, filters {recording_ids, tag_ids, speakers, date_from,+ date_to}, scope (own|shared|all), mode (rag|agent|auto), stream, history.+ """+ import re as _re+ from flask import Response, stream_with_context+ from src.api.inquire import inquire_stream+ from src.services.inquire_agent import agent_enabled+ from src.services.recording_scope import scope_condition+ if os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() != 'true':+ return jsonify({'error': 'Inquire is turned off on this server', 'code': 'feature_disabled'}), 403+ body = request.get_json(silent=True) or {}+ question = (body.get('question') or '').strip()+ if not question:+ return jsonify({'error': 'question is required', 'code': 'invalid_parameter'}), 400+ mode = body.get('mode', 'auto')+ if mode not in ('rag', 'agent', 'auto'):+ return jsonify({'error': 'mode must be rag, agent or auto', 'code': 'invalid_parameter'}), 400+ if mode == 'agent' and not agent_enabled():+ return jsonify({'error': 'The Inquire agent is turned off on this server', 'code': 'feature_disabled'}), 403+ scope = body.get('scope', 'own')+ if scope not in ('own', 'shared', 'all'):+ return jsonify({'error': 'scope must be own, shared or all', 'code': 'invalid_parameter'}), 400+ filters = body.get('filters') or {}+ if not isinstance(filters, dict):+ return jsonify({'error': 'filters must be an object', 'code': 'invalid_parameter'}), 400++ allowed = [rid for (rid,) in db.session.query(Recording.id).filter(scope_condition(current_user.id, scope))]+ if filters.get('recording_ids'):+ wanted = {int(r) for r in filters['recording_ids'] if str(r).isdigit()}+ allowed = [rid for rid in allowed if rid in wanted]+ if not allowed:+ return jsonify({'answer': 'There are no recordings to search with these filters.', 'citations': [],+ 'mode_used': 'rag', 'steps': 0, 'usage': None})+ data = {+ 'message': question,+ 'message_history': body.get('history') or [],+ 'filter_recording_ids': allowed,+ 'filter_tags': filters.get('tag_ids') or [],+ 'filter_speakers': filters.get('speakers') or [],+ 'filter_date_from': filters.get('date_from'),+ 'filter_date_to': filters.get('date_to'),+ }+ mode_used = 'agent' if (mode != 'rag' and agent_enabled()) else 'rag'+ stream = inquire_stream(current_user, data, mode=mode)+ if body.get('stream'):+ return Response(stream_with_context(stream), mimetype='text/event-stream')++ answer, steps, error = [], 0, None+ for chunk in stream:+ for line in str(chunk).splitlines():+ if not line.startswith('data: '):+ continue+ try:+ event = json.loads(line[6:])+ except ValueError:+ continue+ if isinstance(event.get('delta'), str):+ answer.append(event['delta'])+ if 'error' in event:+ error = event['error']+ summary = event.get('agent_summary')+ if isinstance(summary, dict) and isinstance(summary.get('steps'), int):+ steps = summary['steps']+ text = ''.join(answer)+ if error and not text:+ return jsonify({'error': error, 'code': 'inquire_failed'}), 502++ # [Title @ 12:34](/recordings/412?t=754) -> [1], for recordings the caller can read.+ readable = set(allowed)+ citations, numbers = [], {}+ link = _re.compile(r'\[([^\]]+)\]\(/recordings/(\d+)(?:\?t=(\d+(?:\.\d+)?))?\)')++ def _cite(match):+ rid = int(match.group(2))+ if rid not in readable:+ return match.group(1)+ t = float(match.group(3)) if match.group(3) else None+ key = (rid, t)+ if key not in numbers:+ rec = db.session.get(Recording, rid)+ numbers[key] = len(citations) + 1+ citations.append({'n': numbers[key], 'recording_id': rid, 'title': rec.title if rec else None,+ 'start_time': t, 'quote': None,+ 'url': f'/recordings/{rid}' + (f'?t={match.group(3)}' if match.group(3) else '')})+ return f'[{numbers[key]}]'++ text = link.sub(_cite, text)+ return jsonify({'answer': text, 'citations': citations, 'mode_used': mode_used, 'steps': steps, 'usage': None})+# =============================================================================# Calendar Eventsdiff --git a/src/api/inquire.py b/src/api/inquire.pyindex c17b731d..82111e96 100644--- a/src/api/inquire.py+++ b/src/api/inquire.py@@ -9,7 +9,7 @@ import jsonimport reimport timefrom datetime import datetime, timedelta-from src.utils.timezones import to_user_local, user_timezone+from src.utils.timezones import to_local, user_timezonefrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_appfrom flask_login import login_required, current_userfrom werkzeug.utils import secure_filename@@ -169,71 +169,61 @@ def inquire_search():-@inquire_bp.route('/api/inquire/chat', methods=['POST'])-@login_required-def inquire_chat():- """Chat with filtered transcriptions using RAG."""- if not ENABLE_INQUIRE_MODE:- return jsonify({'error': 'Inquire mode is not enabled'}), 403- try:- data = request.json- if not data:- return jsonify({'error': 'No data provided'}), 400-- user_message = data.get('message')- message_history = data.get('message_history', [])-- if not user_message:- return jsonify({'error': 'No message provided'}), 400-- # Check if OpenRouter client is available- if client is None:- return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503-- # Build filters from request- filters = {}- if data.get('filter_tags'):- filters['tag_ids'] = data['filter_tags']- if data.get('filter_speakers'):- filters['speaker_names'] = data['filter_speakers']- if data.get('filter_recording_ids'):- filters['recording_ids'] = data['filter_recording_ids']- if data.get('filter_date_from'):- filters['date_from'] = datetime.fromisoformat(data['filter_date_from']).date()- if data.get('filter_date_to'):- filters['date_to'] = datetime.fromisoformat(data['filter_date_to']).date()-- # Debug logging- current_app.logger.info(f"Inquire chat - User: {current_user.username}, Query: '{user_message}', Filters: {filters}")-- # Capture user context and app before generator to avoid context issues- user_id = current_user.id- user_name = current_user.name if current_user.name else "the user"- user_title = current_user.job_title if current_user.job_title else "professional"- user_company = current_user.company if current_user.company else "their organization"- user_output_language = current_user.output_language if current_user.output_language else None- app = current_app._get_current_object() # Capture app for use in generator-- # Enhanced query processing with enrichment and debugging- def create_status_response(status, message):- """Helper to create SSE status updates"""- return f"data: {json.dumps({'status': status, 'message': message})}\n\n"-- def generate_enhanced_chat():- # Explicitly reference outer scope variables- nonlocal user_id, user_name, user_title, user_company, user_output_language, data, filters-- # Push app context for entire generator execution- # This is needed because call_llm_completion uses current_app.logger internally- ctx = app.app_context()- ctx.push()-- try:- # Send initial status- yield create_status_response('processing', 'Analyzing your query...')-- # Step 1: Router - Determine if RAG lookup is needed- router_prompt = f"""Analyze this user query to determine if it requires searching through transcription content or if it's a simple formatting/clarification request.+def inquire_stream(user, data, mode='auto'):+ """The Inquire answer as an SSE generator, for the web route and API v1.++ data: message, message_history, conversation_memory, filter_tags,+ filter_speakers, filter_recording_ids, filter_date_from, filter_date_to.+ mode: 'auto' (the agent when ENABLE_INQUIRE_AGENT is on), 'rag' or+ 'agent' (the caller checks that the agent is on).+ """+ user_message = data.get('message')+ message_history = data.get('message_history', [])+ # Build filters from request+ filters = {}+ if data.get('filter_tags'):+ filters['tag_ids'] = data['filter_tags']+ if data.get('filter_speakers'):+ filters['speaker_names'] = data['filter_speakers']+ if data.get('filter_recording_ids'):+ filters['recording_ids'] = data['filter_recording_ids']+ if data.get('filter_date_from'):+ filters['date_from'] = datetime.fromisoformat(data['filter_date_from']).date()+ if data.get('filter_date_to'):+ filters['date_to'] = datetime.fromisoformat(data['filter_date_to']).date()++ # Debug logging+ current_app.logger.info(f"Inquire chat - User: {user.username}, Query: '{user_message}', Filters: {filters}")++ # Capture user context and app before generator to avoid context issues+ user_id = user.id+ user_zone = user_timezone(user) # read here: the stream runs without the request+ user_name = user.name if user.name else "the user"+ user_title = user.job_title if user.job_title else "professional"+ user_company = user.company if user.company else "their organization"+ user_output_language = user.output_language if user.output_language else None+ app = current_app._get_current_object() # Capture app for use in generator++ # Enhanced query processing with enrichment and debugging+ def create_status_response(status, message):+ """Helper to create SSE status updates"""+ return f"data: {json.dumps({'status': status, 'message': message})}\n\n"++ def generate_enhanced_chat():+ # Explicitly reference outer scope variables+ nonlocal user_id, user_name, user_title, user_company, user_output_language, data, filters++ # Push app context for entire generator execution+ # This is needed because call_llm_completion uses current_app.logger internally+ ctx = app.app_context()+ ctx.push()++ try:+ # Send initial status+ yield create_status_response('processing', 'Analyzing your query...')++ # Step 1: Router - Determine if RAG lookup is needed+ router_prompt = f"""Analyze this user query to determine if it requires searching through transcription content or if it's a simple formatting/clarification request.User query: "{user_message}"@@ -246,31 +236,31 @@ Examples:- "Who mentioned the timeline?" → RAG- "Make this more structured" → DIRECT"""- try:- router_response = call_llm_completion(- messages=[- {"role": "system", "content": "You are a query router. Respond with only 'RAG' or 'DIRECT'."},- {"role": "user", "content": router_prompt}- ],- temperature=0.1,- max_tokens=10,- user_id=user_id,- operation_type='query_routing'- )+ try:+ router_response = call_llm_completion(+ messages=[+ {"role": "system", "content": "You are a query router. Respond with only 'RAG' or 'DIRECT'."},+ {"role": "user", "content": router_prompt}+ ],+ temperature=0.1,+ max_tokens=10,+ user_id=user_id,+ operation_type='query_routing'+ )- raw_decision = router_response.choices[0].message.content- if not raw_decision or not raw_decision.strip():- app.logger.warning("Router returned empty response, defaulting to RAG")- raise ValueError("Empty router response")+ raw_decision = router_response.choices[0].message.content+ if not raw_decision or not raw_decision.strip():+ app.logger.warning("Router returned empty response, defaulting to RAG")+ raise ValueError("Empty router response")- route_decision = raw_decision.strip().upper()- app.logger.info(f"Router decision: {route_decision}")+ route_decision = raw_decision.strip().upper()+ app.logger.info(f"Router decision: {route_decision}")- if route_decision == "DIRECT":- # Direct response without RAG lookup- yield create_status_response('responding', 'Generating direct response...')+ if route_decision == "DIRECT":+ # Direct response without RAG lookup+ yield create_status_response('responding', 'Generating direct response...')- direct_prompt = f"""You are assisting {user_name}. Respond to their request directly using proper markdown formatting.+ direct_prompt = f"""You are assisting {user_name}. Respond to their request directly using proper markdown formatting.User request: "{user_message}"@@ -279,33 +269,33 @@ Previous conversation context (if relevant):Use proper markdown formatting including headings (##), bold (**text**), bullet points (-), etc."""- stream = call_llm_completion(- messages=[- {"role": "system", "content": direct_prompt},- {"role": "user", "content": user_message}- ],- temperature=0.7,- max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),- stream=True,- user_id=user_id,- operation_type='chat'- )-- # Use helper function to process streaming with thinking tag support- for response in process_streaming_with_thinking(stream, user_id=user_id, operation_type='chat', model_name=os.environ.get('LLM_MODEL')):- yield response- return-- except Exception as e:- app.logger.warning(f"Router failed, defaulting to RAG: {e}")-- # Step 2: Query enrichment - generate better search terms based on user intent- yield create_status_response('enriching', 'Enriching search query...')-- # Use captured user context for personalized search terms-- if EMBEDDINGS_AVAILABLE:- enrichment_prompt = f"""You are a query enhancement assistant. Given a user's question about transcribed meetings/recordings, generate 3-5 alternative search terms or phrases that would help find relevant content in a semantic search system.+ stream = call_llm_completion(+ messages=[+ {"role": "system", "content": direct_prompt},+ {"role": "user", "content": user_message}+ ],+ temperature=0.7,+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),+ stream=True,+ user_id=user_id,+ operation_type='chat'+ )++ # Use helper function to process streaming with thinking tag support+ for response in process_streaming_with_thinking(stream, user_id=user_id, operation_type='chat', model_name=os.environ.get('LLM_MODEL')):+ yield response+ return++ except Exception as e:+ app.logger.warning(f"Router failed, defaulting to RAG: {e}")++ # Step 2: Query enrichment - generate better search terms based on user intent+ yield create_status_response('enriching', 'Enriching search query...')++ # Use captured user context for personalized search terms++ if EMBEDDINGS_AVAILABLE:+ enrichment_prompt = f"""You are a query enhancement assistant. Given a user's question about transcribed meetings/recordings, generate 3-5 alternative search terms or phrases that would help find relevant content in a semantic search system.User context:- Name: {user_name}@@ -327,8 +317,8 @@ Examples:- Use their job title and company context when relevantRespond with only a JSON array of strings: ["term1", "term2", "term3", ...]"""- else:- enrichment_prompt = f"""You are a keyword extraction assistant. Given a user's question about transcribed meetings/recordings, extract 3-5 essential keyword phrases for a basic text search (SQL LIKE matching, not semantic search).+ else:+ enrichment_prompt = f"""You are a keyword extraction assistant. Given a user's question about transcribed meetings/recordings, extract 3-5 essential keyword phrases for a basic text search (SQL LIKE matching, not semantic search).User context:- Name: {user_name}@@ -348,272 +338,272 @@ Examples:- "what did we discuss about AI foresight" → ["AI foresight", "{user_name}", "foresight"]Respond with only a JSON array of strings: ["term1", "term2", ...]"""-- try:- enrichment_response = call_llm_completion(- messages=[- {"role": "system", "content": "You are a query enhancement assistant. Respond only with valid JSON arrays of search terms."},- {"role": "user", "content": enrichment_prompt}- ],- temperature=0.3,- max_tokens=200,- user_id=user_id,- operation_type='query_enrichment'- )++ try:+ enrichment_response = call_llm_completion(+ messages=[+ {"role": "system", "content": "You are a query enhancement assistant. Respond only with valid JSON arrays of search terms."},+ {"role": "user", "content": enrichment_prompt}+ ],+ temperature=0.3,+ max_tokens=200,+ user_id=user_id,+ operation_type='query_enrichment'+ )- raw_content = enrichment_response.choices[0].message.content- if not raw_content or not raw_content.strip():- app.logger.warning(f"Query enrichment returned empty response")- raise ValueError("Empty response from LLM")+ raw_content = enrichment_response.choices[0].message.content+ if not raw_content or not raw_content.strip():+ app.logger.warning(f"Query enrichment returned empty response")+ raise ValueError("Empty response from LLM")- # Try to extract JSON array if wrapped in other text- content = raw_content.strip()- if content.startswith('['):- enriched_terms = json.loads(content)+ # Try to extract JSON array if wrapped in other text+ content = raw_content.strip()+ if content.startswith('['):+ enriched_terms = json.loads(content)+ else:+ # Try to find JSON array in the response+ match = re.search(r'\[.*?\]', content, re.DOTALL)+ if match:+ enriched_terms = json.loads(match.group())else:- # Try to find JSON array in the response- match = re.search(r'\[.*?\]', content, re.DOTALL)- if match:- enriched_terms = json.loads(match.group())- else:- app.logger.warning(f"Query enrichment response not JSON: {content[:200]}")- raise ValueError("No JSON array found in response")+ app.logger.warning(f"Query enrichment response not JSON: {content[:200]}")+ raise ValueError("No JSON array found in response")- app.logger.info(f"Enriched search terms: {enriched_terms}")-- # Combine original query with enriched terms for search- search_queries = [user_message] + enriched_terms[:3] # Use original + top 3 enriched terms-- except Exception as e:- app.logger.warning(f"Query enrichment failed, using original query: {e}")- search_queries = [user_message]-- # Step 2: Semantic search with multiple queries- yield create_status_response('searching', 'Searching transcriptions...')+ app.logger.info(f"Enriched search terms: {enriched_terms}")- all_chunks = []- seen_chunk_ids = set()+ # Combine original query with enriched terms for search+ search_queries = [user_message] + enriched_terms[:3] # Use original + top 3 enriched terms- for query in search_queries:- with app.app_context():- chunk_results = semantic_search_chunks(user_id, query, filters, 8)- app.logger.info(f"Search query '{query}' returned {len(chunk_results)} chunks")-- for chunk, similarity in chunk_results:- if chunk and chunk.id not in seen_chunk_ids:- all_chunks.append((chunk, similarity))- seen_chunk_ids.add(chunk.id)-- # Sort by similarity and take top results- all_chunks.sort(key=lambda x: x[1], reverse=True)- chunk_results = all_chunks[:data.get('context_chunks', 8)]-- app.logger.info(f"Final chunk results: {len(chunk_results)} chunks with similarities: {[f'{s:.3f}' for _, s in chunk_results]}")-- # Step 2.5: Auto-detect mentioned speakers and apply filters if needed+ except Exception as e:+ app.logger.warning(f"Query enrichment failed, using original query: {e}")+ search_queries = [user_message]++ # Step 2: Semantic search with multiple queries+ yield create_status_response('searching', 'Searching transcriptions...')++ all_chunks = []+ seen_chunk_ids = set()++ for query in search_queries:with app.app_context():- # Get available speakers- recordings_with_participants = Recording.query.filter_by(user_id=user_id).filter(- Recording.participants.isnot(None),- Recording.participants != ''- ).all()-- available_speakers = set()- for recording in recordings_with_participants:- if recording.participants:- participants = [p.strip() for p in recording.participants.split(',') if p.strip()]- available_speakers.update(participants)-- # Check if any speakers are mentioned in the user query but missing from results- mentioned_speakers = []- for speaker in available_speakers:- if speaker.lower() in user_message.lower():- # Check if this speaker appears in current chunk results- speaker_in_results = False- for chunk, _ in chunk_results:- if chunk and (- (chunk.speaker_name and speaker.lower() in chunk.speaker_name.lower()) or- (chunk.recording and chunk.recording.participants and speaker.lower() in chunk.recording.participants.lower())- ):- speaker_in_results = True- break-- if not speaker_in_results:- mentioned_speakers.append(speaker)-- # If we found mentioned speakers not in results, automatically apply speaker filter- if mentioned_speakers and not data.get('filter_speakers'): # Only if no speaker filter already applied- app.logger.info(f"Auto-detected mentioned speakers not in results: {mentioned_speakers}")- yield create_status_response('filtering', f'Detected mention of {", ".join(mentioned_speakers)}, applying speaker filter...')-- # Apply automatic speaker filter- auto_filters = filters.copy()- auto_filters['speaker_names'] = mentioned_speakers-- # Re-run semantic search with speaker filter- auto_filtered_chunks = []- auto_filtered_seen_ids = set()-- for query in search_queries:- with app.app_context():- auto_filtered_results = semantic_search_chunks(user_id, query, auto_filters, data.get('context_chunks', 8))- app.logger.info(f"Auto-filtered search for '{query}' with speakers {mentioned_speakers} returned {len(auto_filtered_results)} chunks")-- for chunk, similarity in auto_filtered_results:- if chunk and chunk.id not in auto_filtered_seen_ids:- auto_filtered_chunks.append((chunk, similarity))- auto_filtered_seen_ids.add(chunk.id)-- # If auto-filter found better results, use them- if len(auto_filtered_chunks) > 0:- auto_filtered_chunks.sort(key=lambda x: x[1], reverse=True)- chunk_results = auto_filtered_chunks[:data.get('context_chunks', 8)]- app.logger.info(f"Auto speaker filter found {len(chunk_results)} relevant chunks, using filtered results")- filters = auto_filters # Update filters for context building-- # Step 3: Evaluate results and re-query if needed- if len(chunk_results) < 2: # If we got very few results, try a broader search- yield create_status_response('requerying', 'Expanding search scope...')-- # Try without speaker filter if it was applied- broader_filters = filters.copy()- if 'speaker_names' in broader_filters:- del broader_filters['speaker_names']- app.logger.info("Retrying search without speaker filter...")-- for query in search_queries:- with app.app_context():- chunk_results_broader = semantic_search_chunks(user_id, query, broader_filters, 6)- for chunk, similarity in chunk_results_broader:- if chunk and chunk.id not in seen_chunk_ids:- all_chunks.append((chunk, similarity))- seen_chunk_ids.add(chunk.id)-- # Re-sort and limit- all_chunks.sort(key=lambda x: x[1], reverse=True)- chunk_results = all_chunks[:data.get('context_chunks', 8)]- app.logger.info(f"Broader search returned {len(chunk_results)} total chunks")-- # Build context from retrieved chunks- yield create_status_response('contextualizing', 'Building context...')-- # Group chunks by recording and organize properly- recording_chunks = {}- recording_ids_in_context = set()+ chunk_results = semantic_search_chunks(user_id, query, filters, 8)+ app.logger.info(f"Search query '{query}' returned {len(chunk_results)} chunks")for chunk, similarity in chunk_results:- if not chunk or not chunk.recording:- continue- recording_id = chunk.recording.id- recording_ids_in_context.add(recording_id)-- if recording_id not in recording_chunks:- recording_chunks[recording_id] = {- 'recording': chunk.recording,- 'chunks': []- }-- recording_chunks[recording_id]['chunks'].append({- 'chunk': chunk,- 'similarity': similarity- })+ if chunk and chunk.id not in seen_chunk_ids:+ all_chunks.append((chunk, similarity))+ seen_chunk_ids.add(chunk.id)++ # Sort by similarity and take top results+ all_chunks.sort(key=lambda x: x[1], reverse=True)+ chunk_results = all_chunks[:data.get('context_chunks', 8)]++ app.logger.info(f"Final chunk results: {len(chunk_results)} chunks with similarities: {[f'{s:.3f}' for _, s in chunk_results]}")++ # Step 2.5: Auto-detect mentioned speakers and apply filters if needed+ with app.app_context():+ # Get available speakers+ recordings_with_participants = Recording.query.filter_by(user_id=user_id).filter(+ Recording.participants.isnot(None),+ Recording.participants != ''+ ).all()++ available_speakers = set()+ for recording in recordings_with_participants:+ if recording.participants:+ participants = [p.strip() for p in recording.participants.split(',') if p.strip()]+ available_speakers.update(participants)- # Build organized context pieces- context_pieces = []+ # Check if any speakers are mentioned in the user query but missing from results+ mentioned_speakers = []+ for speaker in available_speakers:+ if speaker.lower() in user_message.lower():+ # Check if this speaker appears in current chunk results+ speaker_in_results = False+ for chunk, _ in chunk_results:+ if chunk and (+ (chunk.speaker_name and speaker.lower() in chunk.speaker_name.lower()) or+ (chunk.recording and chunk.recording.participants and speaker.lower() in chunk.recording.participants.lower())+ ):+ speaker_in_results = True+ break++ if not speaker_in_results:+ mentioned_speakers.append(speaker)- for recording_id, data in recording_chunks.items():- recording = data['recording']- chunks = data['chunks']+ # If we found mentioned speakers not in results, automatically apply speaker filter+ if mentioned_speakers and not data.get('filter_speakers'): # Only if no speaker filter already applied+ app.logger.info(f"Auto-detected mentioned speakers not in results: {mentioned_speakers}")+ yield create_status_response('filtering', f'Detected mention of {", ".join(mentioned_speakers)}, applying speaker filter...')- # Sort chunks by their index to maintain chronological order- chunks.sort(key=lambda x: x['chunk'].chunk_index)+ # Apply automatic speaker filter+ auto_filters = filters.copy()+ auto_filters['speaker_names'] = mentioned_speakers- # Build recording header with complete metadata- header = f"=== {recording.title} [Recording ID: {recording_id}] ==="- if recording.meeting_date:- header += f" ({to_user_local(recording.meeting_date, current_user).strftime('%Y-%m-%d %H:%M')})"+ # Re-run semantic search with speaker filter+ auto_filtered_chunks = []+ auto_filtered_seen_ids = set()- # Add participants information- if recording.participants:- participants_list = [p.strip() for p in recording.participants.split(',') if p.strip()]- header += f"\\nParticipants: {', '.join(participants_list)}"+ for query in search_queries:+ with app.app_context():+ auto_filtered_results = semantic_search_chunks(user_id, query, auto_filters, data.get('context_chunks', 8))+ app.logger.info(f"Auto-filtered search for '{query}' with speakers {mentioned_speakers} returned {len(auto_filtered_results)} chunks")++ for chunk, similarity in auto_filtered_results:+ if chunk and chunk.id not in auto_filtered_seen_ids:+ auto_filtered_chunks.append((chunk, similarity))+ auto_filtered_seen_ids.add(chunk.id)- context_piece = header + "\\n\\n"+ # If auto-filter found better results, use them+ if len(auto_filtered_chunks) > 0:+ auto_filtered_chunks.sort(key=lambda x: x[1], reverse=True)+ chunk_results = auto_filtered_chunks[:data.get('context_chunks', 8)]+ app.logger.info(f"Auto speaker filter found {len(chunk_results)} relevant chunks, using filtered results")+ filters = auto_filters # Update filters for context building++ # Step 3: Evaluate results and re-query if needed+ if len(chunk_results) < 2: # If we got very few results, try a broader search+ yield create_status_response('requerying', 'Expanding search scope...')++ # Try without speaker filter if it was applied+ broader_filters = filters.copy()+ if 'speaker_names' in broader_filters:+ del broader_filters['speaker_names']+ app.logger.info("Retrying search without speaker filter...")- # Process chunks and detect non-continuity- prev_chunk_index = None- for chunk_data in chunks:- chunk = chunk_data['chunk']- similarity = chunk_data['similarity']-- # Check for non-continuity- if prev_chunk_index is not None and chunk.chunk_index != prev_chunk_index + 1:- context_piece += "\\n[... gap in transcript - non-consecutive chunks ...]\\n\\n"-- # Add speaker information if available- speaker_info = ""- if chunk.speaker_name:- speaker_info = f"{chunk.speaker_name}: "- elif chunk.start_time is not None:- speaker_info = f"[{chunk.start_time:.1f}s]: "-- # Add timing info if available- timing_info = ""- if chunk.start_time is not None and chunk.end_time is not None:- timing_info = f" [{chunk.start_time:.1f}s-{chunk.end_time:.1f}s]"-- context_piece += f"{speaker_info}{chunk.content}{timing_info} (similarity: {similarity:.3f})\\n\\n"- prev_chunk_index = chunk.chunk_index+ for query in search_queries:+ with app.app_context():+ chunk_results_broader = semantic_search_chunks(user_id, query, broader_filters, 6)+ for chunk, similarity in chunk_results_broader:+ if chunk and chunk.id not in seen_chunk_ids:+ all_chunks.append((chunk, similarity))+ seen_chunk_ids.add(chunk.id)- context_pieces.append(context_piece)+ # Re-sort and limit+ all_chunks.sort(key=lambda x: x[1], reverse=True)+ chunk_results = all_chunks[:data.get('context_chunks', 8)]+ app.logger.info(f"Broader search returned {len(chunk_results)} total chunks")++ # Build context from retrieved chunks+ yield create_status_response('contextualizing', 'Building context...')++ # Group chunks by recording and organize properly+ recording_chunks = {}+ recording_ids_in_context = set()++ for chunk, similarity in chunk_results:+ if not chunk or not chunk.recording:+ continue+ recording_id = chunk.recording.id+ recording_ids_in_context.add(recording_id)- app.logger.info(f"Built context from {len(chunk_results)} chunks across {len(recording_chunks)} recordings")+ if recording_id not in recording_chunks:+ recording_chunks[recording_id] = {+ 'recording': chunk.recording,+ 'chunks': []+ }- # Generate response- yield create_status_response('responding', 'Generating response...')+ recording_chunks[recording_id]['chunks'].append({+ 'chunk': chunk,+ 'similarity': similarity+ })++ # Build organized context pieces+ context_pieces = []++ for recording_id, data in recording_chunks.items():+ recording = data['recording']+ chunks = data['chunks']- # Prepare system prompt- language_instruction = f"Please provide all your responses in {user_output_language}." if user_output_language else ""+ # Sort chunks by their index to maintain chronological order+ chunks.sort(key=lambda x: x['chunk'].chunk_index)- # Build filter description for context- filter_description = []- with app.app_context():- if data.get('filter_tags'):- tag_names = [tag.name for tag in Tag.query.filter(Tag.id.in_(data['filter_tags'])).all()]- filter_description.append(f"tags: {', '.join(tag_names)}")- if data.get('filter_speakers'):- filter_description.append(f"speakers: {', '.join(data['filter_speakers'])}")- if data.get('filter_date_from') or data.get('filter_date_to'):- date_range = []- if data.get('filter_date_from'):- date_range.append(f"from {data['filter_date_from']}")- if data.get('filter_date_to'):- date_range.append(f"to {data['filter_date_to']}")- filter_description.append(f"dates: {' '.join(date_range)}")+ # Build recording header with complete metadata+ header = f"=== {recording.title} [Recording ID: {recording_id}] ==="+ if recording.meeting_date:+ header += f" ({to_local(recording.meeting_date, user_zone).strftime('%Y-%m-%d %H:%M')})"- filter_text = f" (filtered by {'; '.join(filter_description)})" if filter_description else ""+ # Add participants information+ if recording.participants:+ participants_list = [p.strip() for p in recording.participants.split(',') if p.strip()]+ header += f"\\nParticipants: {', '.join(participants_list)}"- context_text = "\n\n".join(context_pieces) if context_pieces else "No relevant context found."+ context_piece = header + "\\n\\n"- # Get transcript length limit setting and available speakers- with app.app_context():- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ # Process chunks and detect non-continuity+ prev_chunk_index = None+ for chunk_data in chunks:+ chunk = chunk_data['chunk']+ similarity = chunk_data['similarity']++ # Check for non-continuity+ if prev_chunk_index is not None and chunk.chunk_index != prev_chunk_index + 1:+ context_piece += "\\n[... gap in transcript - non-consecutive chunks ...]\\n\\n"- # Get all available speakers for this user- recordings_with_participants = Recording.query.filter_by(user_id=user_id).filter(- Recording.participants.isnot(None),- Recording.participants != ''- ).all()+ # Add speaker information if available+ speaker_info = ""+ if chunk.speaker_name:+ speaker_info = f"{chunk.speaker_name}: "+ elif chunk.start_time is not None:+ speaker_info = f"[{chunk.start_time:.1f}s]: "- available_speakers = set()- for recording in recordings_with_participants:- if recording.participants:- participants = [p.strip() for p in recording.participants.split(',') if p.strip()]- available_speakers.update(participants)+ # Add timing info if available+ timing_info = ""+ if chunk.start_time is not None and chunk.end_time is not None:+ timing_info = f" [{chunk.start_time:.1f}s-{chunk.end_time:.1f}s]"- available_speakers = sorted(list(available_speakers))+ context_piece += f"{speaker_info}{chunk.content}{timing_info} (similarity: {similarity:.3f})\\n\\n"+ prev_chunk_index = chunk.chunk_index++ context_pieces.append(context_piece)++ app.logger.info(f"Built context from {len(chunk_results)} chunks across {len(recording_chunks)} recordings")++ # Generate response+ yield create_status_response('responding', 'Generating response...')++ # Prepare system prompt+ language_instruction = f"Please provide all your responses in {user_output_language}." if user_output_language else ""++ # Build filter description for context+ filter_description = []+ with app.app_context():+ if data.get('filter_tags'):+ tag_names = [tag.name for tag in Tag.query.filter(Tag.id.in_(data['filter_tags'])).all()]+ filter_description.append(f"tags: {', '.join(tag_names)}")+ if data.get('filter_speakers'):+ filter_description.append(f"speakers: {', '.join(data['filter_speakers'])}")+ if data.get('filter_date_from') or data.get('filter_date_to'):+ date_range = []+ if data.get('filter_date_from'):+ date_range.append(f"from {data['filter_date_from']}")+ if data.get('filter_date_to'):+ date_range.append(f"to {data['filter_date_to']}")+ filter_description.append(f"dates: {' '.join(date_range)}")++ filter_text = f" (filtered by {'; '.join(filter_description)})" if filter_description else ""++ context_text = "\n\n".join(context_pieces) if context_pieces else "No relevant context found."++ # Get transcript length limit setting and available speakers+ with app.app_context():+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)++ # Get all available speakers for this user+ recordings_with_participants = Recording.query.filter_by(user_id=user_id).filter(+ Recording.participants.isnot(None),+ Recording.participants != ''+ ).all()- system_prompt = f"""You are a professional meeting and audio transcription analyst assisting {user_name}, who is a(n) {user_title} at {user_company}. {language_instruction}+ available_speakers = set()+ for recording in recordings_with_participants:+ if recording.participants:+ participants = [p.strip() for p in recording.participants.split(',') if p.strip()]+ available_speakers.update(participants)++ available_speakers = sorted(list(available_speakers))++ system_prompt = f"""You are a professional meeting and audio transcription analyst assisting {user_name}, who is a(n) {user_title} at {user_company}. {language_instruction}You are analyzing transcriptions from multiple recordings{filter_text}. The following context has been retrieved based on semantic similarity to the user's question:@@ -656,186 +646,210 @@ Brief summary with **key points** highlighted...- Coordination needed for upcoming milestonesOrder your response with notes from the most recent meetings first. Always use proper markdown formatting and structure by source recording for maximum clarity and readability."""-- # Prepare messages array- messages = [{"role": "system", "content": system_prompt}]- if message_history:- messages.extend(message_history)- messages.append({"role": "user", "content": user_message})-- # Enable streaming- stream = call_chat_completion(- messages=messages,- temperature=0.7,- max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),- stream=True,- user_id=user_id,- operation_type='chat'- )-- # Buffer content to detect full transcript requests- response_buffer = ""++ # Prepare messages array+ messages = [{"role": "system", "content": system_prompt}]+ if message_history:+ messages.extend(message_history)+ messages.append({"role": "user", "content": user_message})++ # Enable streaming+ stream = call_chat_completion(+ messages=messages,+ temperature=0.7,+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),+ stream=True,+ user_id=user_id,+ operation_type='chat'+ )- # Buffer content to detect full transcript requests- response_buffer = ""- content_buffer = ""- in_thinking = False- thinking_buffer = ""-- for chunk in stream:- if not chunk.choices:- continue- content = chunk.choices[0].delta.content- if content:- response_buffer += content- content_buffer += content+ # Buffer content to detect full transcript requests+ response_buffer = ""++ # Buffer content to detect full transcript requests+ response_buffer = ""+ content_buffer = ""+ in_thinking = False+ thinking_buffer = ""++ for chunk in stream:+ if not chunk.choices:+ continue+ content = chunk.choices[0].delta.content+ if content:+ response_buffer += content+ content_buffer += content++ # Check if this is a full transcript request+ if response_buffer.strip().startswith("REQUEST_FULL_TRANSCRIPT:"):+ lines = response_buffer.split('\n')+ request_line = lines[0].strip()- # Check if this is a full transcript request- if response_buffer.strip().startswith("REQUEST_FULL_TRANSCRIPT:"):- lines = response_buffer.split('\n')- request_line = lines[0].strip()-- if ':' in request_line:- try:- recording_id = int(request_line.split(':')[1])- app.logger.info(f"Agent requested full transcript for recording {recording_id}")-- # Fetch full transcript- yield create_status_response('fetching', f'Retrieving full transcript for recording {recording_id}...')-- with app.app_context():- recording = db.session.get(Recording, recording_id)- if recording and recording.user_id == user_id and recording.transcription:- # Apply transcript length limit- if transcript_limit == -1:- full_transcript = recording.transcription- else:- full_transcript = recording.transcription[:transcript_limit]-- # Add full transcript to context- full_context = f"{context_text}\n\n<<FULL TRANSCRIPT - {recording.title}>>\n{full_transcript}\n<<END FULL TRANSCRIPT>>"-- # Update system prompt with full transcript- updated_system_prompt = system_prompt.replace(- f"<<start context>>\n{context_text}\n<<end context>>",- f"<<start context>>\n{full_context}\n<<end context>>"- )-- # Create new messages with updated context- updated_messages = [{"role": "system", "content": updated_system_prompt}]- if message_history:- updated_messages.extend(message_history)- updated_messages.append({"role": "user", "content": user_message})-- # Generate new response with full context- yield create_status_response('responding', 'Analyzing full transcript...')-- new_stream = call_chat_completion(- messages=updated_messages,- temperature=0.7,- max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),- stream=True,- user_id=user_id,- operation_type='chat'- )-- # Use helper function to process streaming with thinking tag support- for response in process_streaming_with_thinking(new_stream, user_id=user_id, operation_type='chat', model_name=os.environ.get('CHAT_MODEL')):- yield response- return+ if ':' in request_line:+ try:+ recording_id = int(request_line.split(':')[1])+ app.logger.info(f"Agent requested full transcript for recording {recording_id}")++ # Fetch full transcript+ yield create_status_response('fetching', f'Retrieving full transcript for recording {recording_id}...')++ with app.app_context():+ recording = db.session.get(Recording, recording_id)+ if recording and recording.user_id == user_id and recording.transcription:+ # Apply transcript length limit+ if transcript_limit == -1:+ full_transcript = recording.transcriptionelse:- # Recording not found or no permission- error_msg = f"\n\nError: Unable to access full transcript for recording {recording_id}. Recording may not exist or you may not have permission."- yield f"data: {json.dumps({'delta': error_msg})}\n\n"- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"- return-- except (ValueError, IndexError):- app.logger.warning(f"Invalid transcript request format: {request_line}")- # Continue with normal streaming- pass-- # Process the buffer to detect and handle thinking tags- while True:- if not in_thinking:- # Look for opening thinking tag- think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)- if think_start:- # Send any content before the thinking tag- before_thinking = content_buffer[:think_start.start()]- if before_thinking:- yield f"data: {json.dumps({'delta': before_thinking})}\n\n"-- # Start capturing thinking content- in_thinking = True- content_buffer = content_buffer[think_start.end():]- thinking_buffer = ""- else:- # No thinking tag found, send accumulated content- if content_buffer:- yield f"data: {json.dumps({'delta': content_buffer})}\n\n"- content_buffer = ""- break+ full_transcript = recording.transcription[:transcript_limit]++ # Add full transcript to context+ full_context = f"{context_text}\n\n<<FULL TRANSCRIPT - {recording.title}>>\n{full_transcript}\n<<END FULL TRANSCRIPT>>"++ # Update system prompt with full transcript+ updated_system_prompt = system_prompt.replace(+ f"<<start context>>\n{context_text}\n<<end context>>",+ f"<<start context>>\n{full_context}\n<<end context>>"+ )++ # Create new messages with updated context+ updated_messages = [{"role": "system", "content": updated_system_prompt}]+ if message_history:+ updated_messages.extend(message_history)+ updated_messages.append({"role": "user", "content": user_message})++ # Generate new response with full context+ yield create_status_response('responding', 'Analyzing full transcript...')++ new_stream = call_chat_completion(+ messages=updated_messages,+ temperature=0.7,+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),+ stream=True,+ user_id=user_id,+ operation_type='chat'+ )++ # Use helper function to process streaming with thinking tag support+ for response in process_streaming_with_thinking(new_stream, user_id=user_id, operation_type='chat', model_name=os.environ.get('CHAT_MODEL')):+ yield response+ return+ else:+ # Recording not found or no permission+ error_msg = f"\n\nError: Unable to access full transcript for recording {recording_id}. Recording may not exist or you may not have permission."+ yield f"data: {json.dumps({'delta': error_msg})}\n\n"+ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"+ return++ except (ValueError, IndexError):+ app.logger.warning(f"Invalid transcript request format: {request_line}")+ # Continue with normal streaming+ pass++ # Process the buffer to detect and handle thinking tags+ while True:+ if not in_thinking:+ # Look for opening thinking tag+ think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)+ if think_start:+ # Send any content before the thinking tag+ before_thinking = content_buffer[:think_start.start()]+ if before_thinking:+ yield f"data: {json.dumps({'delta': before_thinking})}\n\n"++ # Start capturing thinking content+ in_thinking = True+ content_buffer = content_buffer[think_start.end():]+ thinking_buffer = ""else:- # We're inside a thinking tag, look for closing tag- think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)- if think_end:- # Capture thinking content up to the closing tag- thinking_buffer += content_buffer[:think_end.start()]-- # Send the thinking content as a special type- if thinking_buffer.strip():- yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"-- # Continue processing after the closing tag- in_thinking = False- content_buffer = content_buffer[think_end.end():]- thinking_buffer = ""- else:- # Still inside thinking tag, accumulate content- thinking_buffer += content_buffer- content_buffer = ""- break-- # Handle any remaining content- if in_thinking and thinking_buffer:- # Unclosed thinking tag - send as thinking content- yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"- elif content_buffer:- # Regular content- yield f"data: {json.dumps({'delta': content_buffer})}\n\n"-- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"+ # No thinking tag found, send accumulated content+ if content_buffer:+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"+ content_buffer = ""+ break+ else:+ # We're inside a thinking tag, look for closing tag+ think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)+ if think_end:+ # Capture thinking content up to the closing tag+ thinking_buffer += content_buffer[:think_end.start()]++ # Send the thinking content as a special type+ if thinking_buffer.strip():+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"++ # Continue processing after the closing tag+ in_thinking = False+ content_buffer = content_buffer[think_end.end():]+ thinking_buffer = ""+ else:+ # Still inside thinking tag, accumulate content+ thinking_buffer += content_buffer+ content_buffer = ""+ break++ # Handle any remaining content+ if in_thinking and thinking_buffer:+ # Unclosed thinking tag - send as thinking content+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"+ elif content_buffer:+ # Regular content+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"++ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"++ except TokenBudgetExceeded as e:+ app.logger.warning(f"Token budget exceeded for user {user_id}: {e}")+ yield f"data: {json.dumps({'error': str(e), 'budget_exceeded': True})}\n\n"+ except Exception as e:+ app.logger.error(f"Error in enhanced chat generation: {e}")+ yield f"data: {json.dumps({'error': str(e)})}\n\n"+ finally:+ ctx.pop()++ # Agentic mode (opt-in beta, ENABLE_INQUIRE_AGENT): a ReAct-style tool+ # loop replaces the single-shot pipeline. The legacy generator is+ # passed as fallback so a failing agent never breaks Inquire.+ from src.services.inquire_agent import agent_enabled, run_inquire_agent+ if mode != 'rag' and agent_enabled():+ user_ctx = {+ 'name': user_name,+ 'title': user_title,+ 'company': user_company,+ 'output_language': user_output_language,+ 'timezone': user_zone,+ }+ agent_gen = run_inquire_agent(+ app, user_id, user_ctx, user_message, message_history,+ data.get('conversation_memory'), filters,+ legacy_fallback=generate_enhanced_chat,+ )+ return agent_gen- except TokenBudgetExceeded as e:- app.logger.warning(f"Token budget exceeded for user {user_id}: {e}")- yield f"data: {json.dumps({'error': str(e), 'budget_exceeded': True})}\n\n"- except Exception as e:- app.logger.error(f"Error in enhanced chat generation: {e}")- yield f"data: {json.dumps({'error': str(e)})}\n\n"- finally:- ctx.pop()-- # Agentic mode (opt-in beta, ENABLE_INQUIRE_AGENT): a ReAct-style tool- # loop replaces the single-shot pipeline. The legacy generator is- # passed as fallback so a failing agent never breaks Inquire.- from src.services.inquire_agent import agent_enabled, run_inquire_agent- if agent_enabled():- user_ctx = {- 'name': user_name,- 'title': user_title,- 'company': user_company,- 'output_language': user_output_language,- 'timezone': user_timezone(current_user),- }- agent_gen = run_inquire_agent(- app, user_id, user_ctx, user_message, message_history,- data.get('conversation_memory'), filters,- legacy_fallback=generate_enhanced_chat,- )- return Response(agent_gen, mimetype='text/event-stream')+ return generate_enhanced_chat()- return Response(generate_enhanced_chat(), mimetype='text/event-stream')++@inquire_bp.route('/api/inquire/chat', methods=['POST'])+@login_required+def inquire_chat():+ """Chat with filtered transcriptions using RAG."""+ if not ENABLE_INQUIRE_MODE:+ return jsonify({'error': 'Inquire mode is not enabled'}), 403+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ user_message = data.get('message')+ message_history = data.get('message_history', [])++ if not user_message:+ return jsonify({'error': 'No message provided'}), 400++ # Check if OpenRouter client is available+ if client is None:+ return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503++ return Response(inquire_stream(current_user, data), mimetype='text/event-stream')except Exception as e:current_app.logger.error(f"Error in inquire chat endpoint: {str(e)}")diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 6deec1fd..a8db96c2 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -3099,66 +3099,10 @@ def chat_incognito():if chat_client is None:return jsonify({'error': 'Chat service is not available (chat client not configured)'}), 503- # Prepare the system prompt with the transcription- user_chat_output_language = current_user.output_language if current_user.is_authenticated else None-- language_instruction = ""- if user_chat_output_language:- language_instruction = f"Please provide all your responses in {user_chat_output_language}."-- user_name = current_user.name if current_user.is_authenticated and current_user.name else "User"- user_title = current_user.job_title if current_user.is_authenticated and current_user.job_title else "a professional"- user_company = current_user.company if current_user.is_authenticated and current_user.company else "their organization"-- _chat_ts = bool(current_user.is_authenticated and current_user.chat_include_timestamps)- formatted_transcription = format_transcription_for_llm(- transcription,- include_timestamps=_chat_ts,- template_format=_resolve_timestamp_template_format(- current_user, current_user.chat_timestamp_template_id) if _chat_ts else None,- )-- # Get configurable transcript length limit for chat- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)- if transcript_limit == -1:- chat_transcript = formatted_transcription- else:- chat_transcript = formatted_transcription[:transcript_limit]-- # When timestamps are in the transcript, ask the model to cite them so- # the chat panel can render clickable seek chips (bracketed [h:mm:ss]).- timestamp_instruction = ""- if _chat_ts:- timestamp_instruction = (- "\nWhen you reference a specific moment in the recording, cite its "- "timestamp in square brackets exactly as it appears in the transcript "- "(for example [00:07:35]). The interface renders these as clickable "- "links that start playback at that moment, so cite them wherever they "- "support your answer. Never invent a timestamp that is not in the "- "transcript.\n"- )-- system_prompt = f"""You are a professional meeting and audio transcription analyst assisting {user_name}, who is a(n) {user_title} at {user_company}. {language_instruction} Analyze the following meeting information and respond to the specific request.-{timestamp_instruction}-Following are the meeting participants and their roles:-{participants or "No specific participants information provided."}--Following is the meeting transcript:-<<start transcript>>-{chat_transcript or "No transcript available."}-<<end transcript>>--Additional context and notes about the meeting:-{notes or "none"}--Note: This is an incognito recording - no data is stored on the server.-"""-- # Prepare messages array with system prompt and conversation history- messages = [{"role": "system", "content": system_prompt}]- if message_history:- messages.extend(message_history)- messages.append({"role": "user", "content": user_message})+ # Same prompt as API v1 chat (src/services/recording_chat.py); the notes+ # are the ones this user can see.+ from src.services.recording_chat import build_chat_messages+ messages, _ = build_chat_messages(recording, current_user, user_message, message_history)# Get model infochat_model = os.environ.get('TEXT_MODEL_NAME', os.environ.get('OPENAI_CHAT_MODEL', 'gpt-4o-mini'))diff --git a/src/services/recording_chat.py b/src/services/recording_chat.pynew file mode 100644index 00000000..b5b0a70a--- /dev/null+++ b/src/services/recording_chat.py@@ -0,0 +1,121 @@+"""The prompt for chatting with one recording: one builder for the web app+and API v1 (#412 audit C1, mailr spec G9).++The notes in the prompt are the ones the chatting user can see: the owner's+for the owner, a recipient's own personal notes otherwise.++with_sources: the transcript is sent with segment markers ([S12 12:34 Dana])+and the model is asked to cite [S12 "exact words"]; parse_sources turns those+into numbered sources and checks each quote against its segment.+"""++import re++_CITE = re.compile(r'\[S(\d+)(?:\s+"([^"\]]*)")?\]')+++def _clock(seconds):+ if seconds is None:+ return '--:--'+ seconds = int(seconds)+ h, rest = divmod(seconds, 3600)+ m, s = divmod(rest, 60)+ return f'{h}:{m:02d}:{s:02d}' if h else f'{m:02d}:{s:02d}'+++def _marked_transcript(segments):+ return '\n'.join(f"[S{seg['index']} {_clock(seg['start_time'])} {seg['speaker'] or 'Unknown'}] {seg['text']}"+ for seg in segments)+++def build_chat_messages(recording, user, message, history=None, with_sources=False):+ """(messages, segments). segments is the canonical list when with_sources+ is on and the transcript has segments, else None."""+ from src.models import SystemSetting+ from src.services.transcript_segments import canonical_segments+ from src.tasks.processing import _resolve_timestamp_template_format, format_transcription_for_llm++ segments = canonical_segments(recording) if with_sources else None+ use_markers = bool(segments)+ include_timestamps = bool(getattr(user, 'chat_include_timestamps', False)) and not use_markers+ if use_markers:+ transcript = _marked_transcript(segments)+ else:+ transcript = format_transcription_for_llm(+ recording.transcription,+ include_timestamps=include_timestamps,+ template_format=_resolve_timestamp_template_format(+ user, user.chat_timestamp_template_id) if include_timestamps else None,+ )+ limit = SystemSetting.get_setting('transcript_length_limit', 30000)+ if limit != -1:+ transcript = transcript[:limit]++ language = f"Please provide all your responses in {user.output_language}." if user.output_language else ""+ name = user.name or "User"+ title = user.job_title or "a professional"+ company = user.company or "their organization"++ citation = ""+ if use_markers:+ citation = (+ "\nEach transcript line starts with a marker such as [S12 12:34 Dana]: segment 12, its time and "+ "speaker. Support every statement about the recording with a citation of the segment and a short "+ "exact quote from it, written as [S12 \"exact words\"]. Quote words that appear in that segment; "+ "never invent a segment or a quote.\n")+ elif include_timestamps:+ citation = (+ "\nWhen you reference a specific moment in the recording, cite its "+ "timestamp in square brackets exactly as it appears in the transcript "+ "(for example [00:07:35]). The interface renders these as clickable "+ "links that start playback at that moment, so cite them wherever they "+ "support your answer. Never invent a timestamp that is not in the "+ "transcript.\n")++ notes = recording.get_user_notes(user)+ system_prompt = f"""You are a professional meeting and audio transcription analyst assisting {name}, who is a(n) {title} at {company}. {language} Analyze the following meeting information and respond to the specific request.+{citation}+Following are the meeting participants and their roles:+{recording.participants or "No specific participants information provided."}++Following is the meeting transcript:+<<start transcript>>+{transcript or "No transcript available."}+<<end transcript>>++Additional context and notes about the meeting:+{notes or "none"}+"""+ messages = [{"role": "system", "content": system_prompt}]+ messages.extend(history or [])+ messages.append({"role": "user", "content": message})+ return messages, (segments if use_markers else None)+++def _norm(text):+ return re.sub(r'\s+', ' ', (text or '')).strip().lower()+++def parse_sources(reply, segments):+ """Replace [S12 "quote"] citations with [n]; returns (reply, sources)."""+ by_index = {seg['index']: seg for seg in segments or []}+ sources, numbers = [], {}++ def _replace(match):+ index, quote = int(match.group(1)), match.group(2)+ key = (index, _norm(quote))+ if key not in numbers:+ seg = by_index.get(index)+ numbers[key] = len(sources) + 1+ sources.append({+ 'n': numbers[key],+ 'segment_index': index if seg else None,+ 'start_time': seg['start_time'] if seg else None,+ 'end_time': seg['end_time'] if seg else None,+ 'speaker': seg['speaker'] if seg else None,+ 'quote': quote,+ 'verified': bool(seg and quote and _norm(quote) in _norm(seg['text'])),+ })+ return f'[{numbers[key]}]'++ return _CITE.sub(_replace, reply or ''), sourcesdiff --git a/tests/test_api_v1_chat_inquire.py b/tests/test_api_v1_chat_inquire.pynew file mode 100644index 00000000..3fc69768--- /dev/null+++ b/tests/test_api_v1_chat_inquire.py@@ -0,0 +1,148 @@+"""Chat sources and v1 Inquire (mailr spec G9), and the shared chat prompt (#412 C1).++The model is mocked: no request leaves the test.++SHARED-DB: users, tokens, shares, states and recordings are removed afterwards.+"""++import json+import os+import secrets+import sys+from unittest.mock import MagicMock, patch++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import APIToken, InternalShare, Recording, SharedRecordingState, User+from src.utils.token_auth import hash_token++SEGMENTS = [{"speaker": "Dana", "sentence": "Welcome back.", "start_time": 0.0, "end_time": 3.0},+ {"speaker": "Omar", "sentence": "So the budget freeze applies to travel only.", "start_time": 754.2,+ "end_time": 761.0}]+++def world():+ with app.app_context():+ s = secrets.token_hex(4)+ owner = User(username=f"ch_{s}", email=f"ch_{s}@local.test", password="x")+ guest = User(username=f"chg_{s}", email=f"chg_{s}@local.test", password="x")+ db.session.add_all([owner, guest])+ db.session.commit()+ rec = Recording(user_id=owner.id, title="Weekly sync", status="COMPLETED", original_filename="a.wav",+ transcription=json.dumps(SEGMENTS), notes="OWNER SECRET NOTE")+ other = Recording(user_id=guest.id, title="Guest only", status="COMPLETED", original_filename="b.wav")+ db.session.add_all([rec, other])+ db.session.commit()+ db.session.add(InternalShare(recording_id=rec.id, owner_id=owner.id, shared_with_user_id=guest.id))+ db.session.add(SharedRecordingState(recording_id=rec.id, user_id=guest.id, personal_notes="GUEST NOTE"))+ tokens = {}+ for key, user, scopes in (("process", owner, ["read", "process"]), ("read", owner, ["read"])):+ p = f"tok-{secrets.token_urlsafe(16)}"+ db.session.add(APIToken(user_id=user.id, token_hash=hash_token(p), name=key, scopes=json.dumps(scopes)))+ tokens[key] = p+ db.session.commit()+ ids = dict(owner=owner.id, guest=guest.id, rec=rec.id, other=other.id, tokens=tokens)+ yield ids+ with app.app_context():+ db.session.rollback()+ SharedRecordingState.query.filter_by(recording_id=ids["rec"]).delete()+ InternalShare.query.filter_by(recording_id=ids["rec"]).delete()+ Recording.query.filter(Recording.id.in_([ids["rec"], ids["other"]])).delete(synchronize_session=False)+ APIToken.query.filter_by(user_id=ids["owner"]).delete()+ User.query.filter(User.id.in_([ids["owner"], ids["guest"]])).delete(synchronize_session=False)+ db.session.commit()+++def _completion(text):+ return MagicMock(choices=[MagicMock(message=MagicMock(content=text))])+++def _chat(world, body, reply):+ seen = {}++ def fake(messages, **kw):+ seen["messages"] = messages+ return _completion(reply)++ with patch("src.services.llm.chat_client", MagicMock()), patch("src.services.llm.call_chat_completion", side_effect=fake):+ with app.test_client() as c:+ resp = c.post(f"/api/v1/recordings/{world['rec']}/chat", json=body,+ headers={"Authorization": f"Bearer {world['tokens']['process']}"})+ return resp, seen.get("messages")+++def test_with_sources_marks_segments_and_checks_quotes(world):+ reply = 'Travel only [S1 "budget freeze applies to travel"], not hiring [S1 "freeze on hiring"] [S9 "x"].'+ resp, messages = _chat(world, {"message": "What does the freeze cover?", "with_sources": True}, reply)+ assert resp.status_code == 200, resp.get_json()+ system = messages[0]["content"]+ assert "[S1 12:34 Omar] So the budget freeze applies to travel only." in system and '[S12 "exact words"]' in system+ body = resp.get_json()+ assert body["response"] == "Travel only [1], not hiring [2] [3]."+ first, invented, missing = body["sources"]+ assert (first["segment_index"], first["start_time"], first["end_time"], first["speaker"], first["verified"]) == \+ (1, 754.2, 761.0, "Omar", True)+ assert invented["verified"] is False and invented["segment_index"] == 1+ assert missing["segment_index"] is None and missing["verified"] is False+++def test_without_sources_nothing_changes(world):+ resp, messages = _chat(world, {"message": "Summarise"}, "A summary [S1].")+ assert resp.get_json() == {"response": "A summary [S1].", "sources": []}+ assert "[S1 " not in messages[0]["content"]+++def test_the_prompt_carries_the_notes_this_user_can_see(world):+ from src.services.recording_chat import build_chat_messages+ with app.app_context():+ rec = db.session.get(Recording, world["rec"])+ guest_prompt = build_chat_messages(rec, db.session.get(User, world["guest"]), "hi")[0][0]["content"]+ owner_prompt = build_chat_messages(rec, db.session.get(User, world["owner"]), "hi")[0][0]["content"]+ assert "GUEST NOTE" in guest_prompt and "OWNER SECRET NOTE" not in guest_prompt+ assert "OWNER SECRET NOTE" in owner_prompt+++def _inquire(world, body, token="process", env="true"):+ with patch.dict(os.environ, {"ENABLE_INQUIRE_MODE": env}):+ with app.test_client() as c:+ return c.post("/api/v1/inquire", json=body, headers={"Authorization": f"Bearer {world['tokens'][token]}"})+++def test_inquire_refusals(world):+ off = _inquire(world, {"question": "x"}, env="false")+ assert off.status_code == 403 and off.get_json()["code"] == "feature_disabled"+ read = _inquire(world, {"question": "x"}, token="read")+ assert read.status_code == 403 and read.get_json()["code"] == "insufficient_scope"+ assert _inquire(world, {"question": ""}).status_code == 400+++def test_inquire_parses_agent_links_into_citations(world):+ events = [+ {"agent_step": {"id": 1, "tool": "search"}},+ {"delta": f"The freeze covers travel [Weekly sync @ 12:34](/recordings/{world['rec']}?t=754) "},+ {"delta": f"and again [Weekly sync @ 12:34](/recordings/{world['rec']}?t=754); "+ f"see [Weekly sync](/recordings/{world['rec']}) and [Guest only](/recordings/{world['other']})."},+ {"agent_summary": {"steps": 3, "line": "3 searches"}},+ {"end_of_stream": True},+ ]++ def fake_stream(user, data, mode="auto"):+ assert data["filter_recording_ids"] == [world["rec"]] # own scope only+ for e in events:+ yield f"data: {json.dumps(e)}\n\n"++ with patch("src.api.inquire.inquire_stream", side_effect=fake_stream), \+ patch("src.services.inquire_agent.agent_enabled", return_value=True):+ resp = _inquire(world, {"question": "What about the freeze?"})+ body = resp.get_json()+ assert resp.status_code == 200, body+ assert body["answer"] == "The freeze covers travel [1] and again [1]; see [2] and Guest only."+ assert [(c["n"], c["recording_id"], c["start_time"], c["url"]) for c in body["citations"]] == [+ (1, world["rec"], 754.0, f"/recordings/{world['rec']}?t=754"),+ (2, world["rec"], None, f"/recordings/{world['rec']}")]+ assert body["citations"][0]["title"] == "Weekly sync"+ assert body["mode_used"] == "agent" and body["steps"] == 3diff --git a/tests/test_api_v1_scope_coverage.py b/tests/test_api_v1_scope_coverage.pyindex 5043a1ca..e9a14d26 100644--- a/tests/test_api_v1_scope_coverage.py+++ b/tests/test_api_v1_scope_coverage.py@@ -23,7 +23,7 @@ EXPECTED = {"create_speaker", "update_speaker", "assign_speakers", "batch_update_recordings"},"account": {"update_auto_summarization"},"upload": {"upload_recording", "upload_from_asr_voice_recorder"},- "process": {"api_regenerate_title", "identify_speakers", "start_transcription", "start_summarization",+ "process": {"inquire_v1", "api_regenerate_title", "identify_speakers", "start_transcription", "start_summarization","chat_with_recording", "batch_transcribe_recordings"},"delete": {"delete_recording", "delete_recording_audio", "batch_delete_recordings", "delete_tag","delete_folder", "delete_speaker"},