Spaces:
Running
Running
Upload folder using huggingface_hub
Browse files- app/ai/interpreter.py +27 -4
- app/ai/tool_interpreter.py +17 -7
app/ai/interpreter.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import asyncio
|
| 2 |
import json
|
|
|
|
| 3 |
import logging
|
| 4 |
import re
|
| 5 |
from typing import AsyncGenerator
|
|
@@ -90,6 +91,21 @@ def _friendly_error(error: BaseException) -> str:
|
|
| 90 |
return f"AI interpretation failed: {text}"
|
| 91 |
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
async def interpret_stream(pipeline_type: str, context: dict) -> AsyncGenerator[str, None]:
|
| 94 |
acompletion = _get_acompletion()
|
| 95 |
if acompletion is None:
|
|
@@ -118,11 +134,18 @@ async def interpret_stream(pipeline_type: str, context: dict) -> AsyncGenerator[
|
|
| 118 |
timeout=25,
|
| 119 |
api_key=candidate["api_key"],
|
| 120 |
)
|
|
|
|
|
|
|
|
|
|
| 121 |
async for chunk in response:
|
| 122 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
return
|
| 127 |
except Exception as e:
|
| 128 |
last_error = e
|
|
@@ -173,7 +196,7 @@ async def interpret_text(pipeline_type: str, context: dict) -> dict:
|
|
| 173 |
)
|
| 174 |
text = response.choices[0].message.content if response.choices else ""
|
| 175 |
if text:
|
| 176 |
-
return {"interpretation": text}
|
| 177 |
except Exception as e:
|
| 178 |
last_error = e
|
| 179 |
logger.warning("LLM provider %s attempt %d failed: %s", candidate["name"], attempt + 1, e)
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import json
|
| 3 |
+
import hashlib
|
| 4 |
import logging
|
| 5 |
import re
|
| 6 |
from typing import AsyncGenerator
|
|
|
|
| 91 |
return f"AI interpretation failed: {text}"
|
| 92 |
|
| 93 |
|
| 94 |
+
def _numeric_grounding(text: str, context: dict) -> dict:
|
| 95 |
+
"""Check numeric presence only; this does not establish biological truth."""
|
| 96 |
+
from app.services.evidence_policy import numbers
|
| 97 |
+
evidence = json.dumps(context, sort_keys=True, separators=(",", ":"), default=str)
|
| 98 |
+
unsupported = set(numbers(text)) - set(numbers(evidence))
|
| 99 |
+
if unsupported:
|
| 100 |
+
raise ValueError("AI explanation contained numeric claims absent from the recorded evidence.")
|
| 101 |
+
return {
|
| 102 |
+
"status": "numeric_fidelity_passed",
|
| 103 |
+
"evidence_sha256": hashlib.sha256(evidence.encode()).hexdigest(),
|
| 104 |
+
"evidence_class": "AI-generated interpretation",
|
| 105 |
+
"limitations": ["Numeric presence does not verify units, attribution, citations, causality or biological correctness."],
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
async def interpret_stream(pipeline_type: str, context: dict) -> AsyncGenerator[str, None]:
|
| 110 |
acompletion = _get_acompletion()
|
| 111 |
if acompletion is None:
|
|
|
|
| 134 |
timeout=25,
|
| 135 |
api_key=candidate["api_key"],
|
| 136 |
)
|
| 137 |
+
# Do not expose an incomplete provider reply or mix it with a
|
| 138 |
+
# backup reply. Admit the complete explanation only after its gate.
|
| 139 |
+
parts = []
|
| 140 |
async for chunk in response:
|
| 141 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 142 |
+
parts.append(chunk.choices[0].delta.content)
|
| 143 |
+
text = "".join(parts)
|
| 144 |
+
if not text.strip():
|
| 145 |
+
raise ValueError("AI provider returned an empty explanation.")
|
| 146 |
+
grounding = _numeric_grounding(text, context)
|
| 147 |
+
yield _chunk_event(text)
|
| 148 |
+
yield _done_event({"model": candidate["model"], "pipeline_type": pipeline_type, "grounding": grounding})
|
| 149 |
return
|
| 150 |
except Exception as e:
|
| 151 |
last_error = e
|
|
|
|
| 196 |
)
|
| 197 |
text = response.choices[0].message.content if response.choices else ""
|
| 198 |
if text:
|
| 199 |
+
return {"interpretation": text, "grounding": _numeric_grounding(text, context)}
|
| 200 |
except Exception as e:
|
| 201 |
last_error = e
|
| 202 |
logger.warning("LLM provider %s attempt %d failed: %s", candidate["name"], attempt + 1, e)
|
app/ai/tool_interpreter.py
CHANGED
|
@@ -61,10 +61,12 @@ _TOOL_PROMPTS: dict[str, str] = {
|
|
| 61 |
"concerns about data quality. 2-4 sentences max."
|
| 62 |
),
|
| 63 |
"md": (
|
| 64 |
-
"You are a computational biophysicist.
|
| 65 |
-
"
|
| 66 |
-
"
|
| 67 |
-
"
|
|
|
|
|
|
|
| 68 |
),
|
| 69 |
"phylo": (
|
| 70 |
"You are an evolutionary biologist. A phylogenetic analysis just completed. "
|
|
@@ -78,9 +80,11 @@ _TOOL_PROMPTS: dict[str, str] = {
|
|
| 78 |
"2-3 sentences max."
|
| 79 |
),
|
| 80 |
"admet": (
|
| 81 |
-
"You are a medicinal chemist.
|
| 82 |
-
"
|
| 83 |
-
"
|
|
|
|
|
|
|
| 84 |
"2-3 sentences max."
|
| 85 |
),
|
| 86 |
"primers": (
|
|
@@ -206,6 +210,12 @@ async def interpret_tool_result(tool_name: str, result: dict) -> dict | None:
|
|
| 206 |
except Exception:
|
| 207 |
return None
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
result_text = _summarize_result(result)
|
| 210 |
|
| 211 |
user_prompt = (
|
|
|
|
| 61 |
"concerns about data quality. 2-4 sentences max."
|
| 62 |
),
|
| 63 |
"md": (
|
| 64 |
+
"You are a computational biophysicist. Explain the recorded engine, "
|
| 65 |
+
"simulation duration and computed observables. State convergence only "
|
| 66 |
+
"when an explicit convergence diagnostic is present; a short or stable "
|
| 67 |
+
"RMSD trace alone does not establish convergence. A simulation does not "
|
| 68 |
+
"establish experimental binding, efficacy or a biological mechanism. "
|
| 69 |
+
"Use only reported results. 2-3 sentences max."
|
| 70 |
),
|
| 71 |
"phylo": (
|
| 72 |
"You are an evolutionary biologist. A phylogenetic analysis just completed. "
|
|
|
|
| 80 |
"2-3 sentences max."
|
| 81 |
),
|
| 82 |
"admet": (
|
| 83 |
+
"You are a medicinal chemist. Separate recorded physicochemical descriptors "
|
| 84 |
+
"and rule-based alerts from predictions made by actually executed ADMET "
|
| 85 |
+
"models. Discuss absorption, metabolism or toxicity only for endpoints "
|
| 86 |
+
"reported by a named model; preserve applicability-domain limitations. "
|
| 87 |
+
"Descriptors and alerts do not establish measured ADMET or clinical safety. "
|
| 88 |
"2-3 sentences max."
|
| 89 |
),
|
| 90 |
"primers": (
|
|
|
|
| 210 |
except Exception:
|
| 211 |
return None
|
| 212 |
|
| 213 |
+
system_prompt += (" Use only the recorded method identity and evidence class. "
|
| 214 |
+
"Missing values mean not reported, never zero. Do not infer "
|
| 215 |
+
"experimental validation, causality or clinical suitability "
|
| 216 |
+
"from computation. Qualitative biological statements must "
|
| 217 |
+
"remain hypotheses unless supported by recorded evidence. "
|
| 218 |
+
"Do not invent citations or links.")
|
| 219 |
result_text = _summarize_result(result)
|
| 220 |
|
| 221 |
user_prompt = (
|