File size: 8,281 Bytes
b29fc12
 
 
 
 
 
 
 
 
 
428de23
685b77a
b29fc12
47fa380
 
67b6f27
daa0358
 
47fa380
 
308d067
 
 
 
 
 
428de23
 
 
9fbe15f
428de23
308d067
 
47fa380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428de23
47fa380
 
428de23
67b6f27
daa0358
67b6f27
47fa380
 
 
 
 
 
685b77a
428de23
308d067
daa0358
685b77a
47fa380
 
 
685b77a
 
daa0358
47fa380
 
daa0358
 
47fa380
daa0358
 
 
47fa380
daa0358
 
 
 
 
47fa380
 
 
 
 
 
 
 
 
 
45f5063
685b77a
47fa380
 
 
428de23
 
47fa380
 
428de23
685b77a
daa0358
67b6f27
428de23
685b77a
428de23
685b77a
428de23
 
 
 
 
 
685b77a
daa0358
685b77a
428de23
308d067
428de23
308d067
428de23
 
308d067
428de23
 
308d067
428de23
308d067
 
 
428de23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685b77a
428de23
685b77a
428de23
daa0358
47fa380
67b6f27
428de23
 
 
 
 
685b77a
 
428de23
47fa380
428de23
 
47fa380
 
308d067
428de23
47fa380
 
 
 
 
 
 
 
 
 
67b6f27
daa0358
67b6f27
47fa380
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
---
title: MetaGuard Ad Policy Sandbox
emoji: πŸ›‘
colorFrom: blue
colorTo: indigo
sdk: docker
app_port: 8000
pinned: false
license: mit
---
# MetaGuard: A Multi-App RL Environment for Ad Policy Compliance


> An OpenEnv-compatible reinforcement learning environment that forces an LLM agent
> to do **real investigative work** across multiple enterprise APIs β€” not pattern-match.

