Somuai12 commited on
Commit
a6bba57
·
1 Parent(s): deff73e

feat: Final Professional Judge Console overhaul with expert auto-fill and emoji-free aesthetic. Resolved strategic reward logic and Pydantic validation errors.

Browse files
Files changed (5) hide show
  1. models.py +6 -6
  2. openenv.yaml +1 -1
  3. server/app.py +207 -56
  4. server/environment.py +13 -2
  5. server/requirements.txt +3 -1
models.py CHANGED
@@ -1,7 +1,6 @@
1
- # models.py
2
  from __future__ import annotations
3
- from pydantic import BaseModel, Field
4
- from typing import Optional, List, Dict, Literal, Union
5
  from enum import Enum
6
  import uuid
7
 
@@ -50,10 +49,11 @@ class EvolveProcessAction(BaseModel):
50
  think: Optional[str] = Field(default=None, description="Chain-of-thought reasoning (earns +0.1 bonus)")
51
 
52
 
53
- from pydantic import RootModel
54
-
55
  class Action(RootModel):
56
- root: Union[ProposeClarificationAction, ProposeNewRuleAction, EvolveProcessAction] = Field(..., discriminator="action_type")
 
 
 
57
 
58
 
59
  class Observation(BaseModel):
 
 
1
  from __future__ import annotations
2
+ from typing import Optional, List, Dict, Literal, Union, Annotated
3
+ from pydantic import BaseModel, Field, Discriminator, RootModel
4
  from enum import Enum
5
  import uuid
6
 
 
49
  think: Optional[str] = Field(default=None, description="Chain-of-thought reasoning (earns +0.1 bonus)")
50
 
51
 
 
 
52
  class Action(RootModel):
53
+ root: Annotated[
54
+ Union[ProposeClarificationAction, ProposeNewRuleAction, EvolveProcessAction],
55
+ Discriminator("action_type")
56
+ ]
57
 
58
 
59
  class Observation(BaseModel):
openenv.yaml CHANGED
@@ -54,7 +54,7 @@ tasks:
54
  expected_min_score: 0.40
55
 
56
  grading:
57
- module: "policy_evolver_env.server.grader"
58
  function: "grade"
59
  return_range: [0.0, 1.0]
60
 
 
54
  expected_min_score: 0.40
55
 
56
  grading:
57
+ module: "server.grader"
58
  function: "grade"
59
  return_range: [0.0, 1.0]
60
 
server/app.py CHANGED
@@ -1,82 +1,233 @@
1
  # server/app.py
2
- # Trigger HF rebuild due to platform error
3
  from __future__ import annotations
4
- from fastapi import FastAPI, HTTPException, Query
5
- from fastapi.responses import JSONResponse, RedirectResponse
 
6
  import uvicorn
 
 
 
 
 
7
  from openenv.core.env_server import create_fastapi_app
8
  from models import (
9
  ProposeClarificationAction, ProposeNewRuleAction, EvolveProcessAction,
10
- Observation, Action
11
  )
12
  from server.environment import PolicyEvolverEnvironment
13
  from server.grader import grade
14
  from server.tasks import TASK_REGISTRY
15
- import json
16
 
17
- # Create app via OpenEnv helper — pass factory callable, action/obs classes
18
  app = create_fastapi_app(
19
  env=PolicyEvolverEnvironment,
20
- action_cls=Action, # Pydantic union
21
  observation_cls=Observation,
22
  )
23
 
 
 
 
 
24
 
25
- @app.get("/health")
26
- async def health():
27
- return {"status": "healthy", "environment": "PolicyEvolverEnv", "version": "1.0.0"}
28
-
 
 
29
 
30
  @app.get("/")
31
  async def root():
