Upload folder using huggingface_hub
Browse filesFiles changed (8)
18 unmodified lines19202122232418 unmodified lines# Hallucination Detector GymAn **OpenEnv** environment where AI agents learn to detect, classify, and correct hallucinations in LLM-generated text. Built for the [Meta Γ OpenEnv Γ Hugging Face Γ PyTorch Hackathon](https://www.scaler.com/school-of-technology/meta-pytorch-hackathon).**Links:**18 unmodified lines192021222324252627282930313218 unmodified lines# Hallucination Detector Gym[](https://huggingface.co/spaces/williyam/hallucination-detector-gym)[](https://huggingface.co/williyam/hallucination-detector-agent-qwen3-0.6b)[](https://github.com/open-env/openenv)[](https://python.org)[](https://fastapi.tiangolo.com)[](Dockerfile)[](LICENSE)An **OpenEnv** environment where AI agents learn to detect, classify, and correct hallucinations in LLM-generated text. Built for the [Meta Γ OpenEnv Γ Hugging Face Γ PyTorch Hackathon](https://www.scaler.com/school-of-technology/meta-pytorch-hackathon).**Links:**
39 unmodified lines40414243444546474839 unmodified lines# Step efficiency bonus (awarded at submit for finishing early)BONUS_STEP_EFFICIENCY: Final[float] = 0.10# Grader score boundsGRADER_SCORE_MIN: Final[float] = 0.0GRADER_SCORE_MAX: Final[float] = 1.0# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ39 unmodified lines40414243444546474839 unmodified lines# Step efficiency bonus (awarded at submit for finishing early)BONUS_STEP_EFFICIENCY: Final[float] = 0.10# Grader score bounds (strict open interval β never exactly 0 or 1)GRADER_SCORE_MIN: Final[float] = 0.001GRADER_SCORE_MAX: Final[float] = 0.999# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1 unmodified line234567813 unmodified lines2223242526272817 unmodified lines4647484950515226 unmodified lines798081828384851 unmodified lineHallucination Detector Gym β Task Graders.Programmatic graders that score agent performance on each task.Scores range from 0.0 to 1.0 with deterministic, reproducible criteria."""from __future__ import annotations13 unmodified lines"""Deterministic grader for a single task.Runs through a sequence of agent actions and produces a normalisedscore in [0.0, 1.0]."""def __init__(self, task_id: TaskID) -> None:17 unmodified linesactions: Ordered list of actions the agent took during the episode.Returns:A score in [0.0, 1.0]."""engine = RewardEngine(self._task)26 unmodified linesactions_per_task: Mapping from TaskID to the list of actions taken.Returns:Mapping from TaskID to score in [0.0, 1.0]."""results: dict[TaskID, float] = {}for task_id, actions in actions_per_task.items():1 unmodified line2345678913 unmodified lines2324252627282917 unmodified lines4748495051525326 unmodified lines808182838485861 unmodified lineHallucination Detector Gym β Task Graders.Programmatic graders that score agent performance on each task.Scores are strictly between 0 and 1 (exclusive) with deterministic,reproducible criteria."""from __future__ import annotations13 unmodified lines"""Deterministic grader for a single task.Runs through a sequence of agent actions and produces a normalisedscore strictly between 0 and 1 (exclusive)."""def __init__(self, task_id: TaskID) -> None:17 unmodified linesactions: Ordered list of actions the agent took during the episode.Returns:A score strictly between GRADER_SCORE_MIN and GRADER_SCORE_MAX."""engine = RewardEngine(self._task)26 unmodified linesactions_per_task: Mapping from TaskID to the list of actions taken.Returns:Mapping from TaskID to score strictly between 0 and 1."""results: dict[TaskID, float] = {}for task_id, actions in actions_per_task.items():
19 unmodified lines202122232425390 unmodified lines41641741841942042142242342442542642742842943043143219 unmodified linesfrom .constants import (ActionType,HallucinationType,MAX_STEPS_PER_EPISODE,BONUS_STEP_EFFICIENCY,390 unmodified linesreturn reward, feedback_partsdef get_final_score(self) -> float:"""Compute a normalised final score in [0, 1] for grading.Returns:Score between 0.0 and 1.0."""num_annotations = len(self._task.annotations)if num_annotations == 0:return 1.0 if self._cumulative_reward >= 0 else 0.0# Max theoretical reward per annotation:# detect(0.3) + span(0.2) + classify(0.3) + correct(0.2) = 1.0max_reward = num_annotations * 1.0normalised = max(0.0, min(1.0, self._cumulative_reward / max_reward))return round(normalised, 4)19 unmodified lines2021222324252627390 unmodified lines41841942042142242342442542642742842943043143243343443519 unmodified linesfrom .constants import (ActionType,GRADER_SCORE_MAX,GRADER_SCORE_MIN,HallucinationType,MAX_STEPS_PER_EPISODE,BONUS_STEP_EFFICIENCY,390 unmodified linesreturn reward, feedback_partsdef get_final_score(self) -> float:"""Compute a normalised final score in (0, 1) for grading.Returns:Score strictly between GRADER_SCORE_MIN and GRADER_SCORE_MAX."""num_annotations = len(self._task.annotations)if num_annotations == 0:return GRADER_SCORE_MAX if self._cumulative_reward >= 0 else GRADER_SCORE_MIN# Max theoretical reward per annotation:# detect(0.3) + span(0.2) + classify(0.3) + correct(0.2) = 1.0max_reward = num_annotations * 1.0normalised = max(0.0, min(1.0, self._cumulative_reward / max_reward))clamped = max(GRADER_SCORE_MIN, min(GRADER_SCORE_MAX, normalised))return round(clamped, 4)
51 unmodified lines525354555657332 unmodified lines39039139239339439539639739839940051 unmodified linesTEMPERATURE: float = 0.1MAX_TOKENS: int = 800# Benchmark name for structured loggingBENCHMARK: str = "hallucination_detector_gym"332 unmodified linesif final_score is None:cumulative = obs.get("cumulative_reward", 0.0)if cumulative is not None:final_score = max(0.0, min(1.0, cumulative))else:final_score = 0.0final_score = max(0.0, min(1.0, final_score))success = final_score > 0.0# Emit mandatory [END] log51 unmodified lines52535455565758596061332 unmodified lines39439539639739839940040140240340451 unmodified linesTEMPERATURE: float = 0.1MAX_TOKENS: int = 800# Score bounds matching environment grader (strict open interval)_SCORE_MIN: float = 0.001_SCORE_MAX: float = 0.999# Benchmark name for structured loggingBENCHMARK: str = "hallucination_detector_gym"332 unmodified linesif final_score is None:cumulative = obs.get("cumulative_reward", 0.0)if cumulative is not None:final_score = max(_SCORE_MIN, min(_SCORE_MAX, cumulative))else:final_score = _SCORE_MINfinal_score = max(_SCORE_MIN, min(_SCORE_MAX, final_score))success = final_score > 0.0# Emit mandatory [END] log
123 unmodified lines1241251261271281291306 unmodified lines1371381391401411421431441451461471 unmodified line149150151152153154155123 unmodified linesasync def web_root_no_slash():return RedirectResponse(url="/web/")@fastapi_app.get("/web/metadata")async def web_metadata():return web_manager.metadata.model_dump()6 unmodified linesexcept WebSocketDisconnect:await web_manager.disconnect_websocket(websocket)@fastapi_app.post("/web/reset")async def web_reset(request: Optional[Dict[str, Any]] = Body(default=None)):return await web_manager.reset_environment(request)@fastapi_app.post("/web/step")async def web_step(request: Dict[str, Any]):if "message" in request:action_data = {"message": request["message"]}1 unmodified lineaction_data = request.get("action", {})return await web_manager.step_environment(action_data)@fastapi_app.get("/web/state")async def web_state():return web_manager.get_state()123 unmodified lines1241251261271281291306 unmodified lines1371381391401411421431441451461471 unmodified line149150151152153154155123 unmodified linesasync def web_root_no_slash():return RedirectResponse(url="/web/")@fastapi_app.get("/web/metadata", include_in_schema=False)async def web_metadata():return web_manager.metadata.model_dump()6 unmodified linesexcept WebSocketDisconnect:await web_manager.disconnect_websocket(websocket)@fastapi_app.post("/web/reset", include_in_schema=False)async def web_reset(request: Optional[Dict[str, Any]] = Body(default=None)):return await web_manager.reset_environment(request)@fastapi_app.post("/web/step", include_in_schema=False)async def web_step(request: Dict[str, Any]):if "message" in request:action_data = {"message": request["message"]}1 unmodified lineaction_data = request.get("action", {})return await web_manager.step_environment(action_data)@fastapi_app.get("/web/state", include_in_schema=False)async def web_state():return web_manager.get_state()
152 unmodified lines153154155156157158159160161162163164120 unmodified lines28528628728828929011 unmodified lines302303304305306307152 unmodified lines# ββ Callbacks ββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def reset_env():"""Reset the environment and return formatted observation."""try:data = await web_manager.reset_environment()obs_md = _format_hallucination_observation(data)return obs_md, json.dumps(data, indent=2), "Environment reset. Analyse the passage."except Exception as e:return "", "", f"Error: {e}"120 unmodified lines)step_inputs.append(inp)with gr.Row():step_btn = gr.Button("Step", variant="primary")reset_btn = gr.Button("Reset", variant="secondary")11 unmodified lines# ββ Event bindings βββββββββββββββββββββββββββββββββββββββββββββββreset_btn.click(fn=reset_env,outputs=[obs_display, raw_json, status],)step_btn.click(152 unmodified lines153154155156157158159160161162163164165166120 unmodified lines28728828929029129229329429529629729829930030130230330411 unmodified lines316317318319320321322152 unmodified lines# ββ Callbacks ββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def reset_env(task_choice: str | None = None):"""Reset the environment and return formatted observation."""try:request_data = {"task_id": task_choice} if task_choice else Nonedata = await web_manager.reset_environment(request_data)obs_md = _format_hallucination_observation(data)label = task_choice or "default (easy)"return obs_md, json.dumps(data, indent=2), f"Environment reset with task: {label}."except Exception as e:return "", "", f"Error: {e}"120 unmodified lines)step_inputs.append(inp)with gr.Row():task_dropdown = gr.Dropdown(choices=[("Easy β Simple Factual Error", "task_easy_factual"),("Medium β Entity Fabrication + Factual", "task_medium_entity"),("Hard β Multi-type Detection", "task_hard_multi"),],value="task_easy_factual",label="Task",info="Select the task to load on Reset",)with gr.Row():step_btn = gr.Button("Step", variant="primary")reset_btn = gr.Button("Reset", variant="secondary")11 unmodified lines# ββ Event bindings βββββββββββββββββββββββββββββββββββββββββββββββreset_btn.click(fn=reset_env,inputs=[task_dropdown],outputs=[obs_display, raw_json, status],)step_btn.click(
203 unmodified lines20420520620720820921021121221317 unmodified lines2312322332342352362373 unmodified lines24124224324424524624719 unmodified lines26726826927027127227327427527627743 unmodified lines3213223233243253263276 unmodified lines334335336337338339340203 unmodified linesassert abs(engine.cumulative_reward - (r1 + r2)) < 1e-6def test_final_score_in_range(self) -> None:"""Final score must be in [0, 1]."""engine = RewardEngine(TASK_EASY)score = engine.get_final_score()assert 0.0 <= score <= 1.0def test_span_overlap_ratio_identical(self) -> None:"""Identical spans should have overlap 1.0."""17 unmodified lines"""Tests for the task grader."""def test_grader_score_in_range(self) -> None:"""Grader must return score in [0.0, 1.0]."""grader = TaskGrader(TaskID.TASK_EASY)actions = [HallucinationAction(3 unmodified linesHallucinationAction(action_type=ActionType.SUBMIT),]score = grader.grade(actions)assert 0.0 <= score <= 1.0def test_perfect_easy_task_high_score(self) -> None:"""Perfect actions on easy task should yield high score."""19 unmodified linesscore = grader.grade(actions)assert score > 0.7def test_empty_actions_score_zero(self) -> None:"""No actions should produce score 0."""grader = TaskGrader(TaskID.TASK_EASY)score = grader.grade([])assert score == 0.0def test_all_wrong_low_score(self) -> None:"""All wrong actions should yield low score."""43 unmodified lines),HallucinationAction(action_type=ActionType.SUBMIT),])assert 0.0 <= score <= 1.0def test_hard_task_grading(self) -> None:"""Hard task should be gradable."""6 unmodified lines),HallucinationAction(action_type=ActionType.SUBMIT),])assert 0.0 <= score <= 1.0# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ203 unmodified lines20420520620720820921021121221317 unmodified lines2312322332342352362373 unmodified lines24124224324424524624719 unmodified lines26726826927027127227327427527627743 unmodified lines3213223233243253263276 unmodified lines334335336337338339340203 unmodified linesassert abs(engine.cumulative_reward - (r1 + r2)) < 1e-6def test_final_score_in_range(self) -> None:"""Final score must be in (0, 1) strictly."""engine = RewardEngine(TASK_EASY)score = engine.get_final_score()assert 0.0 < score < 1.0def test_span_overlap_ratio_identical(self) -> None:"""Identical spans should have overlap 1.0."""17 unmodified lines"""Tests for the task grader."""def test_grader_score_in_range(self) -> None:"""Grader must return score strictly between 0 and 1."""grader = TaskGrader(TaskID.TASK_EASY)actions = [HallucinationAction(3 unmodified linesHallucinationAction(action_type=ActionType.SUBMIT),]score = grader.grade(actions)assert 0.0 < score < 1.0def test_perfect_easy_task_high_score(self) -> None:"""Perfect actions on easy task should yield high score."""19 unmodified linesscore = grader.grade(actions)assert score > 0.7def test_empty_actions_score_minimum(self) -> None:"""No actions should produce minimum score (not zero)."""grader = TaskGrader(TaskID.TASK_EASY)score = grader.grade([])assert score == 0.001def test_all_wrong_low_score(self) -> None:"""All wrong actions should yield low score."""43 unmodified lines),HallucinationAction(action_type=ActionType.SUBMIT),])assert 0.0 < score < 1.0def test_hard_task_grading(self) -> None:"""Hard task should be gradable."""6 unmodified lines),HallucinationAction(action_type=ActionType.SUBMIT),])assert 0.0 < score < 1.0# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
README.md+8
hallucination_detector_gym/constants.py+3-3
hallucination_detector_gym/graders.py+5-4
hallucination_detector_gym/rewards.py+7-4
inference.py+7-3
server/app.py+4-4
server/gradio_builder.py+18-3
tests/test_environment.py+9-9