Upload explain.py
Browse files- lablens/explain.py +10 -3
lablens/explain.py
CHANGED
|
@@ -100,12 +100,18 @@ def explain_with_llm(analysis: Analysis, lang: str, timeout: float = 45.0) -> di
|
|
| 100 |
items = _payload(analysis, lang)
|
| 101 |
user = (f"Language: {LANGS.get(lang, 'English')}. {LANG_INSTRUCTIONS.get(lang, '')}\n\n"
|
| 102 |
f"Results (JSON):\n{json.dumps(items, ensure_ascii=False)}")
|
| 103 |
-
|
| 104 |
model=os.getenv("LLM_MODEL", DEFAULT_MODEL),
|
| 105 |
messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user}],
|
| 106 |
temperature=0.2,
|
| 107 |
-
max_tokens=
|
| 108 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
text = resp.choices[0].message.content or ""
|
| 110 |
m = re.search(r"\{.*\}", text, re.S)
|
| 111 |
if not m:
|
|
@@ -158,7 +164,8 @@ def explain(analysis: Analysis, lang: str) -> tuple[dict, str]:
|
|
| 158 |
try:
|
| 159 |
return explain_with_llm(analysis, lang), "llm"
|
| 160 |
except Exception as e: # network, JSON, or guardrail failure -> safe fallback
|
| 161 |
-
|
|
|
|
| 162 |
|
| 163 |
|
| 164 |
def render_markdown(analysis: Analysis, exp: dict, lang: str) -> str:
|
|
|
|
| 100 |
items = _payload(analysis, lang)
|
| 101 |
user = (f"Language: {LANGS.get(lang, 'English')}. {LANG_INSTRUCTIONS.get(lang, '')}\n\n"
|
| 102 |
f"Results (JSON):\n{json.dumps(items, ensure_ascii=False)}")
|
| 103 |
+
kwargs = dict(
|
| 104 |
model=os.getenv("LLM_MODEL", DEFAULT_MODEL),
|
| 105 |
messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user}],
|
| 106 |
temperature=0.2,
|
| 107 |
+
max_tokens=3000, # Arabic/Darija text uses many tokens; truncated JSON can't be parsed
|
| 108 |
)
|
| 109 |
+
try: # JSON mode where the provider supports it, plain request otherwise
|
| 110 |
+
resp = client.chat.completions.create(response_format={"type": "json_object"}, **kwargs)
|
| 111 |
+
except Exception as e:
|
| 112 |
+
if "response_format" not in str(e) and "json" not in str(e).lower():
|
| 113 |
+
raise
|
| 114 |
+
resp = client.chat.completions.create(**kwargs)
|
| 115 |
text = resp.choices[0].message.content or ""
|
| 116 |
m = re.search(r"\{.*\}", text, re.S)
|
| 117 |
if not m:
|
|
|
|
| 164 |
try:
|
| 165 |
return explain_with_llm(analysis, lang), "llm"
|
| 166 |
except Exception as e: # network, JSON, or guardrail failure -> safe fallback
|
| 167 |
+
print(f"[LabLens] AI explanation failed, using template: {type(e).__name__}: {e}", flush=True)
|
| 168 |
+
return explain_with_template(analysis, lang), f"template:{type(e).__name__}: {str(e)[:160]}"
|
| 169 |
|
| 170 |
|
| 171 |
def render_markdown(analysis: Analysis, exp: dict, lang: str) -> str:
|