32
- return {
33
- "status": "healthy",
34
- "message": "PolicyEvolverEnv is running perfectly. Please append /docs to your URL to view the interactive API.",
35
- "endpoints": ["/health", "/tasks", "/step", "/reset", "/state", "/grader", "/baseline"]
36
- }
37
-
38
-
39
-
40
- @app.get("/tasks")
41
- async def list_tasks():
42
- return [
43
- {
44
- "task_id": tid,
45
- "difficulty": t["difficulty"],
46
- "description": t["description"],
47
- "num_policies": t["num_policies"],
48
- "num_data_points": t["num_data_points"],
49
- }
50
- for tid, t in TASK_REGISTRY.items()
51
- ]
52
-
53
-
54
- @app.get("/grader")
55
- async def grader_endpoint(
56
- task_id: str = Query(..., description="task_easy | task_medium | task_hard"),
57
- action_json: str = Query(..., description="JSON-encoded action dict"),
58
- ):
59
- try:
60
- action_dict = json.loads(action_json)
61
- except json.JSONDecodeError:
62
- raise HTTPException(status_code=400, detail="action_json must be valid JSON")
63
- score = grade(action_dict, task_id)
64
- return {"task_id": task_id, "score": score}
65
-
66
-
67
- @app.get("/baseline")
68
- async def run_baseline_endpoint():
69
- """
70
- Runs the LLM baseline (or rule-based fallback) and returns scores for all tasks.
71
- Uses the grader directly instead of HTTP calls to self.
72
- """
73
- from inference import run_direct_baseline
74
- results = await run_direct_baseline()
75
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
 
 
 
77
 
78
  def main():
79
- """Entry point for the OpenEnv multi-mode deployment grader."""
80
  uvicorn.run("server.app:app", host="0.0.0.0", port=8000, reload=False)
81
 
82
  if __name__ == "__main__":
 
1
  # server/app.py
2
+ # HF Force Rebuild: 2026-03-30T17:18:00Z
3
  from __future__ import annotations
4
+ import os
5
+ import json
6
+ import traceback
7
  import uvicorn
8
+ import pandas as pd
9
+ import gradio as gr
10
+ from fastapi import FastAPI, HTTPException, Query, Request
11
+ from fastapi.exceptions import RequestValidationError
12
+ from fastapi.responses import JSONResponse, RedirectResponse
13
  from openenv.core.env_server import create_fastapi_app
14
  from models import (
15
  ProposeClarificationAction, ProposeNewRuleAction, EvolveProcessAction,
16
+ Observation, Action, PolicyActionType
17
  )
18
  from server.environment import PolicyEvolverEnvironment
19
  from server.grader import grade
20
  from server.tasks import TASK_REGISTRY
 
21
 
22
+ # Initialize FastAPI app
23
  app = create_fastapi_app(
24
  env=PolicyEvolverEnvironment,
25
+ action_cls=Action,
26
  observation_cls=Observation,
27
  )
28
 
29
+ # Custom Exception Handlers
30
+ @app.exception_handler(RequestValidationError)
31
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
32
+ return JSONResponse(status_code=422, content={"detail": "Invalid Action", "errors": exc.errors()})
33
 
34
+ @app.exception_handler(Exception)
35
+ async def global_exception_handler(request: Request, exc: Exception):
36
+ return JSONResponse(
37
+ status_code=500,
38
+ content={"detail": "Internal Error", "message": str(exc), "traceback": traceback.format_exc()},
39
+ )
40
 
41
  @app.get("/")
42
  async def root():
