PERDYPTO commited on
Update app/services/nim.py
Browse files- app/services/nim.py +72 -32
app/services/nim.py
CHANGED
|
@@ -15,15 +15,16 @@ def _decline_result(mode: str, judge_mode: str) -> dict:
|
|
| 15 |
|
| 16 |
Always returns the same schema as a normal judgment so the frontend
|
| 17 |
can render it with the same code path, just flagged as declined.
|
|
|
|
| 18 |
"""
|
| 19 |
if mode == "image":
|
| 20 |
reason = (
|
| 21 |
-
"
|
| 22 |
"Try adding a written scenario for context, or use a different photo."
|
| 23 |
)
|
| 24 |
else:
|
| 25 |
reason = (
|
| 26 |
-
"
|
| 27 |
"Try rephrasing the scenario or using different evidence."
|
| 28 |
)
|
| 29 |
|
|
@@ -32,7 +33,7 @@ def _decline_result(mode: str, judge_mode: str) -> dict:
|
|
| 32 |
"score": 50,
|
| 33 |
"title": "Couldn't reach a verdict",
|
| 34 |
"summary": reason,
|
| 35 |
-
"reasons": ["
|
| 36 |
"vibe": "unclear",
|
| 37 |
"advice": "Try again with a different photo or a clearer written scenario.",
|
| 38 |
"declined": True,
|
|
@@ -43,9 +44,23 @@ def _decline_result(mode: str, judge_mode: str) -> dict:
|
|
| 43 |
class NIMService:
|
| 44 |
def __init__(self):
|
| 45 |
self.base_url = settings.nvidia_base_url
|
| 46 |
-
self.model = settings.nvidia_model
|
| 47 |
self.timeout = settings.nvidia_timeout
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
def _build_messages(
|
| 50 |
self,
|
| 51 |
mode: str,
|
|
@@ -94,24 +109,14 @@ class NIMService:
|
|
| 94 |
{"role": "user", "content": user_content},
|
| 95 |
]
|
| 96 |
|
| 97 |
-
async def
|
| 98 |
-
|
| 99 |
-
mode: str,
|
| 100 |
-
judge_mode: str,
|
| 101 |
-
scenario: str | None,
|
| 102 |
-
tone: str,
|
| 103 |
-
image_b64: str | None,
|
| 104 |
-
image_mime: str = "image/png",
|
| 105 |
-
) -> dict:
|
| 106 |
-
messages = self._build_messages(mode, judge_mode, scenario, tone, image_b64, image_mime)
|
| 107 |
-
|
| 108 |
payload = {
|
| 109 |
-
"model":
|
| 110 |
"messages": messages,
|
| 111 |
"temperature": 0.7,
|
| 112 |
"max_tokens": 1024,
|
| 113 |
}
|
| 114 |
-
|
| 115 |
headers = {
|
| 116 |
"Authorization": f"Bearer {settings.nvidia_api_key}",
|
| 117 |
"Content-Type": "application/json",
|
|
@@ -126,21 +131,56 @@ class NIMService:
|
|
| 126 |
response.raise_for_status()
|
| 127 |
data = response.json()
|
| 128 |
|
| 129 |
-
|
| 130 |
-
logger.info("NIM raw response received (length=%d)", len(raw_content))
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
"
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
| 143 |
)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
Always returns the same schema as a normal judgment so the frontend
|
| 17 |
can render it with the same code path, just flagged as declined.
|
| 18 |
+
Used only if every model in the fallback chain refuses/fails.
|
| 19 |
"""
|
| 20 |
if mode == "image":
|
| 21 |
reason = (
|
| 22 |
+
"None of the AI models were comfortable making a judgment call from this photo alone. "
|
| 23 |
"Try adding a written scenario for context, or use a different photo."
|
| 24 |
)
|
| 25 |
else:
|
| 26 |
reason = (
|
| 27 |
+
"None of the AI models were comfortable judging this particular input. "
|
| 28 |
"Try rephrasing the scenario or using different evidence."
|
| 29 |
)
|
| 30 |
|
|
|
|
| 33 |
"score": 50,
|
| 34 |
"title": "Couldn't reach a verdict",
|
| 35 |
"summary": reason,
|
| 36 |
+
"reasons": ["All available models declined to evaluate this input."],
|
| 37 |
"vibe": "unclear",
|
| 38 |
"advice": "Try again with a different photo or a clearer written scenario.",
|
| 39 |
"declined": True,
|
|
|
|
| 44 |
class NIMService:
|
| 45 |
def __init__(self):
|
| 46 |
self.base_url = settings.nvidia_base_url
|
|
|
|
| 47 |
self.timeout = settings.nvidia_timeout
|
| 48 |
|
| 49 |
+
# Build the ordered list of models to try. Primary first, then any
|
| 50 |
+
# configured fallbacks, skipping blanks/duplicates.
|
| 51 |
+
candidates = [settings.nvidia_model]
|
| 52 |
+
if settings.nvidia_model_fallback_1:
|
| 53 |
+
candidates.append(settings.nvidia_model_fallback_1)
|
| 54 |
+
if settings.nvidia_model_fallback_2:
|
| 55 |
+
candidates.append(settings.nvidia_model_fallback_2)
|
| 56 |
+
|
| 57 |
+
seen = set()
|
| 58 |
+
self.model_chain = []
|
| 59 |
+
for m in candidates:
|
| 60 |
+
if m and m not in seen:
|
| 61 |
+
self.model_chain.append(m)
|
| 62 |
+
seen.add(m)
|
| 63 |
+
|
| 64 |
def _build_messages(
|
| 65 |
self,
|
| 66 |
mode: str,
|
|
|
|
| 109 |
{"role": "user", "content": user_content},
|
| 110 |
]
|
| 111 |
|
| 112 |
+
async def _call_model(self, model: str, messages: list[dict]) -> str:
|
| 113 |
+
"""Make a single request to one model. Raises on transport/HTTP error."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
payload = {
|
| 115 |
+
"model": model,
|
| 116 |
"messages": messages,
|
| 117 |
"temperature": 0.7,
|
| 118 |
"max_tokens": 1024,
|
| 119 |
}
|
|
|
|
| 120 |
headers = {
|
| 121 |
"Authorization": f"Bearer {settings.nvidia_api_key}",
|
| 122 |
"Content-Type": "application/json",
|
|
|
|
| 131 |
response.raise_for_status()
|
| 132 |
data = response.json()
|
| 133 |
|
| 134 |
+
return data["choices"][0]["message"]["content"]
|
|
|
|
| 135 |
|
| 136 |
+
async def judge(
|
| 137 |
+
self,
|
| 138 |
+
mode: str,
|
| 139 |
+
judge_mode: str,
|
| 140 |
+
scenario: str | None,
|
| 141 |
+
tone: str,
|
| 142 |
+
image_b64: str | None,
|
| 143 |
+
image_mime: str = "image/png",
|
| 144 |
+
) -> dict:
|
| 145 |
+
messages = self._build_messages(mode, judge_mode, scenario, tone, image_b64, image_mime)
|
| 146 |
+
|
| 147 |
+
last_error = None
|
| 148 |
|
| 149 |
+
for i, model in enumerate(self.model_chain):
|
| 150 |
+
try:
|
| 151 |
+
raw_content = await self._call_model(model, messages)
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logger.warning("Model %s failed with transport/HTTP error: %s", model, e)
|
| 154 |
+
last_error = e
|
| 155 |
+
continue # try next model in chain
|
| 156 |
+
|
| 157 |
+
logger.info(
|
| 158 |
+
"Model %s raw response received (length=%d)", model, len(raw_content)
|
| 159 |
)
|
| 160 |
+
|
| 161 |
+
if is_refusal(raw_content):
|
| 162 |
+
logger.warning(
|
| 163 |
+
"Model %s declined the request (length=%d): %s",
|
| 164 |
+
model, len(raw_content), raw_content,
|
| 165 |
+
)
|
| 166 |
+
continue # try next model in chain
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
result = extract_and_validate_json(raw_content)
|
| 170 |
+
if i > 0:
|
| 171 |
+
logger.info("Fell back to model %s successfully", model)
|
| 172 |
+
return result
|
| 173 |
+
except ValueError as e:
|
| 174 |
+
logger.warning(
|
| 175 |
+
"Model %s returned non-JSON response (length=%d): %.500s",
|
| 176 |
+
model, len(raw_content), raw_content,
|
| 177 |
+
)
|
| 178 |
+
last_error = e
|
| 179 |
+
continue # try next model in chain
|
| 180 |
+
|
| 181 |
+
# Every model in the chain refused, errored, or returned unparseable output
|
| 182 |
+
logger.error(
|
| 183 |
+
"All %d model(s) in chain failed/declined. Last error: %s",
|
| 184 |
+
len(self.model_chain), last_error,
|
| 185 |
+
)
|
| 186 |
+
return _decline_result(mode, judge_mode)
|