File size: 21,003 Bytes
8cd3fa7 8520614 8cd3fa7 8520614 666d07a 8520614 511f04a 8520614 8cd3fa7 a541c0b 8cd3fa7 6aa8acb 8cd3fa7 a541c0b 8cd3fa7 6aa8acb 8cd3fa7 8520614 8cd3fa7 6aa8acb 8520614 8cd3fa7 8520614 8cd3fa7 f6f583b 6aa8acb c8aa313 6aa8acb 511f04a 6aa8acb 4c68ece 6aa8acb 511f04a 09a9c72 511f04a 47a298a 511f04a 6aa8acb 4c68ece 6aa8acb 511f04a 6aa8acb 4c68ece 6aa8acb 4c68ece 292424c 6aa8acb f6f583b 8520614 6aa8acb 8520614 6aa8acb 8520614 6aa8acb 8520614 a5522cd d78cfdc 8085f66 d78cfdc 8085f66 d78cfdc 8520614 6aa8acb d78cfdc 8520614 d78cfdc 8520614 d78cfdc 8520614 d78cfdc 8520614 d78cfdc 8520614 8085f66 8520614 6aa8acb 199d538 6aa8acb 8520614 d78cfdc 8520614 6aa8acb 8520614 6aa8acb 8520614 6aa8acb 8520614 8eede32 6aa8acb 8eede32 6aa8acb 8eede32 6aa8acb 8eede32 6aa8acb d78cfdc 6aa8acb 8eede32 6aa8acb 8eede32 6aa8acb 8eede32 6aa8acb 8eede32 6aa8acb 8520614 d78cfdc 8520614 666d07a 9e34c41 666d07a 706dca3 47a298a 666d07a | 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | # server/app.py
# HF Force Rebuild: 2026-03-30T17:18:00Z
from __future__ import annotations
import os
import json
import traceback
import uvicorn
import pandas as pd
import gradio as gr
from fastapi import FastAPI, HTTPException, Query, Request, Body
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, RedirectResponse
from openenv.core.env_server import create_fastapi_app
from models import (
ProposeClarificationAction, ProposeNewRuleAction, EvolveProcessAction,
Observation, Action, PolicyActionType, TaskInfo
)
from server.environment import PolicyEvolverEnvironment
from server.grader import grade
from server.tasks import TASK_REGISTRY
# Initialize Environment and FastAPI app
env = PolicyEvolverEnvironment()
app = create_fastapi_app(
env=PolicyEvolverEnvironment,
action_cls=Action,
observation_cls=Observation,
)
# Remove default routes to avoid collision with custom overrides below
app.router.routes = [r for r in app.router.routes if r.path not in ["/health", "/state", "/tasks", "/grader", "/baseline"]]
# Custom Exception Handlers
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(status_code=422, content={"detail": "Invalid Action", "errors": exc.errors()})
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"detail": "Internal Error", "message": str(exc), "traceback": traceback.format_exc()},
)
@app.get("/")
async def root():
"""Root endpoint for automated pings to return 200 OK."""
return {"message": "PolicyEvolverEnv is running", "status": "ok"}
@app.get("/health")
async def health():
return {"status": "healthy"}
@app.get("/state")
def get_state():
"""Return the current environment state."""
return {
"episode_id": env.state.episode_id,
"step_count": env.state.step_count,
"max_steps": env.state.max_steps,
"current_score": env.state.current_score
}
@app.get("/tasks")
def list_tasks() -> list[TaskInfo]:
"""Return all tasks with their action schema."""
return [
TaskInfo(
task_id=tid,
difficulty=task["difficulty"],
description=task["description"],
action_schema=Action.model_json_schema(),
)
for tid, task in TASK_REGISTRY.items()
]
@app.post("/grader")
def get_grader_score(task_id: str = Body(...), action: dict = Body(...)):
"""
Grade a submission directly.
"""
if task_id not in TASK_REGISTRY:
raise HTTPException(status_code=404, detail=f"Unknown task_id: {task_id}")
score = grade(action, task_id)
return {
"task_id": task_id,
"score": score,
"passed": 1 if score > 0.5 else 0, # Hackathon-appropriate proxy
"total": 1
}
@app.get("/baseline")
def run_baseline_route():
"""
Run the baseline agent on all tasks and return scores.
"""
import subprocess, sys, os, re
try:
env_vars = {
**os.environ,
"API_KEY": os.environ.get("API_KEY", ""),
"API_BASE_URL": os.environ.get("API_BASE_URL", ""),
"MODEL_NAME": os.environ.get("MODEL_NAME", "llama-3.1-8b-instant"),
"ENV_BASE_URL": "http://127.0.0.1:8000",
}
result = subprocess.run(
[sys.executable, "inference.py"],
capture_output=True,
text=True,
timeout=1200,
env=env_vars,
cwd=os.path.dirname(os.path.abspath(__file__)) + "/.."
)
# Parse [END] lines from stdout to extract scores
scores = []
for line in result.stdout.splitlines():
if line.startswith("[END]"):
m = re.search(r"score=([\d.]+)", line)
if m:
scores.append(float(m.group(1)))
avg = sum(scores) / len(scores) if scores else 0.0
return {
"baseline_results": scores,
"average_score": round(avg, 4),
"model": os.environ.get("MODEL_NAME", "llama-3.1-8b-instant"),
"stdout": result.stdout[-2000:] if result.stdout else "",
"stderr": result.stderr[-2000:] if result.stderr else "",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Custom Professional "Judge Ready" Gradio Dashboard
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_custom_ui():
env = PolicyEvolverEnvironment()
def format_obs(obs):
"""Helper to extract tabular data and Markdown for the Judge Console."""
if not obs: return pd.DataFrame(), "### No Data Framework Available", 0.0, 5, "N/A"
# 1. Data Corpus Table (Dynamic Handling)
corpus_data = []
for item in obs.get("data_corpus", []):
content = item.get("content") or item.get("text") or item.get("type", "N/A")
if "flags" in item:
content += f" | Tags: {', '.join(item['flags'])}"
if "desc" in item:
content += f" | Info: {item['desc']}"
corpus_data.append({
"ID": item.get("id"),
"Content": content[:120] + ("..." if len(content) > 120 else ""),
"System Action": item.get("system_action") or item.get("action_taken") or item.get("outcome", "pending")
})
df_corpus = pd.DataFrame(corpus_data) if corpus_data else pd.DataFrame(columns=["ID", "Content", "System Action"])
# 2. Policy List (Markdown)
policy_md = "### π Active Governance Framework\n"
for p in obs.get("current_policies", []):
policy_md += f"- **{p.get('id')}**: {p.get('text')}\n"
# 3. Simple Stats & Reward History
history = obs.get("info", {}).get("rewards_history", [])
# Always include point (0,0) to ensure a visible line from episode start
df_reward = pd.DataFrame({
"Step": [0] + [i + 1 for i in range(len(history))],
"Reward": [0.0] + [float(r) for r in history]
})
best_score = obs.get("info", {}).get("best_score", 0.0)
steps_left = obs.get("info", {}).get("steps_remaining", 5)
episode_id = obs.get("episode_id", "N/A")[:8]
shown = obs.get("corpus_shown", len(corpus_data))
total = obs.get("corpus_size", len(corpus_data))
corpus_stat = f"### π Corpus: **{shown}** of **{total}** incidents displayed"
return df_corpus, policy_md, best_score, steps_left, episode_id, corpus_stat, df_reward
def handle_reset(task_id):
obs = env.reset(task_id=task_id).model_dump()
df, pol, score, steps, ep, stat, df_hist = format_obs(obs)
reward_msg = "### π Scenario Initialized\nReview the Data Corpus and Active Framework to identify gaps."
return df, pol, score, steps, ep, stat, df_hist, reward_msg, json.dumps(obs, indent=2)
def handle_step(task_id, action_type, easy_term, easy_def, easy_just, easy_think,
med_domain, med_rule, med_scope, med_just, med_think,
hard_mods, hard_outcomes, hard_just, hard_think):
try:
payload = {"action_type": action_type}
if action_type == "propose_clarification":
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"]})
elif action_type == "propose_new_rule":
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 ""})
elif action_type == "evolve_policy":
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 ""})
validated_action = Action.model_validate(payload)
obs_obj = env.step(validated_action)
obs = obs_obj.model_dump()
df, pol, score, steps, ep, stat, df_hist = format_obs(obs)
reward = obs.get("reward", 0.0)
color = "green" if reward > 0 else "orange" if reward == 0 else "red"
reward_msg = f"### <span style='color:{color}'>Latest Strategic Reward: {reward}</span>\nCurrent Project Score: {score}"
return df, pol, score, steps, ep, stat, df_hist, reward_msg, json.dumps(obs, indent=2)
except Exception as e:
err_df = pd.DataFrame({"Step": [0], "Reward": [0.0]})
return pd.DataFrame(), f"### Execution Error\n{str(e)}", 0, 0, "ERROR", "### ERROR", err_df, f"Traceback:\n{traceback.format_exc()}", "{}"
with gr.Blocks(
title="PolicyEvolver Judge Console",
) as demo:
gr.HTML("<h1 style='text-align: center; color: #2D5A27;'>PolicyEvolver: Judge's Strategic Console</h1>")
gr.Markdown("Welcome, Judge Agent. Use this console to identify data-to-policy gaps and propose measurable governance refinements.")
with gr.Row():
# LEFT: Leaderboard & Meta-Data
with gr.Column(scale=1, variant="panel"):
gr.Markdown("### π Scenario Metrics")
best_score_disp = gr.Number(label="Environment Best Score", value=0.0, interactive=False)
steps_left_disp = gr.Number(label="Remaining Execution Steps", value=5, interactive=False)
episode_disp = gr.Textbox(label="Active Episode ID", value="N/A", interactive=False)
gr.Markdown("### π Reward Evolution")
reward_plot = gr.LinePlot(
label="Strategic Reward Trend",
x="Step",
y="Reward",
tooltip=["Step", "Reward"],
)
reward_outcome_disp = gr.Markdown("### Awaiting Scenario...")
gr.Markdown("---")
task_id = gr.Dropdown(choices=list(TASK_REGISTRY.keys()), value="task_easy", label="Deployment Scenario")
reset_btn = gr.Button("Initialize Scenario", variant="secondary")
# RIGHT: Observations & Data Corpus
with gr.Column(scale=3):
corpus_count_disp = gr.Markdown("### π Corpus: 0 of 0 incidents displayed")
with gr.Tabs():
with gr.Tab("π Data Corpus (Tabular View)"):
corpus_table = gr.DataFrame(label="Sampled Posts and System Actions", interactive=False)
with gr.Tab("π Active Framework"):
policy_display = gr.Markdown("Initialize to see current active framework.")
with gr.Tab("π Diagnostic JSON"):
raw_json_box = gr.Code(label="Environment Raw Response", language="json", interactive=False)
gr.Markdown("---")
# BOTTOM: Action Console
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### Propose Strategic Refinement")
action_mode = gr.Radio(
choices=[("1. Clarification (Easy)", "propose_clarification"), ("2. New Rule (Medium)", "propose_new_rule"), ("3. Evolution (Hard)", "evolve_policy")],
value="propose_clarification",
label="Current Execution Mode"
)
with gr.Tabs() as action_tabs:
with gr.Tab("Easy: Definition Refining"):
gr.Markdown("*Fix subjectivity by precisely defining ambiguous terms from the corpus.*")
with gr.Row():
load_easy_btn = gr.Button("Load Expert Suggestion", variant="secondary", size="sm")
easy_term = gr.Textbox(label="Target Ambiguous Term", placeholder="e.g. offensive")
easy_def = gr.TextArea(label="Proposed Specific Definition", placeholder="Be precise and measurable...")
easy_just = gr.TextArea(label="Justification", placeholder="How does this fix specific items in the data?")
easy_think = gr.Textbox(label="Agent Reasoning (CoT)", placeholder="Internal logic...")
def load_easy():
return (
"offensive",
"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.",
"The current policy leads to inconsistent moderation because the term is subjective. Moderators interpret it differently which causes significant disputes.",
"I am narrowing the definition to measurable slurs and insults to remove subjectivity and ensure consistency across human moderators."
)
load_easy_btn.click(load_easy, outputs=[easy_term, easy_def, easy_just, easy_think])
with gr.Tab("Medium: Gap Detection"):
gr.Markdown("*Propose entire new rules for detected coverage gaps.*")
with gr.Row():
load_med_btn = gr.Button("Load Expert Suggestion", variant="secondary", size="sm")
med_domain = gr.Textbox(label="Risk Domain", placeholder="e.g. AI-generated hate speech")
med_rule = gr.TextArea(label="Draft New Rule Text", placeholder="Draft the complete policy text...")
med_scope = gr.Textbox(label="Applicable Context Tags", placeholder="images, chat, user_meta...")
med_just = gr.TextArea(label="Evidence of Coverage Gap", placeholder="Evidence for why this rule is needed...")
med_think = gr.Textbox(label="Agent Reasoning (CoT)", placeholder="Explain your logic...")
def load_med(task_id):
if task_id == "task_hard":
return (
"seller_legitimacy",
"Sellers with fewer than 30 days of history and more than 20 sales per day must complete enhanced identity verification before withdrawals are processed.",
"marketplace, fraud, seller_onboarding, payments",
"Cases h_leg_001 and h_leg_005 show that rapid sales velocity combined with zero return history is a known fraud pattern not covered by current policies.",
"The corpus shows multiple high-velocity new seller patterns. The gap is the absence of velocity-based verification triggers in the onboarding policy."
)
return (
"AI_use",
"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.",
"chat, code, email, documents",
"Current policies like pol_hr_001 handle general confidentiality but do not account for data privacy risks specifically associated with external AI training sets.",
"I am bridging the gap between general confidentiality and AI usage. By introducing mandatory disclosure, we mitigate the risk of proprietary data leakages."
)
load_med_btn.click(load_med, inputs=[task_id], outputs=[med_domain, med_rule, med_scope, med_just, med_think])
with gr.Tab("Hard: Full System Evolution"):
gr.Markdown("*Manually modify the underlying framework logic.*")
with gr.Row():
load_hard_btn = gr.Button("Load Expert Suggestion", variant="secondary", size="sm")
hard_mods = gr.TextArea(label="Policy Mods (JSON Array)", value="[]")
hard_outcomes = gr.TextArea(label="Projected Impact (JSON Dict)", value="{}")
hard_just = gr.TextArea(label="Strategic Rationale", placeholder="Comprehensive reasoning...")
hard_think = gr.Textbox(label="Agent Reasoning (CoT)", placeholder="Explain your logic...")
def load_hard():
return (
'[{"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."}]',
'{"fraud_rate": 0.15, "revenue_velocity": 0.20, "seller_trust": 0.10}',
"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.",
"I am optimizing the framework to reduce false positives for trusted sellers while tightening the manual review net for high-risk categories."
)
load_hard_btn.click(load_hard, outputs=[hard_mods, hard_outcomes, hard_just, hard_think])
step_btn = gr.Button("Execute Strategic Step", variant="primary")
# Logic β lightweight sync (NO reset on tab/radio change)
def sync_from_mode(mode):
"""Only update the dropdown to match the radio. No environment reset."""
t_id = "task_easy"
if mode == "propose_new_rule": t_id = "task_medium"
elif mode == "evolve_policy": t_id = "task_hard"
return t_id
def sync_from_tab(evt: gr.SelectData):
"""Only update dropdown + radio to match the tab. No environment reset."""
mapping = {0: ("task_easy", "propose_clarification"), 1: ("task_medium", "propose_new_rule"), 2: ("task_hard", "evolve_policy")}
t_id, mode = mapping.get(evt.index, ("task_easy", "propose_clarification"))
return t_id, mode
# Event Listeners
reset_btn.click(handle_reset, inputs=[task_id], outputs=[corpus_table, policy_display, best_score_disp, steps_left_disp, episode_disp, corpus_count_disp, reward_plot, reward_outcome_disp, raw_json_box])
# Lightweight Sync: Radio -> Dropdown (instant, no reset)
action_mode.change(
sync_from_mode,
inputs=[action_mode],
outputs=[task_id]
)
# Lightweight Sync: Tab -> Dropdown & Radio (instant, no reset)
action_tabs.select(
sync_from_tab,
outputs=[task_id, action_mode]
)
step_btn.click(
handle_step,
inputs=[
task_id, action_mode,
easy_term, easy_def, easy_just, easy_think,
med_domain, med_rule, med_scope, med_just, med_think,
hard_mods, hard_outcomes, hard_just, hard_think
],
outputs=[corpus_table, policy_display, best_score_disp, steps_left_disp, episode_disp, corpus_count_disp, reward_plot, reward_outcome_disp, raw_json_box]
)
return demo
# Mount Gradio at module level (required for Gradio queue/WebSocket to work)
try:
custom_demo = build_custom_ui()
app = gr.mount_gradio_app(app, custom_demo, path="/dashboard/")
print("[INFO] PolicyEvolver Dashboard mounted at /dashboard/")
except Exception as e:
print(f"[WARNING] Failed to mount Gradio Dashboard: {e}")
def main():
# Sync with Hugging Face and local requirements
uvicorn.run("server.app:app", host="0.0.0.0", port=8000, reload=False)
if __name__ == "__main__":
main()
|