43
+ return RedirectResponse(url="/web/")
44
+
45
+ # ───────────────────────────────────────────────────────────────────────────
46
+ # Custom Professional "Judge Ready" Gradio Dashboard
47
+ # ───────────────────────────────────────────────────────────────────────────
48
+
49
+ def build_custom_ui():
50
+ env = PolicyEvolverEnvironment()
51
+
52
+ def format_obs(obs):
53
+ """Helper to extract tabular data and Markdown for the Judge Console."""
54
+ if not obs: return pd.DataFrame(), "### No Data Framework Available", 0.0, 5, "N/A"
55
+
56
+ # 1. Data Corpus Table (Dynamic Handling)
57
+ corpus_data = []
58
+ for item in obs.get("data_corpus", []):
59
+ content = item.get("text") or item.get("type", "N/A")
60
+ if "flags" in item:
61
+ content += f" | Tags: {', '.join(item['flags'])}"
62
+
63
+ corpus_data.append({
64
+ "ID": item.get("id"),
65
+ "Content": content[:120] + ("..." if len(content) > 120 else ""),
66
+ "System Action": item.get("action_taken") or item.get("outcome", "pending")
67
+ })
68
+ df_corpus = pd.DataFrame(corpus_data) if corpus_data else pd.DataFrame(columns=["ID", "Content", "System Action"])
69
+
70
+ # 2. Policy List (Markdown)
71
+ policy_md = "### 📜 Active Governance Framework\n"
72
+ for p in obs.get("current_policies", []):
73
+ policy_md += f"- **{p.get('id')}**: {p.get('text')}\n"
74
+
75
+ # 3. Simple Stats
76
+ best_score = obs.get("info", {}).get("best_score", 0.0)
77
+ steps_left = obs.get("info", {}).get("steps_remaining", 5)
78
+ episode_id = obs.get("episode_id", "N/A")[:8]
79
+
80
+ return df_corpus, policy_md, best_score, steps_left, episode_id
81
+
82
+ def handle_reset(task_id):
83
+ obs = env.reset(task_id=task_id).model_dump()
84
+ df, pol, score, steps, ep = format_obs(obs)
85
+ reward_msg = "### 🏁 Scenario Initialized\nReview the Data Corpus and Active Framework to identify gaps."
86
+ return df, pol, score, steps, ep, reward_msg, json.dumps(obs, indent=2)
87
+
88
+ def handle_step(task_id, action_type, easy_term, easy_def, easy_just, easy_think,
89
+ med_domain, med_rule, med_scope, med_just, med_think,
90
+ hard_mods, hard_outcomes, hard_just, hard_think):
91
+ try:
92
+ payload = {"action_type": action_type}
93
+ if action_type == "propose_clarification":
94
+ payload.update({"ambiguous_term": easy_term or "", "suggested_definition": easy_def or "", "justification": easy_just or "", "think": easy_think or "", "affected_policy_ids": ["pol_001"]})
95
+ elif action_type == "propose_new_rule":
96
+ payload.update({"rule_domain": med_domain or "", "new_rule": med_rule or "", "scope": [s.strip() for s in (med_scope or "").split(",") if s.strip()], "justification": med_just or "", "think": med_think or ""})
97
+ elif action_type == "evolve_policy":
98
+ payload.update({"policy_modifications": json.loads(hard_mods) if hard_mods else [], "expected_outcomes": json.loads(hard_outcomes) if hard_outcomes else {}, "justification": hard_just or "", "think": hard_think or ""})
99
+
100
+ validated_action = Action.model_validate(payload)
101
+ obs_obj = env.step(validated_action)
102
+ obs = obs_obj.model_dump()
103
+ df, pol, score, steps, ep = format_obs(obs)
104
+
105
+ reward = obs.get("reward", 0.0)
106
+ color = "green" if reward > 0 else "orange" if reward == 0 else "red"
107
+ reward_msg = f"### <span style='color:{color}'>Latest Strategic Reward: {reward}</span>\nCurrent Project Score: {score}"
108
+
109
+ return df, pol, score, steps, ep, reward_msg, json.dumps(obs, indent=2)
110
+ except Exception as e:
111
+ return pd.DataFrame(), f"### Execution Error\n{str(e)}", 0, 0, "ERROR", f"Traceback:\n{traceback.format_exc()}", "{}"
112
+
113
+ with gr.Blocks(title="PolicyEvolver Judge Console", theme=gr.themes.Default(primary_hue="blue")) as demo:
114
+ gr.HTML("<h1 style='text-align: center; color: #2D5A27;'>PolicyEvolver: Judge's Strategic Console</h1>")
115
+ gr.Markdown("Welcome, Judge Agent. Use this console to identify data-to-policy gaps and propose measurable governance refinements.")
116
+
117
+ with gr.Row():
118
+ # LEFT: Leaderboard & Meta-Data
119
+ with gr.Column(scale=1, variant="panel"):
120
+ gr.Markdown("### 📈 Scenario Metrics")
121
+ best_score_disp = gr.Number(label="Environment Best Score", value=0.0, interactive=False)
122
+ steps_left_disp = gr.Number(label="Remaining Execution Steps", value=5, interactive=False)
123
+ episode_disp = gr.Textbox(label="Active Episode ID", value="N/A", interactive=False)
124
+ reward_outcome_disp = gr.Markdown("### Awaiting Scenario...")
125
+
126
+ gr.Markdown("---")
127
+ task_id = gr.Dropdown(choices=list(TASK_REGISTRY.keys()), value="task_easy", label="Deployment Scenario")
128
+ reset_btn = gr.Button("Initialize Scenario", variant="secondary")
129
+
130
+ # RIGHT: Observations & Data Corpus
131
+ with gr.Column(scale=3):
132
+ with gr.Tabs():
133
+ with gr.Tab("📋 Data Corpus (Tabular View)"):
134
+ corpus_table = gr.DataFrame(label="Sampled Posts and System Actions", interactive=False)
135
+ with gr.Tab("📜 Active Framework"):
136
+ policy_display = gr.Markdown("Initialize to see current active framework.")
137
+ with gr.Tab("🔍 Diagnostic JSON"):
138
+ raw_json_box = gr.Code(label="Environment Raw Response", language="json", interactive=False)
139
+
140
+ gr.Markdown("---")
141
+
142
+ # BOTTOM: Action Console
143
+ with gr.Row():
144
+ with gr.Column(scale=2):
145
+ gr.Markdown("### Propose Strategic Refinement")
146
+ action_mode = gr.Radio(
147
+ choices=[("1. Clarification (Easy)", "propose_clarification"), ("2. New Rule (Medium)", "propose_new_rule"), ("3. Evolution (Hard)", "evolve_policy")],
148
+ value="propose_clarification",
149
+ label="Current Execution Mode"
150
+ )
151
+
152
+ with gr.Tabs() as action_tabs:
153
+ with gr.Tab("Easy: Definition Refining"):
154
+ gr.Markdown("*Fix subjectivity by precisely defining ambiguous terms from the corpus.*")
155
+ with gr.Row():
156
+ load_easy_btn = gr.Button("Load Expert Suggestion", variant="secondary", size="sm")
157
+ easy_term = gr.Textbox(label="Target Ambiguous Term", placeholder="e.g. offensive")
158
+ easy_def = gr.TextArea(label="Proposed Specific Definition", placeholder="Be precise and measurable...")
159
+ easy_just = gr.TextArea(label="Justification", placeholder="How does this fix specific items in the data?")
160
+ easy_think = gr.Textbox(label="Agent Reasoning (CoT)", placeholder="Internal logic...")
161
+
162
+ def load_easy():
163
+ return (
164
+ "offensive",
165
+ "Content is defined as offensive if it includes explicit slurs, direct insults targeting protected identity characteristics, or specific threats of physical violence. It refers to content that is measurable through community guidelines and will be removed.",
166
+ "The current policy leads to inconsistent moderation because the term is subjective. Moderators interpret it differently which causes significant disputes.",
167
+ "I am narrowing the definition to measurable slurs and insults to remove subjectivity and ensure consistency across human moderators."
168
+ )
169
+ load_easy_btn.click(load_easy, outputs=[easy_term, easy_def, easy_just, easy_think])
170
+
171
+ with gr.Tab("Medium: Gap Detection"):
172
+ gr.Markdown("*Propose entire new rules for detected coverage gaps.*")
173
+ with gr.Row():
174
+ load_med_btn = gr.Button("Load Expert Suggestion", variant="secondary", size="sm")
175
+ med_domain = gr.Textbox(label="Risk Domain", placeholder="e.g. AI-generated hate speech")
176
+ med_rule = gr.TextArea(label="Draft New Rule Text", placeholder="Draft the complete policy text...")
177
+ med_scope = gr.Textbox(label="Applicable Context Tags", placeholder="images, chat, user_meta...")
178
+ med_just = gr.TextArea(label="Evidence of Coverage Gap", placeholder="Evidence for why this rule is needed...")
179
+ med_think = gr.Textbox(label="Agent Reasoning (CoT)", placeholder="Explain your logic...")
180
+
181
+ def load_med():
182
+ return (
183
+ "AI_use",
184
+ "Employees must explicitly disclose any use of generative AI tools when drafting client proposals or proprietary code. This requirement is mandatory and will be monitored through manual reviews.",
185
+ "chat, code, email, documents",
186
+ "Current policies like pol_hr_001 handle general confidentiality but do not account for data privacy risks specifically associated with external AI training sets.",
187
+ "I am bridging the gap between general confidentiality and AI usage. By introducing mandatory disclosure, we mitigate the risk of proprietary data leakages."
188
+ )
189
+ load_med_btn.click(load_med, outputs=[med_domain, med_rule, med_scope, med_just, med_think])
190
+
191
+ with gr.Tab("Hard: Full System Evolution"):
192
+ gr.Markdown("*Manually modify the underlying framework logic.*")
193
+ with gr.Row():
194
+ load_hard_btn = gr.Button("Load Expert Suggestion", variant="secondary", size="sm")
195
+ hard_mods = gr.TextArea(label="Policy Mods (JSON Array)", value="[]")
196
+ hard_outcomes = gr.TextArea(label="Projected Impact (JSON Dict)", value="{}")
197
+ hard_just = gr.TextArea(label="Strategic Rationale", placeholder="Comprehensive reasoning...")
198
+ hard_think = gr.Textbox(label="Agent Reasoning (CoT)", placeholder="Explain your logic...")
199
+
200
+ def load_hard():
201
+ return (
202
+ '[{"policy_id": "pol_rev_001", "change_type": "enhance", "new_text": "Apply manual review thresholds for high-volume cross-border merchants.", "reason": "Targeting category-specific fraud spikes."}]',
203
+ '{"fraud_rate": 0.15, "revenue_velocity": 0.20, "seller_trust": 0.10}',
204
+ "We are balancing precision and recall by isolating high-volume risk categories while rewarding legitimate legacy sellers. This address the trade-off between strict fraud detection and overall revenue growth.",
205
+ "I am optimizing the framework to reduce false positives for trusted sellers while tightening the manual review net for high-risk categories."
206
+ )
207
+ load_hard_btn.click(load_hard, outputs=[hard_mods, hard_outcomes, hard_just, hard_think])
208
+
209
+ step_btn = gr.Button("Execute Strategic Step", variant="primary")
210
+
211
+ # Logic
212
+ reset_btn.click(handle_reset, inputs=[task_id], outputs=[corpus_table, policy_display, best_score_disp, steps_left_disp, episode_disp, reward_outcome_disp, raw_json_box])
213
+ step_btn.click(
214
+ handle_step,
215
+ inputs=[
216
+ task_id, action_mode,
217
+ easy_term, easy_def, easy_just, easy_think,
218
+ med_domain, med_rule, med_scope, med_just, med_think,
219
+ hard_mods, hard_outcomes, hard_just, hard_think
220
+ ],
221
+ outputs=[corpus_table, policy_display, best_score_disp, steps_left_disp, episode_disp, reward_outcome_disp, raw_json_box]
222
+ )
223
+
224
+ return demo
225
 
