|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import time |
| 5 | +from collections.abc import AsyncIterator |
| 6 | + |
| 7 | +from server.chat.generation import generate_chat_text, stream_chat_text |
| 8 | +from server.chat.provider_router import select_provider_route |
| 9 | +from server.chat.source_router import resolve_sources |
| 10 | +from server.db.postgres import PostgresClient |
| 11 | +from server.models.chat_config import RecallConfig |
| 12 | +from server.models.retrieval import ChunkMatch |
| 13 | +from server.models.tribrid_config_model import ChatRequest, TriBridConfig |
| 14 | +from server.services.conversation_store import Conversation |
| 15 | +from server.services.rag import FusionProtocol |
| 16 | + |
| 17 | + |
| 18 | +def _build_system_prompt(*, config: TriBridConfig, corpus_ids: list[str]) -> str: |
| 19 | + chat_cfg = config.chat |
| 20 | + prompt = str(chat_cfg.system_prompt_base or "") |
| 21 | + |
| 22 | + recall_id = str(chat_cfg.recall.default_corpus_id or "recall_default") |
| 23 | + has_recall = recall_id in set(corpus_ids) |
| 24 | + has_rag = any(cid and cid != recall_id for cid in corpus_ids) |
| 25 | + |
| 26 | + if has_recall: |
| 27 | + prompt += str(chat_cfg.system_prompt_recall_suffix or "") |
| 28 | + if has_rag: |
| 29 | + prompt += str(chat_cfg.system_prompt_rag_suffix or "") |
| 30 | + return prompt.strip() or "You are a helpful assistant." |
| 31 | + |
| 32 | + |
| 33 | +async def _ensure_recall_ready(pg: PostgresClient, recall_cfg: RecallConfig) -> None: |
| 34 | + # Ensure Recall corpus exists before any retrieval/indexing attempts. |
| 35 | + await pg.connect() |
| 36 | + from server.chat.recall_indexer import ensure_recall_corpus |
| 37 | + |
| 38 | + await ensure_recall_corpus(pg, recall_cfg) |
| 39 | + |
| 40 | + |
| 41 | +def _should_index_recall(*, recall_cfg: RecallConfig, corpus_ids: list[str]) -> bool: |
| 42 | + if not recall_cfg.enabled: |
| 43 | + return False |
| 44 | + recall_id = str(recall_cfg.default_corpus_id or "recall_default") |
| 45 | + return recall_id in set(corpus_ids) |
| 46 | + |
| 47 | + |
| 48 | +async def chat_once( |
| 49 | + *, |
| 50 | + request: ChatRequest, |
| 51 | + config: TriBridConfig, |
| 52 | + fusion: FusionProtocol, |
| 53 | + conversation: Conversation, |
| 54 | +) -> tuple[str, list[ChunkMatch], str | None]: |
| 55 | + """Non-streaming chat handler.""" |
| 56 | + |
| 57 | + corpus_ids = resolve_sources(request.sources) |
| 58 | + |
| 59 | + # Ensure recall corpus exists before retrieval/indexing if enabled + selected. |
| 60 | + pg = PostgresClient(config.indexing.postgres_url) |
| 61 | + if _should_index_recall(recall_cfg=config.chat.recall, corpus_ids=corpus_ids): |
| 62 | + await _ensure_recall_ready(pg, config.chat.recall) |
| 63 | + |
| 64 | + # Retrieval (skip when nothing checked) |
| 65 | + sources: list[ChunkMatch] = [] |
| 66 | + if corpus_ids: |
| 67 | + sources = await fusion.search( |
| 68 | + corpus_ids, |
| 69 | + request.message, |
| 70 | + config.fusion, |
| 71 | + include_vector=bool(request.include_vector), |
| 72 | + include_sparse=bool(request.include_sparse), |
| 73 | + include_graph=bool(request.include_graph), |
| 74 | + top_k=request.top_k, |
| 75 | + ) |
| 76 | + |
| 77 | + # Provider + prompt |
| 78 | + system_prompt = _build_system_prompt(config=config, corpus_ids=corpus_ids) |
| 79 | + route = select_provider_route(chat_config=config.chat, model_override=request.model_override) |
| 80 | + temperature = ( |
| 81 | + float(config.chat.temperature_no_retrieval) if not corpus_ids else float(config.chat.temperature) |
| 82 | + ) |
| 83 | + |
| 84 | + text, provider_id = await generate_chat_text( |
| 85 | + route=route, |
| 86 | + openrouter_cfg=config.chat.openrouter, |
| 87 | + system_prompt=system_prompt, |
| 88 | + user_message=request.message, |
| 89 | + images=list(request.images or []), |
| 90 | + temperature=temperature, |
| 91 | + max_tokens=int(config.chat.max_tokens), |
| 92 | + context_chunks=sources, |
| 93 | + timeout_s=float(getattr(config.ui, "chat_stream_timeout", 120) or 120), |
| 94 | + ) |
| 95 | + |
| 96 | + # Update in-memory conversation continuity (best-effort for local providers) |
| 97 | + if provider_id: |
| 98 | + conversation.last_provider_response_id = provider_id |
| 99 | + |
| 100 | + return text, sources, provider_id |
| 101 | + |
| 102 | + |
| 103 | +async def chat_stream( |
| 104 | + *, |
| 105 | + request: ChatRequest, |
| 106 | + config: TriBridConfig, |
| 107 | + fusion: FusionProtocol, |
| 108 | + conversation: Conversation, |
| 109 | + run_id: str, |
| 110 | + started_at_ms: int, |
| 111 | +) -> AsyncIterator[str]: |
| 112 | + """Streaming chat handler that yields SSE events (type=text/done/error).""" |
| 113 | + |
| 114 | + corpus_ids = resolve_sources(request.sources) |
| 115 | + |
| 116 | + pg = PostgresClient(config.indexing.postgres_url) |
| 117 | + if _should_index_recall(recall_cfg=config.chat.recall, corpus_ids=corpus_ids): |
| 118 | + await _ensure_recall_ready(pg, config.chat.recall) |
| 119 | + |
| 120 | + # Retrieval (skip when nothing checked) |
| 121 | + sources: list[ChunkMatch] = [] |
| 122 | + if corpus_ids: |
| 123 | + sources = await fusion.search( |
| 124 | + corpus_ids, |
| 125 | + request.message, |
| 126 | + config.fusion, |
| 127 | + include_vector=bool(request.include_vector), |
| 128 | + include_sparse=bool(request.include_sparse), |
| 129 | + include_graph=bool(request.include_graph), |
| 130 | + top_k=request.top_k, |
| 131 | + ) |
| 132 | + |
| 133 | + system_prompt = _build_system_prompt(config=config, corpus_ids=corpus_ids) |
| 134 | + route = select_provider_route(chat_config=config.chat, model_override=request.model_override) |
| 135 | + temperature = ( |
| 136 | + float(config.chat.temperature_no_retrieval) if not corpus_ids else float(config.chat.temperature) |
| 137 | + ) |
| 138 | + |
| 139 | + accumulated = "" |
| 140 | + try: |
| 141 | + async for delta in stream_chat_text( |
| 142 | + route=route, |
| 143 | + openrouter_cfg=config.chat.openrouter, |
| 144 | + system_prompt=system_prompt, |
| 145 | + user_message=request.message, |
| 146 | + images=list(request.images or []), |
| 147 | + temperature=temperature, |
| 148 | + max_tokens=int(config.chat.max_tokens), |
| 149 | + context_chunks=sources, |
| 150 | + timeout_s=float(getattr(config.ui, "chat_stream_timeout", 120) or 120), |
| 151 | + ): |
| 152 | + accumulated += delta |
| 153 | + yield f"data: {json.dumps({'type': 'text', 'content': delta})}\n\n" |
| 154 | + |
| 155 | + ended_at_ms = int(time.time() * 1000) |
| 156 | + sources_json = [s.model_dump(mode="serialization", by_alias=True) for s in sources] |
| 157 | + done_payload = { |
| 158 | + "type": "done", |
| 159 | + "run_id": run_id, |
| 160 | + "started_at_ms": int(started_at_ms), |
| 161 | + "ended_at_ms": int(ended_at_ms), |
| 162 | + "conversation_id": conversation.id, |
| 163 | + "sources": sources_json, |
| 164 | + } |
| 165 | + yield f"data: {json.dumps(done_payload)}\n\n" |
| 166 | + |
| 167 | + except Exception as e: |
| 168 | + yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n" |
| 169 | + |
0 commit comments