maxxie114 Claude Sonnet 4.6 commited on
Commit
af6803d
·
1 Parent(s): 2d56484

Fix scientist inference and wire Oracle LLM judge

Browse files

- Fix apply_chat_template TypeError: use tokenize=False + separate
tokenizer call to avoid Jinja template string-indexing error when
Qwen tokenizer expects multimodal content dicts
- Add _generate_judge_verdict() using Anthropic API (ANTHROPIC_API_KEY)
to produce comprehensive Judge Aldric verdicts at episode end
- Wire Oracle judge into _StubEnv.step() replacing stub hardcoded text
- Falls back gracefully if API key not set or anthropic not installed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (1) hide show
  1. server/app.py +135 -8
server/app.py CHANGED
@@ -152,23 +152,26 @@ def _run_scientist_inference(sci_obs: "ScientistObservation", scenario_pack: Any
152
 
153
  with _scientist_lock:
154
  import torch # type: ignore
155
- inputs = _scientist_tokenizer.apply_chat_template(
 
 
 
 
156
  messages,
157
- tokenize=True,
158
  add_generation_prompt=True,
159
- return_tensors="pt",
160
  )
161
- # Move to same device as model
162
  device = next(_scientist_model.parameters()).device
163
- inputs = inputs.to(device)
164
  with torch.no_grad():
165
  outputs = _scientist_model.generate(
166
- input_ids=inputs,
 
167
  max_new_tokens=512,
168
  temperature=0.7,
169
  do_sample=True,
170
  )
171
- generated_ids = outputs[0][inputs.shape[1]:]
172
  raw_text = _scientist_tokenizer.decode(generated_ids, skip_special_tokens=True)
173
 
174
  return parse_scientist_output(raw_text)
@@ -188,6 +191,124 @@ def _generic_scientist_system_prompt() -> str:
188
  f"Return exactly one JSON object with all ScientistAction fields. Allowed action_type values: {allowed}."
189
  )
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  # ---------------------------------------------------------------------------
192
  # Environment factory — prefer ReplicaLabEnv, retain _StubEnv only as fallback
193
  # ---------------------------------------------------------------------------
@@ -311,6 +432,12 @@ class _StubEnv:
311
  self._state.rigor_score = 0.8
312
  self._state.feasibility_score = 0.8
313
  self._state.fidelity_score = 0.8
 
 
 
 
 
 
314
  return StepResult(
315
  observation=self._make_observation(),
316
  reward=reward,
@@ -323,7 +450,7 @@ class _StubEnv:
323
  feasibility=self._state.feasibility_score,
324
  fidelity=self._state.fidelity_score,
325
  ) if done else None,
326
- judge_notes="Stub audit until judge integration lands." if done else None,
327
  verdict=("accept" if self._state.agreement_reached else "revise") if done else None,
328
  round=self._state.round_number,
329
  stub=True,
 
152
 
153
  with _scientist_lock:
154
  import torch # type: ignore
155
+ # Use tokenize=False first to get the formatted string, then tokenize
156
+ # separately. This avoids the Jinja template "string indices must be
157
+ # integers" error that occurs when the tokenizer template expects
158
+ # multimodal content dicts but receives plain strings.
159
+ prompt_text = _scientist_tokenizer.apply_chat_template(
160
  messages,
161
+ tokenize=False,
162
  add_generation_prompt=True,
 
163
  )
 
164
  device = next(_scientist_model.parameters()).device
165
+ enc = _scientist_tokenizer(prompt_text, return_tensors="pt").to(device)
166
  with torch.no_grad():
167
  outputs = _scientist_model.generate(
168
+ input_ids=enc["input_ids"],
169
+ attention_mask=enc["attention_mask"],
170
  max_new_tokens=512,
171
  temperature=0.7,
172
  do_sample=True,
173
  )
174
+ generated_ids = outputs[0][enc["input_ids"].shape[1]:]
175
  raw_text = _scientist_tokenizer.decode(generated_ids, skip_special_tokens=True)
176
 
177
  return parse_scientist_output(raw_text)
 
191
  f"Return exactly one JSON object with all ScientistAction fields. Allowed action_type values: {allowed}."
192
  )
193
 