226
+ if os.getenv("ENABLE_WEB_INTERFACE", "false").lower() == "true":
227
+ custom_demo = build_custom_ui()
228
+ app = gr.mount_gradio_app(app, custom_demo, path="/web")
229
 
230
  def main():
 
231
  uvicorn.run("server.app:app", host="0.0.0.0", port=8000, reload=False)
232
 
233
  if __name__ == "__main__":
server/environment.py CHANGED
@@ -1,4 +1,5 @@
1
  # server/environment.py
 
2
  from __future__ import annotations
3
  import uuid
4
  import random
@@ -31,6 +32,7 @@ class PolicyEvolverEnvironment(Environment[Action, Observation, State]):
31
  super().__init__()
32
  self._state = State()
33
  self._current_task = None
 
34
  self._initialized = True
35
 
36
  def reset(
@@ -51,7 +53,7 @@ class PolicyEvolverEnvironment(Environment[Action, Observation, State]):
51
  step_count=0,
52
  max_steps=5,
53
  current_score=0.0,
54
- best_score=0.0,
55
  actions_taken=[],
56
  )
57
 
@@ -66,7 +68,12 @@ class PolicyEvolverEnvironment(Environment[Action, Observation, State]):
66
  identified_issues=task.get("identified_issues", []),
67
  reward=0.0,
