feat(backend): retry once when an interpretation reads flat
Browse filesSmall models sometimes return a generic one-liner or describe "the photo"
despite the prompt. Detect that (min length + banned-phrase regex) and retry
once with the refined prompt and a hotter temperature, keeping whichever pass
is stronger. Adds an explicit `refined` override to system_prompt() and a
per-call temperature to providers.
- backend/oracle.py +47 -5
- backend/prompt.py +13 -6
- backend/providers.py +22 -4
backend/oracle.py
CHANGED
|
@@ -21,6 +21,20 @@ from .providers import Provider, get_provider
|
|
| 21 |
MAX_IMAGES = 4
|
| 22 |
MAX_TOKENS = 2048
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
class OracleError(Exception):
|
| 26 |
"""Raised when the model reply can't be coerced into the contract."""
|
|
@@ -111,17 +125,45 @@ def _validate(data: dict[str, Any]) -> dict[str, Any]:
|
|
| 111 |
return {"interpretation": interp.strip(), "films": clean_films[:3]}
|
| 112 |
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
def interpret(
|
| 115 |
images: list[str],
|
| 116 |
fragment: str = "",
|
| 117 |
provider: Provider | None = None,
|
| 118 |
) -> dict[str, Any]:
|
| 119 |
-
"""Run the full flow. `images` are data URLs or raw base64 JPEG strings.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
if not images:
|
| 121 |
raise OracleError("Bring at least one image.")
|
| 122 |
provider = provider or get_provider()
|
| 123 |
content = _build_content(images, fragment)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
MAX_IMAGES = 4
|
| 22 |
MAX_TOKENS = 2048
|
| 23 |
|
| 24 |
+
# Below this, an interpretation reads as a flat one-liner rather than a reading.
|
| 25 |
+
MIN_INTERPRETATION_CHARS = 180
|
| 26 |
+
# A slightly hotter retry to shake a generic first pass loose.
|
| 27 |
+
RETRY_TEMPERATURE = 0.95
|
| 28 |
+
|
| 29 |
+
# Phrases the prompt forbids — describing "the image" instead of the felt moment.
|
| 30 |
+
# Word-bounded so we don't trip on "imagery", "depict", etc.
|
| 31 |
+
_BANNED = re.compile(
|
| 32 |
+
r"\bthe (images?|photos?|photographs?|pictures?)\b"
|
| 33 |
+
r"|\b(this|these) (image|images|photo|photos|picture|pictures)\b"
|
| 34 |
+
r"|\bthe (image|photo|picture) shows?\b",
|
| 35 |
+
re.IGNORECASE,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
|
| 39 |
class OracleError(Exception):
|
| 40 |
"""Raised when the model reply can't be coerced into the contract."""
|
|
|
|
| 125 |
return {"interpretation": interp.strip(), "films": clean_films[:3]}
|
| 126 |
|
| 127 |
|
| 128 |
+
def _is_weak(interpretation: str) -> bool:
|
| 129 |
+
"""A flat or rule-breaking interpretation worth one retry."""
|
| 130 |
+
text = interpretation.strip()
|
| 131 |
+
return len(text) < MIN_INTERPRETATION_CHARS or bool(_BANNED.search(text))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _run(provider: Provider, content, *, refined: bool, temperature=None) -> dict[str, Any]:
|
| 135 |
+
raw = provider.complete(system_prompt(refined=refined), content, MAX_TOKENS, temperature)
|
| 136 |
+
if not raw.strip():
|
| 137 |
+
raise OracleError("The model returned an empty reply.")
|
| 138 |
+
return _validate(_extract_json(raw))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
def interpret(
|
| 142 |
images: list[str],
|
| 143 |
fragment: str = "",
|
| 144 |
provider: Provider | None = None,
|
| 145 |
) -> dict[str, Any]:
|
| 146 |
+
"""Run the full flow. `images` are data URLs or raw base64 JPEG strings.
|
| 147 |
+
|
| 148 |
+
If the first interpretation reads flat or breaks the "never describe the
|
| 149 |
+
photo" rule, retry once with the refined prompt and a hotter temperature,
|
| 150 |
+
then keep whichever pass is stronger.
|
| 151 |
+
"""
|
| 152 |
if not images:
|
| 153 |
raise OracleError("Bring at least one image.")
|
| 154 |
provider = provider or get_provider()
|
| 155 |
content = _build_content(images, fragment)
|
| 156 |
+
|
| 157 |
+
result = _run(provider, content, refined=False)
|
| 158 |
+
if not _is_weak(result["interpretation"]):
|
| 159 |
+
return result
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
retry = _run(provider, content, refined=True, temperature=RETRY_TEMPERATURE)
|
| 163 |
+
except OracleError:
|
| 164 |
+
return result # a bad retry shouldn't lose a usable first pass
|
| 165 |
+
|
| 166 |
+
if not _is_weak(retry["interpretation"]):
|
| 167 |
+
return retry
|
| 168 |
+
# Both flagged — return the meatier of the two.
|
| 169 |
+
return retry if len(retry["interpretation"]) > len(result["interpretation"]) else result
|
backend/prompt.py
CHANGED
|
@@ -39,12 +39,19 @@ _FILM_REFINEMENT = (
|
|
| 39 |
)
|
| 40 |
|
| 41 |
|
| 42 |
-
def system_prompt() -> str:
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return _BASE.format(
|
| 49 |
interp_extra=_INTERP_REFINEMENT if refined else "",
|
| 50 |
film_extra=_FILM_REFINEMENT if refined else "",
|
|
|
|
| 39 |
)
|
| 40 |
|
| 41 |
|
| 42 |
+
def system_prompt(refined: bool | None = None) -> str:
|
| 43 |
+
"""Build the system prompt.
|
| 44 |
+
|
| 45 |
+
`refined=None` reads the env flag (default baseline). Pass `refined=True`
|
| 46 |
+
explicitly to force the refinements — used by the oracle's one-shot retry
|
| 47 |
+
when a first interpretation reads flat.
|
| 48 |
+
"""
|
| 49 |
+
if refined is None:
|
| 50 |
+
refined = os.environ.get("CHALCHITRA_REFINED_PROMPT", "").lower() in (
|
| 51 |
+
"1",
|
| 52 |
+
"true",
|
| 53 |
+
"yes",
|
| 54 |
+
)
|
| 55 |
return _BASE.format(
|
| 56 |
interp_extra=_INTERP_REFINEMENT if refined else "",
|
| 57 |
film_extra=_FILM_REFINEMENT if refined else "",
|
backend/providers.py
CHANGED
|
@@ -31,7 +31,13 @@ class Provider(Protocol):
|
|
| 31 |
name: str
|
| 32 |
model: str
|
| 33 |
|
| 34 |
-
def complete(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
class OpenAICompatibleProvider:
|
|
@@ -56,11 +62,17 @@ class OpenAICompatibleProvider:
|
|
| 56 |
self.temperature = temperature
|
| 57 |
self._client = OpenAI(base_url=base_url, api_key=api_key)
|
| 58 |
|
| 59 |
-
def complete(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
resp = self._client.chat.completions.create(
|
| 61 |
model=self.model,
|
| 62 |
max_tokens=max_tokens,
|
| 63 |
-
temperature=self.temperature,
|
| 64 |
messages=[
|
| 65 |
{"role": "system", "content": system},
|
| 66 |
{"role": "user", "content": content},
|
|
@@ -98,7 +110,13 @@ class HFLocalProvider:
|
|
| 98 |
self.name = "hf_local"
|
| 99 |
self.model = model
|
| 100 |
|
| 101 |
-
def complete(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
raise NotImplementedError(
|
| 103 |
"HFLocalProvider (ZeroGPU/transformers) is not implemented yet. While "
|
| 104 |
"developing, use CHALCHITRA_PROVIDER=openai_compatible against LM Studio."
|
|
|
|
| 31 |
name: str
|
| 32 |
model: str
|
| 33 |
|
| 34 |
+
def complete(
|
| 35 |
+
self,
|
| 36 |
+
system: str,
|
| 37 |
+
content: list[dict[str, Any]],
|
| 38 |
+
max_tokens: int,
|
| 39 |
+
temperature: float | None = None,
|
| 40 |
+
) -> str: ...
|
| 41 |
|
| 42 |
|
| 43 |
class OpenAICompatibleProvider:
|
|
|
|
| 62 |
self.temperature = temperature
|
| 63 |
self._client = OpenAI(base_url=base_url, api_key=api_key)
|
| 64 |
|
| 65 |
+
def complete(
|
| 66 |
+
self,
|
| 67 |
+
system: str,
|
| 68 |
+
content: list[dict[str, Any]],
|
| 69 |
+
max_tokens: int,
|
| 70 |
+
temperature: float | None = None,
|
| 71 |
+
) -> str:
|
| 72 |
resp = self._client.chat.completions.create(
|
| 73 |
model=self.model,
|
| 74 |
max_tokens=max_tokens,
|
| 75 |
+
temperature=self.temperature if temperature is None else temperature,
|
| 76 |
messages=[
|
| 77 |
{"role": "system", "content": system},
|
| 78 |
{"role": "user", "content": content},
|
|
|
|
| 110 |
self.name = "hf_local"
|
| 111 |
self.model = model
|
| 112 |
|
| 113 |
+
def complete(
|
| 114 |
+
self,
|
| 115 |
+
system: str,
|
| 116 |
+
content: list[dict[str, Any]],
|
| 117 |
+
max_tokens: int,
|
| 118 |
+
temperature: float | None = None,
|
| 119 |
+
) -> str:
|
| 120 |
raise NotImplementedError(
|
| 121 |
"HFLocalProvider (ZeroGPU/transformers) is not implemented yet. While "
|
| 122 |
"developing, use CHALCHITRA_PROVIDER=openai_compatible against LM Studio."
|