194
+ # ---------------------------------------------------------------------------
195
+ # Oracle LLM judge — optional; requires ANTHROPIC_API_KEY
196
+ # ---------------------------------------------------------------------------
197
+
198
+ _ORACLE_ENABLED = os.environ.get("REPLICALAB_ORACLE_ENABLED", "1") == "1"
199
+ _ORACLE_MODEL = os.environ.get("REPLICALAB_ORACLE_MODEL", "claude-haiku-4-5-20251001")
200
+
201
+
202
+ def _build_anthropic_client() -> Optional[Any]:
203
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
204
+ if not api_key:
205
+ return None
206
+ try:
207
+ import anthropic # type: ignore
208
+ return anthropic.Anthropic(api_key=api_key)
209
+ except ImportError:
210
+ log.warning("anthropic package not installed — Oracle judge unavailable")
211
+ return None
212
+
213
+
214
+ def _generate_judge_verdict(
215
+ state: "EpisodeState",
216
+ scenario_pack: Any,
217
+ conversation_history: list,
218
+ ) -> str:
219
+ """Call Anthropic to produce Judge Aldric's comprehensive verdict."""
220
+ if not _ORACLE_ENABLED:
221
+ return "Deterministic scoring only. Set REPLICALAB_ORACLE_ENABLED=1 and ANTHROPIC_API_KEY for LLM verdicts."
222
+
223
+ client = _build_anthropic_client()
224
+ if client is None:
225
+ return "No LLM API key configured (ANTHROPIC_API_KEY). Deterministic scoring applied."
226
+
227
+ # Format final protocol
228
+ if state.current_protocol:
229
+ p = state.current_protocol
230
+ protocol_summary = (
231
+ f"Technique: {p.technique}\n"
232
+ f"Sample size: {p.sample_size}\n"
233
+ f"Duration: {p.duration_days} days\n"
234
+ f"Controls: {', '.join(p.controls)}\n"
235
+ f"Equipment: {', '.join(p.required_equipment)}\n"
236
+ f"Reagents: {', '.join(p.required_reagents)}\n"
237
+ f"Rationale: {p.rationale}"
238
+ )
239
+ else:
240
+ protocol_summary = "No concrete protocol was finalized."
241
+
242
+ # Format conversation transcript
243
+ if conversation_history:
244
+ conv_text = "\n".join(
245
+ f"[Round {e.round_number}] {e.role.upper()}: {e.message}"
246
+ for e in conversation_history
247
+ )
248
+ else:
249
+ conv_text = "No conversation recorded."
250
+
251
+ # Scenario context from pack
252
+ scenario_context = ""
253
+ if scenario_pack is not None:
254
+ try:
255
+ sci = scenario_pack.scientist_observation
256
+ lab = scenario_pack.lab_manager_observation
257
+ scenario_context = (
258
+ f"Paper: {getattr(sci, 'paper_title', 'N/A')}\n"
259
+ f"Hypothesis: {getattr(sci, 'paper_hypothesis', 'N/A')}\n"
260
+ f"Goal: {getattr(sci, 'experiment_goal', 'N/A')}\n"
261
+ f"Budget: ${getattr(lab, 'budget_total', '?')}\n"
262
+ f"Time limit: {getattr(lab, 'time_limit_days', '?')} days\n"
263
+ f"Available equipment: {', '.join(getattr(lab, 'equipment_available', []))}\n"
264
+ )
265
+ except Exception:
266
+ scenario_context = "(scenario details unavailable)"
267
+
268
+ outcome = (
269
+ f"Agreement reached after {state.round_number} rounds"
270
+ if state.agreement_reached
271
+ else f"No agreement reached — rounds exhausted ({state.round_number}/{state.max_rounds})"
272
+ )
273
+
274
+ user_prompt = (
275
+ f"Evaluate this scientific replication negotiation and produce a comprehensive judge's verdict.\n\n"
276
+ f"SCENARIO:\n{scenario_context}\n"
277
+ f"OUTCOME: {outcome}\n\n"
278
+ f"FINAL PROTOCOL:\n{protocol_summary}\n\n"
279
+ f"NEGOTIATION TRANSCRIPT:\n{conv_text}\n\n"
280
+ "Write a comprehensive verdict covering:\n"
281
+ "1. Overall assessment (2-3 sentences)\n"
282
+ "2. Scientific rigor of the proposed protocol\n"
283
+ "3. Feasibility within lab constraints\n"
284
+ "4. Fidelity to the original paper's methodology\n"
285
+ "5. Key decisions that shaped the outcome\n"
286
+ "6. Missed opportunities or weaknesses\n"
287
+ "7. How this compares to an optimal negotiation strategy\n\n"
288
+ "Be specific, reference actual protocol details and conversation turns. "
289
+ "Write as Judge Aldric, the impartial arbiter of ReplicaLab."
290
+ )
291
+ system_prompt = (
292
+ "You are Judge Aldric, the impartial arbiter of ReplicaLab — an RL environment where AI scientists "
293
+ "negotiate replication protocols with lab managers under real resource constraints. "
294
+ "Produce comprehensive, evidence-based verdicts evaluating scientific rigor, feasibility, and fidelity. "
295
+ "Be specific, fair, and insightful. Write in clear prose paragraphs."
296
+ )
297
+
298
+ try:
299
+ import anthropic # type: ignore
300
+ response = client.messages.create(
301
+ model=_ORACLE_MODEL,
302
+ max_tokens=1024,
303
+ system=system_prompt,
304
+ messages=[{"role": "user", "content": user_prompt}],
305
+ )
306
+ return response.content[0].text
307
+ except Exception:
308
+ log.exception("Oracle verdict generation failed")
309
+ return "Judge Aldric was unable to render a verdict due to an API error."
310
+
311
+
312
  # ---------------------------------------------------------------------------
313
  # Environment factory — prefer ReplicaLabEnv, retain _StubEnv only as fallback
314
  # ---------------------------------------------------------------------------
 
432
  self._state.rigor_score = 0.8
433
  self._state.feasibility_score = 0.8
434
  self._state.fidelity_score = 0.8
435
+ judge_notes = None
436
+ if done:
437
+ judge_notes = _generate_judge_verdict(
438
+ self._state, self._scenario_pack, self._logs
439
+ )
440
+
441
  return StepResult(
442
  observation=self._make_observation(),
443
  reward=reward,
 
450
  feasibility=self._state.feasibility_score,
451
  fidelity=self._state.fidelity_score,
452
  ) if done else None,
453
+ judge_notes=judge_notes,
454
  verdict=("accept" if self._state.agreement_reached else "revise") if done else None,
455
  round=self._state.round_number,
456
  stub=True,