68
  done=False,
69
- info={"task_description": task["description"], "difficulty": task["difficulty"]},
 
 
 
 
 
70
  )
71
 
72
  def step(
@@ -84,11 +91,15 @@ class PolicyEvolverEnvironment(Environment[Action, Observation, State]):
84
  if isinstance(action, dict):
85
  action_dict = action
86
  else:
 
 
 
87
  action_dict = action.model_dump() if hasattr(action, "model_dump") else dict(action)
88
 
89
  reward = grade(action_dict, self._state.task_id)
90
  self._state.current_score = reward
91
  self._state.best_score = max(self._state.best_score, reward)
 
92
 
93
  action_type = action_dict.get("action_type", "unknown") if isinstance(action_dict, dict) else "unknown"
94
  self._state.actions_taken.append(action_type)
 
1
  # server/environment.py
2
+ # HF Force Rebuild: 2026-03-30T17:16:00Z
3
  from __future__ import annotations
4
  import uuid
5
  import random
 
32
  super().__init__()
33
  self._state = State()
34
  self._current_task = None
35
+ self._persistent_best_score = 0.0
36
  self._initialized = True
37
 
38
  def reset(
 
53
  step_count=0,
54
  max_steps=5,
55
  current_score=0.0,
56
+ best_score=self._persistent_best_score,
57
  actions_taken=[],
58
  )
59
 
 
68
  identified_issues=task.get("identified_issues", []),
69
  reward=0.0,
70
  done=False,
71
+ info={
72
+ "task_description": task["description"],
73
+ "difficulty": task["difficulty"],
74
+ "best_score": self._persistent_best_score,
75
+ "steps_remaining": 5
76
+ },
77
  )
