Team Ai
Apppublic

Sanaaashaikh/AI_Food_Safety_Transparency_Environment

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
App README

AI Food Safety Transparency Environment

An OpenEnv-compliant simulation environment where an AI agent makes decisions about restaurant safety visibility on a food delivery platform — balancing user trust, safety risk, and false positives.


Problem

Consumers using food delivery platforms cannot clearly see verified kitchen hygiene and safety standards. While star ratings exist, verified inspection data is often missing or outdated. This environment simulates a system where an AI agent decides how to expose or act on food safety data to maximize user trust while minimizing health risk.


Environment Design

The environment follows the OpenEnv specification with three core methods:

python
env.reset()       # Initialize / restart the episode
env.step(action)  # Apply an action, receive reward + next state
env.state()       # Inspect current state without acting

State Space

Each restaurant is represented as a RestaurantState dataclass:

FieldTypeRangeDescription
hygiene_scorefloat0.0 – 10.0Official hygiene score from last inspection
inspection_age_daysint0 – 730Days since last official inspection
complaintsint0 – 100Food safety complaints in last 30 days
order_volumeint0 – 10,000Orders placed in last 30 days
verification_statusenumverified/pending/unverified/flaggedVerification state
is_flaggedbool—Whether restaurant has been escalated
badge_visiblebool—Whether safety badge is shown to users
inspection_requestedbool—Whether inspection has been triggered

Action Space

ActionDescriptionOptimal When
show_safety_badgeDisplay verified safety badge to usersHygiene ≥ 7, age ≤ 90d, verified
hide_infoHide safety informationUnverified borderline — avoid false trust
request_inspectionTrigger official health inspectionStale data (>180d) or pending status
flag_restaurantEscalate as unsafeHigh risk: hygiene < 5 AND complaints > 8

Reward Logic

The reward is partial (not binary), ranging from -1.0 to +1.0:

Per-Action Rewards

ActionScenarioReward
show_safety_badgeSafe + verified restaurant+1.0
show_safety_badgeSafe but pending verification+0.4
show_safety_badgeGenuinely risky restaurant-0.8
hide_infoRisky + unverified+0.3
hide_infoSafe restaurant-0.5
request_inspectionStale inspection (>180d)+0.9
request_inspectionPending verification+0.7
request_inspectionAlready fresh + safe+0.1
flag_restaurantHigh-risk + many complaints+1.0
flag_restaurantGenuinely risky+0.7
flag_restaurantSafe restaurant (false positive)-1.0

Episode-Level Score (0.0 – 1.0)

final_score = normalize(total_reward)
            + safety_bonus        # +0.1 for correctly flagging all risky restaurants
            - false_pos_penalty   # -0.15 per safe restaurant incorrectly flagged
            + coverage_bonus      # +0.05 for requesting inspections on stale data

Tasks

Easy Task (easy_task)

  • —5 restaurants, 5 steps
  • —Clear-cut cases: pristine hygiene (8-10) with verified recent inspections vs. severely unsafe kitchens (1-3) with stale data and many complaints
  • —Optimal agent should score ≥ 0.85

Medium Task (medium_task)

  • —7 restaurants, 7 steps
  • —Mixed signals: decent hygiene with stale inspections, high complaints despite good scores, pending verifications requiring judgment calls
  • —Optimal agent should score ≥ 0.70

Hard Task (hard_task)

  • —10 restaurants, 10 steps
  • —Adversarial edge cases: near-perfect hygiene scores with 500+ day-old inspections, newly opened restaurants with low scores but fresh checks, high-volume restaurants with hidden complaint spikes
  • —Optimal agent should score ≥ 0.60

Project Structure

food-safety-env/
├── openenv.yaml          # OpenEnv specification
├── inference.py          # End-to-end inference script
├── app.py                # Gradio Hugging Face Spaces UI
├── Dockerfile            # Container definition
├── requirements.txt      # Python dependencies
├── README.md             # This file
└── env/
    ├── __init__.py
    ├── models.py         # Pydantic/dataclass typed models
    ├── environment.py    # OpenEnv FoodSafetyEnv class
    ├── tasks.py          # Easy, medium, hard task definitions
    └── grader.py         # Scoring logic (0.0 – 1.0)

Setup and Run

Local (Python)

bash
# 1. Clone / extract project
cd food-safety-env

# 2. Install dependencies
pip install -r requirements.txt

# 3. Set environment variables
export API_BASE_URL=https://api.openai.com/v1
export MODEL_NAME=gpt-4o-mini
export HF_TOKEN=your_openai_or_hf_token

# 4. Run inference
python inference.py

Without an API key — the script automatically falls back to a deterministic rule-based agent that still demonstrates all environment mechanics.

Docker

bash
# Build
docker build -t food-safety-env .

# Run inference
docker run -e HF_TOKEN=your_token -e MODEL_NAME=gpt-4o-mini food-safety-env

# Run Gradio UI
docker run -p 7860:7860 -e HF_TOKEN=your_token food-safety-env python app.py

Gradio UI (Hugging Face Spaces)

bash
python app.py
# Open http://localhost:7860
  1. 1.Select difficulty (easy / medium / hard)
  2. 2.Press Reset Environment
  3. 3.Choose an action from the dropdown
  4. 4.Press Take Action
  5. 5.Watch scores update in real time

Environment Variables

VariableDescriptionDefault
API_BASE_URLOpenAI-compatible API base URLhttps://api.openai.com/v1
MODEL_NAMELLM model namegpt-4o-mini
HF_TOKENAPI key (OpenAI or HF)""

Expected Output

============================================================
  AI FOOD SAFETY TRANSPARENCY ENVIRONMENT — INFERENCE
============================================================
  Model:    gpt-4o-mini
  Seed:     42

TASK: EASY_TASK | Difficulty: easy
  Step 1: Golden Spoon
    Action:    show_safety_badge
    Reward:    +1.0000 — Correctly showing badge for a safe, verified restaurant.

  TASK SCORE: 0.9250

FINAL SCORES SUMMARY
============================================================
  easy_task            [easy  ] Score: 0.9250  ██████████████████
  medium_task          [medium] Score: 0.7340  ██████████████
  hard_task            [hard  ] Score: 0.6120  ████████████

  Overall Average Score: 0.7570