![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)
![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-blue.svg)
![Framework: OpenEnv + GRPO](https://img.shields.io/badge/Framework-OpenEnv%20%2B%20GRPO-success.svg)

---

## Quick links

| Asset | URL |
| --- | --- |
| **Hugging Face Space** (environment) | [huggingface.co/spaces/parth-1/MetaGuard](https://huggingface.co/spaces/parth-1/MetaGuard) |
| **Hugging Face Space** (GRPO training) | [huggingface.co/spaces/parth-1/MetaGuard-Train](https://huggingface.co/spaces/parth-1/MetaGuard-Train) |
| **Fine-tuned model** (GRPO checkpoint) | [parth-1/metaguard-policy-agent-v1](https://huggingface.co/parth-1/metaguard-policy-agent-v1) |
| **Training Notebook (Kaggle T4)** | [Open in Kaggle](https://www.kaggle.com/code/parthsinghal121/kaggle-grpo-train-ipynb) |
| **Blog post** | [Draft in repo (`docs/metaguard-blog.md`)](https://github.com/Parth380/meta-ad-policy-sandbox/blob/main/docs/metaguard-blog.md) |


---

## TL;DR for Judges

MetaGuard is a **partially observable, multi-application RL environment** modelled
after a real enterprise ad-moderation workflow. The agent (LLM) must orchestrate
calls across 4 microservices (Regulatory, CRM, Audit, Core), update its internal
beliefs based on each tool result, and produce a defensible decision in the
correct procedural order β€” or get penalised.

| Theme 3.1 requirement | How MetaGuard satisfies it |
| --- | --- |
| Real interaction with tools / APIs / dynamic systems | 4 independent FastAPI microservices on ports 8000-8003 |
| "Real hard work, not shortcuts" | Procedural penalties + ambiguity tasks force investigation |
| Maintain consistent internal state | Env tracks `actions_taken`, `signals`, `api_failed`, `trace` |
| Update beliefs based on outcomes | `signals` dict is populated only as the agent acts |
| Orchestrate multi-step workflows | `REQUIRED_BEFORE_TERMINAL` enforces `query_regulations` β†’ `submit_audit` β†’ decide |
| Partially observable world | Agent sees only what its actions reveal; no global view |
| **Scaler AI Labs bonus** | 4-app architecture mirrors a real compliance stack |

---

## The Problem

Single-shot LLM moderation is brittle in enterprise settings:
- **No traceability** β€” no record of *why* a decision was made.
- **No context** β€” no advertiser history, no jurisdiction-specific rules.
- **No risk gating** β€” high-risk content can be approved without an audit trail.

Real compliance teams follow a **procedure**: check policy β†’ inspect creative β†’ verify the advertiser β†’ log the audit β†’ only then decide. MetaGuard makes the agent learn that procedure end-to-end.

---

## Architecture

A 4-service ecosystem that mirrors a real enterprise compliance stack.

```mermaid
graph LR
    subgraph "Agent"
        A[LLM Policy Agent]
    end

    subgraph "MetaGuard Core (OpenEnv)"
        B(Environment Hub :8000)
    end

    subgraph "Enterprise APIs"
        C[[Regulatory API :8001]]
        D[[CRM API :8002]]
        E[[Audit API :8003]]
    end

    A -- "action_type, reasoning" --> B
    B -- "GET /regulations/{cat}" --> C
    B -- "GET /advertiser/{id}" --> D
    B -- "POST /log" --> E

    C -- "policy + violations" --> B
    D -- "risk_score + history" --> B
    E -- "audit_id" --> B

    B -- "obs + reward + signals" --> A
```

| Service | Port | Responsibility | Real-world analog |
| :--- | :--- | :--- | :--- |
| Core Env | `:8000` | State orchestration, reward shaping | Compliance workflow engine |
| Regulatory API | `:8001` | Category-specific policy lookup | Legal / policy database |
| CRM API | `:8002` | Advertiser trust score and history | Salesforce / advertiser CRM |
| Audit API | `:8003` | Immutable audit-log writes | SOX-compliant audit ledger |

*Note: External APIs have a 10% random failure rate. The agent must learn to retry.*

---

## Action Space & Business Rules

8 actions span the full investigative procedure. The environment penalizes shortcuts and rewards real reasoning:

1. **Phase ordering:** `query_regulations` MUST come first. 
2. **Audit gate:** `submit_audit` is required before any `approve` / `reject`.
3. **API-failure recovery:** Recovering from 10% injected API failures earns `+0.3`; ignoring earns `-0.3`.
4. **Risk-aware approvals:** Approving high-risk content (`risk_score > 0.7` AND `policy_confidence > 0.6`) costs `-0.5`.
5. **Ambiguity enforcement:** When `policy_confidence < 0.6`, the agent MUST gather more signals or take a penalty.
6. **Step cap:** Hard cap at 8 steps.

---

## Training & Results

Training uses **[OpenEnv](https://github.com/openenv-ai/openenv)** as the environment, **[Unsloth](https://github.com/unslothai/unsloth)** for fast LoRA fine-tuning, and **[Hugging Face TRL](https://github.com/huggingface/trl)** for GRPO. The trained weights are on the Hub as **[parth-1/metaguard-policy-agent-v1](https://huggingface.co/parth-1/metaguard-policy-agent-v1)**.

### Evaluation Metrics
The model was evaluated across a 4-task suite testing healthcare, financial, multimodal, and targeting policies.

* **Baseline (Pre-GRPO):** Success Rate: 0/4 (0%) | Mean Reward per Step: -0.185
* **Final (Post-GRPO):** Success Rate: 0/4 (0%) | Mean Reward per Step: -0.050

**Conclusion:** The GRPO fine-tuning successfully improved the agent's intermediate signal gathering phase, significantly pulling the mean reward up from the baseline. However, the model still struggles with strict terminal sequence chaining (failing to call `submit_audit` before the final decision).

---

## Quick Start & Inference

### ⚠️ Critical Warning: 422 Schema Errors
The MetaGuard API enforces strict JSON validation (`additionalProperties: false`). Generative models will often hallucinate extra keys, causing the server to throw `422 Unprocessable Entity` errors. You **must** sanitize the LLM output before passing it to the environment.

**Required Parser Patch for `inference.py` / `demo.py`:**
```python
import json

def parse_attempt(text):
    candidates = []
    if "```" in text:
        for p in text.split("```"):
            p = p.strip().lstrip("json").strip()
            candidates.append(p)
    candidates.append(text.strip())
    s, e = text.find("{"), text.rfind("}") + 1
    if s != -1 and e > s:
        candidates.append(text[s:e])
        
    for c in candidates:
        try:
            r = json.loads(c)
            if isinstance(r, dict) and "action_type" in r:
                r.setdefault("reasoning", "No reasoning provided.")
                
                valid_cat = {"HEALTHCARE", "FINANCIAL", "NONE", None}
                if r.get("violation_category") not in valid_cat:
                    r.pop("violation_category", None)
                    
                allowed = {"action_type", "reasoning", "violation_category", "metadata"}
                return {k: v for k, v in r.items() if k in allowed}
        except Exception:
            continue
    return None
```

### 1. Install & Launch
```bash
git clone [https://github.com/Parth380/meta-ad-policy-sandbox.git](https://github.com/Parth380/meta-ad-policy-sandbox.git)
cd meta-ad-policy-sandbox
pip install -e .

# Launch the 4-service stack (Use apps/start_all.bat on Windows)
python apps/regulatory_api.py &
python apps/crm_api.py &
python apps/audit_api.py &
python -m uvicorn server.app:app --host 0.0.0.0 --port 8000
```

### 2. Run Benchmarks or Train
```bash
# Run inference evaluation
export HF_TOKEN=hf_xxxxxxxx
export MODEL_NAME=meta-llama/Meta-Llama-3-8B-Instruct
python inference.py

# Train an agent (Unsloth + TRL GRPO)
python grpo_train.py
```

---

## Hackathon Submission

- **Theme:** 3.1 Professional Tasks β€” Multi-Step Reasoning & Policy Compliance
- **Bonus Track:** Scaler AI Labs β€” Multi-App RL Environment for Enterprise Workflows
- **Team:** Parth Singhal, Mehakveer Kaur, Kartik Goyal

---

## License
MIT.