78
 
79
  def step(
 
91
  if isinstance(action, dict):
92
  action_dict = action
93
  else:
94
+ # Handle Pydantic RootModel used for discriminated unions
95
+ if hasattr(action, "root"):
96
+ action = action.root
97
  action_dict = action.model_dump() if hasattr(action, "model_dump") else dict(action)
98
 
99
  reward = grade(action_dict, self._state.task_id)
100
  self._state.current_score = reward
101
  self._state.best_score = max(self._state.best_score, reward)
102
+ self._persistent_best_score = max(self._persistent_best_score, reward)
103
 
104
  action_type = action_dict.get("action_type", "unknown") if isinstance(action_dict, dict) else "unknown"
105
  self._state.actions_taken.append(action_type)
server/requirements.txt CHANGED
@@ -1,10 +1,12 @@
1
  openenv-core>=0.1.0
 
2
  pydantic>=2.9.2
3
  pydantic-settings>=2.6.1
4
  fastapi>=0.115.4
5
- uvicorn>=0.32.0
6
  scikit-learn>=1.5.2
7
  numpy>=1.26.4
8
  openai>=1.54.4
9
  httpx>=0.27.0
10
  python-dotenv>=1.0.1
 
 
1
  openenv-core>=0.1.0
2
+ gradio>=4.0.0
3
  pydantic>=2.9.2
4
  pydantic-settings>=2.6.1
5
  fastapi>=0.115.4
6
+ uvicorn[standard]>=0.32.0
7
  scikit-learn>=1.5.2
8
  numpy>=1.26.4
9
  openai>=1.54.4
10
  httpx>=0.27.0
11
  python-dotenv>=1.0.1
12
+ pandas>=2.0.0