Spaces:
Build error
Build error
File size: 7,495 Bytes
460549a 8ea168e 460549a 8ea168e 460549a 8ea168e 460549a 8ea168e 460549a 8ea168e 460549a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | """Context Assembler — Strategy pattern, one AssemblyStrategy per generation
mode (Mcq/Essay/Blueprint/Chat), each owning only its token budget and
image-selection threshold. Everything else (deduplication) already happened
in context_optimizer.py; everything after this (calling the LLM) happens in
gateway.py. This factoring keeps adding a new question type or model tier a
change confined to one new strategy class, not a growing if/elif chain.
Fixed content order for every strategy: paragraph text -> diagram/table/
formula description -> caption -> formula (if not already covered) -> OCR
text -> the image itself, attached last as the multimodal part.
"""
from dataclasses import dataclass, field
from typing import Optional
from app.services.context_optimizer import ElementBundle
from app.services.graph_repository import GraphElement
from app.services.policy import Policy
_CHARS_PER_TOKEN = 4
@dataclass
class AssembledContext:
text: str
image_urls: list[str] = field(default_factory=list)
figure_urls: list[str] = field(default_factory=list) # surfaced to the frontend as question.figure_url
# Chunk id per assembled block, positionally aligned with the `[[المصدر N]]`
# markers `assemble(label_sources=True)` writes into `text` (marker N ->
# block_chunk_ids[N-1]). Exam generation uses this to turn the model's
# self-reported `source_index` into real per-question provenance; callers
# that don't label sources can ignore it.
block_chunk_ids: list[str] = field(default_factory=list)
def _element_description(element: GraphElement) -> str:
if element.element_type == "diagram":
return element.semantic_description or ""
if element.element_type == "table":
return element.table_summary or ""
if element.element_type == "formula":
return element.formula_summary or ""
return ""
def _estimate_tokens(text: str) -> int:
return max(1, len(text) // _CHARS_PER_TOKEN)
def _element_value_density(element: GraphElement, weight: float, normalized_confidence: Optional[float]) -> float:
text = _element_description(element) + (element.ocr_text or "")
cost = _estimate_tokens(text) + (150 if element.element_type == "diagram" else 0) # flat image-attach cost estimate
importance = (element.importance_score or 50) / 100.0
confidence = normalized_confidence if normalized_confidence is not None else 1.0
value = weight * confidence * importance
return value / max(cost, 1)
class AssemblyStrategy:
"""Base strategy — subclasses only need to override `question_type_key`."""
question_type_key: str = "essay"
def image_threshold(self, policy: Policy) -> int:
return policy.image_importance_threshold
def budget_tokens(self, policy: Policy) -> int:
return policy.budget_for(self.question_type_key)
def assemble(
self, bundles: list[ElementBundle], policy: Policy, *, label_sources: bool = False,
) -> AssembledContext:
"""Assemble retrieved bundles into one context string.
`label_sources` prefixes every block with a `[[المصدر N]]` marker and
populates `block_chunk_ids` so a generator can cite which block it
used. Off by default — chat/explanation contexts must not carry
markers the model might echo into a user-facing answer.
"""
budget = self.budget_tokens(policy)
image_threshold = self.image_threshold(policy)
# Greedily rank every (bundle, element) pair by value density and take
# the highest-value ones until the token budget is exhausted — not a
# flat top-K, and not "include everything reachable".
candidates: list[tuple[float, int, ElementBundle, GraphElement]] = []
for b_idx, bundle in enumerate(bundles):
for element, relationship in bundle.elements:
weight = relationship.weight or 0.5
density = _element_value_density(element, weight, relationship.normalized_confidence)
candidates.append((density, b_idx, bundle, element))
candidates.sort(key=lambda c: c[0], reverse=True)
selected_by_bundle: dict[int, list[GraphElement]] = {}
used_tokens = 0
for density, b_idx, bundle, element in candidates:
text = _element_description(element) + (element.ocr_text or "")
cost = _estimate_tokens(text)
if used_tokens + cost > budget:
continue
used_tokens += cost
selected_by_bundle.setdefault(b_idx, []).append(element)
blocks: list[str] = []
block_chunk_ids: list[str] = []
image_urls: list[str] = []
figure_urls: list[str] = []
for b_idx, bundle in enumerate(bundles):
# The marker is written first so it survives any downstream
# truncation of the block's tail, and numbered from 1 because the
# model reproduces it verbatim (0-based indices invite off-by-one
# answers from LLMs far more often than 1-based ones do).
parts = [f"[[المصدر {len(block_chunk_ids) + 1}]]"] if label_sources else []
block_chunk_ids.append(bundle.chunk_id)
parts.append(bundle.chunk_content)
for element in selected_by_bundle.get(b_idx, []):
description = _element_description(element)
if description:
parts.append(description)
if element.caption:
parts.append(f"[تسمية: {element.caption}]")
if element.element_type == "formula" and element.formula_text:
parts.append(f"[المعادلة: {element.formula_text}]")
if element.element_type == "table" and element.markdown_table:
parts.append(element.markdown_table)
if element.ocr_text:
parts.append(f"[نص داخل الصورة: {element.ocr_text}]")
if element.url:
figure_urls.append(element.url)
if (element.importance_score or 0) >= image_threshold:
image_urls.append(element.url)
blocks.append("\n".join(p for p in parts if p))
return AssembledContext(
text="\n\n---\n\n".join(blocks),
image_urls=image_urls,
figure_urls=figure_urls,
block_chunk_ids=block_chunk_ids,
)
class McqStrategy(AssemblyStrategy):
question_type_key = "mcq"
class EssayStrategy(AssemblyStrategy):
question_type_key = "essay"
class BlueprintStrategy(AssemblyStrategy):
question_type_key = "blueprint"
class ChatStrategy(AssemblyStrategy):
question_type_key = "essay" # chat has no dedicated budget tier — reuse essay's
class DiagramQuestionStrategy(AssemblyStrategy):
question_type_key = "diagram_question"
def image_threshold(self, policy: Policy) -> int:
# Diagram-anchored questions should attach the image more readily.
return max(0, policy.image_importance_threshold - 20)
_STRATEGIES: dict[str, type[AssemblyStrategy]] = {
"mcq": McqStrategy,
"essay": EssayStrategy,
"blueprint": BlueprintStrategy,
"chat": ChatStrategy,
"diagram_question": DiagramQuestionStrategy,
}
def get_strategy(question_type: Optional[str]) -> AssemblyStrategy:
cls = _STRATEGIES.get((question_type or "essay").lower(), EssayStrategy)
return cls()
|